4 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
Jason 357c904d1b Adaptive Music v0.8.1 combat automation fixes
Validate and generate manual release / package (push) Waiting to run
2026-12-05 13:37:05 -05:00
Jason 95b0427aa1 Adaptive Music v0.8.0 release candidate
Validate and generate manual release / package (push) Waiting to run
2026-12-05 09:40:14 -05:00
60 changed files with 6527 additions and 418 deletions

No files matched your search

+76 -36
View File
@@ -1,4 +1,4 @@
# Adaptive Music architecture — 0.7.2
# 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
@@ -18,9 +18,12 @@ reads account-authorized music providers. The official pinned Sendspin SDK gener
one X25519 identity for the campaign, GM user and MA origin. Its identity, pairing
storage, catalog key and name are encrypted in local IndexedDB with a non-extractable
AES-GCM key. The key is stored in the same browser; this does not protect against
trusted-origin scripts or theft of the complete browser profile. The token is never
persisted. Failed attempts retain private inputs in tab memory; changing the MA
origin never reuses its token or identity.
trusted-origin scripts or theft of the complete browser profile. A GM can opt in
to a separate encrypted device record with the MA token, address, receiver name
and reconnect preference. Receiver records exclude credentials. Both records are
scoped to the Foundry origin, world and user. Without opt-in, failed attempts
retain private input in tab memory. A different MA origin uses separate credentials
and receiver identity.
The logged-in GM account can retain an AES-GCM envelope containing the last
successfully connected MA address and receiver name in a Foundry User Setting.
@@ -32,6 +35,9 @@ Connect audio first authenticates the `/ws` API session, then authenticates
`/sendspin` using that token and the SDK-generated client ID. MA 2.10.6 associates
this new web receiver with already-authenticated API sessions for the token. The
same API session must therefore survive pairing, catalog reads and playback.
MA 2.10.6 associates all API sessions carrying the same restricted token with the
last Sendspin browser receiver to connect using it. Concurrent receivers need
separate tokens. Loss of receiver access stops automation without retargeting.
`sendspin/pair_web_player` pairs only this identity to the calling account. Noise
activation and clock synchronization precede exact ID/name/provider/topology checks.
During startup, a successful null queue lookup is retried briefly on the same
@@ -45,18 +51,22 @@ account-authorized playlist tracks become opaque HMAC references bound to the st
catalog key and campaign. New references use a separate key derived from the MA
token, MA origin and campaign so the same authorized catalog resolves on another
browser. A browser with its original receiver vault still resolves legacy IDs.
Saving that scene again writes the new reference. Scene/world flags hold opaque
references. Live connections still depend on the active GM browser and its audio
context. Disconnect stops the session and clears the in-memory token.
Saving that scene again writes the new reference. Scene and world flags hold opaque references. The active GM browser and its audio
context host the live connection. Disconnect ends that session and pauses automatic
reconnection.
## Audio and listeners
The pinned official SDK negotiates PCM, performs Noise and time synchronization,
and decodes audio. A bounded Web Audio scheduler accepts the normal approximately
four-second stream-ahead window (six-second ceiling, 512 nodes and 2 MiB of decoded
buffers). Timestamped partial clears trim only affected audio. Full clears and ends
stop the stream. A software gain and output meter feed the GM speakers and a single
MediaStreamDestination track for listener distribution.
and decodes audio. A bounded Web Audio timeline anchors a packet run to the local
audio clock and advances it by each rendered chunk’s length. The browser converts
sample rates from each AudioBuffer’s input rate. A 120 ms startup cushion and
bounded 0.1% rate correction absorb jitter and drift. The queue allows eight
seconds of server lead, up to 768 active nodes and 8 MiB of decoded audio. It
counts source timestamp gaps and overlaps separately from late drops and local
underruns. Timestamped partial clears trim only invalid audio. Separate
transition and volume gains feed the GM output and one MediaStreamDestination
track for listener distribution.
User document public keys authenticate ephemeral ECDH/AES-GCM invitation delivery.
Private keys stay in memory. Invitations are bound to world, sender, recipient,
@@ -66,42 +76,72 @@ never PCM over that socket. Firefox’s session-level SDP direction default is
correctly overridden by the sole audio media direction. Offers remain recvonly;
answers remain sendonly. Video, data and injected sender media are rejected.
Up to eight listeners negotiate automatically. Invitations renew after 20 minutes
and expire after 30. Failed negotiation times out after 20 seconds; disconnected
peers are revoked after 10 seconds and the 15-second reconciliation loop can issue
fresh invitations. One user gesture unlocks browser audio when required. A stable
HTMLAudioElement pumps the incoming remote track; Web Audio provides an optional
activated playback path. Default ICE has no public STUN/TURN service. WAN delivery
requires a viable existing ICE route and is not inferred from local tests.
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. Foundry's connection and User document events reconcile listeners
without replacing the GM transport. One user gesture unlocks browser audio when
required. A stable HTMLAudioElement and optional activated Web Audio path play
the incoming track. Each listener's local output applies their saved mute and
volume settings downstream of WebRTC. Default ICE uses no public STUN/TURN service.
The GM's personal monitor gain sits on the local output branch after the split
to the listener stream. Campaign volume remains upstream of that split.
## Transitions and recovery
Manual override/silence > explicit boss > started combat in the active scene >
ambient > world default > silence. No system actor schemas are used. The existing
Manual override/silence > combatant boss override > designated encounter boss cue
> started combat in the active scene > ambient > world default > silence.
An explicit combat scene takes precedence. An unlinked encounter with
scene-bound combatants applies to their scenes. An unlinked encounter with no
scene-bound combatants is global. Begun, active encounters are resolved through
post-operation combat and combatant hooks. No system actor schemas are used. The existing
serialized controller checks campaign/session/generation and current authority.
A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
server-side distributed fence or seamless handover protocol.
Authority requires one active full Gamemaster. Foundry's Assistant GM role is
eligible for listener audio. A Web Lock excludes common duplicate tabs. Queue
commands retain their existing session and generation fences.
Every queue mutation verifies the exact dedicated target, standalone topology and
its own active queue. Signed snapshots retain ordered duplicates, index, repeat,
whole-second position and state, scoped to campaign/session/fence/generation for up
to 12 hours. Ambiguous writes latch closed and stop automation; they are not retried.
to 12 hours. An interrupted ambient snapshot can survive an excursion while its
scene's encounter remains live and the ambient reference still matches.
Ambiguous writes latch closed and stop automation; they are not retried.
MA Sendspin lacks native pause in 2.10.6, so pause retains a logical stopped-queue
snapshot and resume explicitly seeks its item. A paused restore rebuilds without
briefly playing. This logical pause state is memory-only.
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.
Reconnecting to a remembered owned receiver can attach to its existing queue
without replacing it. Automation remains paused for explicit resumption when that
queue is nonempty. Crash/reload cannot guarantee restoration of an interrupted
ambient stack or logical pause position. No crossfade or independent simultaneous
layers is implemented with the single upstream queue. Native playback uses only
explicitly owned playlists; effects and AmbientSound remain untouched.
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
ambient interruption stack and logical pause. Adaptive Music provides sequential
fade-out and fade-in using its one MA queue. True overlap between arbitrary
scene playlists would require two independently managed streams at once.
Scene Configuration and the Playlists sidebar use Foundry render hooks. The
director displays virtual catalog items for assignment and saves only opaque
references into scene flags. The GM's native Combat Tracker stores the encounter
designation on the Combat document and reflects the current playback mode.
No Foundry Playlist document is created for an MA
item. The module cedes a scene with a configured native soundtrack to Foundry.
Only explicitly owned native fallback playlists can be managed by Adaptive Music.
Positional audio and other native effects stay under Foundry’s control.
## Verification boundary
The installed v0.7.0 module was tested in a logged-in Foundry v14.371 development
world through the private Nginx route. The GM connected to MA and two players
received audio using Foundry’s module socket for signaling. The test also exercised
real combat hooks, ordered ambient restoration, and User document permissions.
Earlier browser tests used a Playwright source overlay. The original Mac path,
physical-device audibility, invitation renewal and WAN behavior remain unverified.
world through the private Nginx route. The v0.8.0 browser preview used validated
ZIP assets with the real development world, MA and two listeners. It exercised
Foundry module-socket signaling, scene and combat hooks, ordered ambient
restoration, real playback controls and User document permissions. The operator
later verified installed v0.8.0 audio in Chrome on macOS and at a remote WAN
listener. macOS Firefox connectivity remains unresolved. See [TESTING.md](TESTING.md).
+65
View File
@@ -1,5 +1,70 @@
# Changelog
## 0.8.3 — floating music controls
- Add a draggable, collapsible Adaptive Music bar for players and the GM.
Personal mute and volume share the existing listening preferences.
- Give the GM separate campaign volume, track skip, and one-click access to
playback and overrides. The GM's personal listening level affects only their
own Music Assistant output.
- Add **Pause all music** and **Play all music** for Adaptive Music. The
campaign pause holds scene and combat automation until Play is selected.
## 0.8.2 — multiplayer continuity and player listening
- Use Foundry's full Gamemaster role for Music Assistant controller authority.
Player, Trusted Player and Assistant GM connections leave the existing host
session and catalog running.
- Reconcile listener connections on Foundry login, logout and User updates.
Late listeners join the existing WebRTC stream, using browser audio activation
where required.
- Add **Campaign audio** to the player Playlists sidebar. The existing listening
window now shows status and offers personal mute and volume, saved per Foundry user.
## 0.8.1 — Combat Tracker cues and Firefox diagnostics
- Follow the combatants' token scenes when Foundry creates an unlinked
encounter through its native token HUD. Switch after combat starts, keep
the cue across initiative changes, and restore ambient when combat ends.
- Add **Boss encounter** to the GM's native Combat Tracker. Beginning a
designated encounter uses the scene's default boss cue. The tracker and
Playback panel show the current music mode and expose a way back to
automation while a manual override is active.
- Retain an interrupted ambient position across a scene excursion while
the original encounter remains active.
- Record the last failed Connect action's timestamp, error code and known setup
stage in the copyable connection report.
- Record each unauthenticated WebSocket probe's duration and the site permission
state observed after that route completes. Keep opaque upgrade failures
distinct from a confirmed CSP block.
- Record installed v0.8.0 macOS operator acceptance and the Firefox connectivity
failure. The macOS Firefox fix is still awaiting diagnosis.
## 0.8.0 — playback stability and native Foundry controls
- Keep Sendspin PCM packet boundaries contiguous in Web Audio. Track source gaps,
overlaps, late packets, buffer overruns and underruns separately.
- Separate API and Sendspin connection failures, distinguish local network
permission hints from transport failures, and identify loss of dedicated queue
rights when Music Assistant reassigns a restricted token’s browser receiver.
- Remember a revocable Music Assistant token on an opted-in trusted GM browser.
Reconnect on world entry, support a deliberate disconnect, and forget the saved
device credential independently of the encrypted Foundry account address.
- Assign ambient, combat and boss music in native Scene Configuration. The
Playlists sidebar shows a draggable Music Assistant catalog for GM assignments.
- Open the live transport controls from the token toolbar or Playlists sidebar.
Use volume, pause/resume, seek, skip, stop, repeat, manual override and return to scene
music. Music Assistant playlist changes use sequential fade-out and fade-in.
- Coalesce duplicate hook updates, continue shared playlists across scene changes,
and keep connected listener media running when its initial signaling invite expires.
- Refresh the open Playlists sidebar after connecting, preserve its expanded state,
and keep an ambient snapshot when the same playlist also serves as a combat cue.
Restore a finished static queue without briefly restarting playback.
- Include the Mac acceptance checklist and handoff in the release bundle. Record
whether the packaged source came from a clean checkout or includes working-tree
changes, and validate the complete module ZIP inventory and SDK provenance.
## 0.7.2 — account-scoped connection setup
- Remember the Music Assistant address and receiver name in an encrypted Foundry User Setting. Enter the MA token to unlock the saved address and connect in a new browser session.
+316
View File
@@ -0,0 +1,316 @@
# 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. The remote-free `.local/v080-release-checkout` has the prior candidate
on `v0.8.2-multiplayer` and the floating controls on `v0.8.3-music-bar`.
Its `main` branch retains `1ed6b4c`.
The operator reported Gitea published v0.8.0 from `95b0427`. That object
is absent in both local Git databases. The published commit's ancestry
can be checked if its Git object is supplied offline.
A read-only check of the authorized private Foundry route confirmed the
installed manifest was v0.8.0 and all 28 runtime files matched `1ed6b4c`.
A later check matched all 28 installed v0.8.1 runtime files to `251a019`.
The v0.8.2 archive is built from a clean checkout and its source is compared
against its local commit. Read its exact commit in
`dist/releases/v0.8.2/release.json`. Gitea access and production deployment
are outside this work.
## Installed v0.8.0 macOS acceptance
- **Operator pass:** Chrome connectivity, credentials after quitting and
reopening Chrome, automatic scene playlist activation, background-tab audio,
remote player audio over WAN, and smooth transitions. The operator heard no
stuttering or crackling during their session.
- **Operator fail:** macOS Firefox connectivity.
- **Combat follow-up:** assigned battle music worked when used as ambient,
while normal combat left ambient playing. The operator could not find
the boss designation. The operator passed combat, restoration, boss and
manual controls with the corrected v0.8.1 candidate.
## v0.8.1 native combat correction
The native token HUD created an unlinked encounter on Foundry 14.371 and D&D 5e
6.1.2. Installed v0.8.0 ignored it even after the native tracker started round 1.
Use the Combatant token scene when the encounter has no explicit scene. The
tracker now has a GM-only **Boss encounter** option and shows the playback mode
and **Return to automation** for a manual override. The same combat and boss
assignment can change mode without restarting the queue. Use distinct playlists
to verify the audible changes.
The authorized GUI run and its hook trace live under ignored
`.local/v081-combat-gui-*`. See [TESTING.md](TESTING.md) and
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the reproduced lifecycle and steps.
The Chromium browser preview used three distinct cues and restored ambient at
30, 33 and 46 seconds across normal, boss and manual-override encounters.
It verified turn and round continuity, End Combat cancellation, scene changes,
and returning from the manual hold. The server still reported v0.8.0 during
the previews. Headed Firefox repeated the normal combat lifecycle against the
same runtime and restored ambient at 9 seconds.
## v0.8.1 Firefox investigation
- The two WSS routes opened with HTTP 101 in Mozilla Firefox 161.0.1 on Ubuntu
from the anonymous Foundry origin and the MA origin using the native
WebSocket. Trusted TLS and the authorized private route were retained.
- The isolated stock-Firefox policy test reproduced enforced CSP, report-only
CSP, a server-side Origin rejection and a mismatched TLS certificate. Browser
script saw Origin rejection and TLS rejection as opaque upgrade failures.
- The candidate improves the token-free report with manual Connect failure
stage and time, per-route duration and post-probe permission states.
Audio, credential storage and the authenticated transport are outside the
change. The original macOS failure needs the browser-side capture described
in [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md#capture-the-firefox-failure).
- The private stock browser, scripts and raw reports under `.local/v081-*`
are test-only. See [sanitized v0.8.1 evidence](evidence/v0.8.1-live.json).
## Historical v0.8.0 audit checkpoint
- The development world keeps **Christmas — Adaptive Music demo** active with
Christmas music assigned. **Dûr-Khazrak — Adaptive Music demo** has distinct
ambient, combat and boss cues and a prepared, unstarted encounter with the
Dûr-Khazrak Champion. Its ambient uses a development playlist as a stand-in.
The authorized catalog contained no identifiable dwarven soundtrack.
- The preview host reported v0.7.2 during the automated audit. The operator
subsequently installed v0.8.0 and carried out the checks above.
- Automated release regressions passed with 110 JavaScript and 17 Python
tests. The dependency, repository and upstream provenance checks passed.
The updated Chromium, Firefox and Linux WebKit credential fixture closed
and reopened persistent browser profiles and tested rejection by a synthetic
MA auth endpoint after simulated revocation. The real preview verified
same-receiver auto-attachment after a page reload, Disconnect and Forget.
- MA-side revocation with a disposable token and Mac sleep/wake still need
operator acceptance. The focused Ubuntu Firefox background check measured
listener audio before switching tabs and could not establish that the GM
page became hidden.
The package targets Foundry VTT 14.371 and MA 2.10.6. It uses the pinned Sendspin
SDK and browser-hosted audio. The user authorized the existing test accounts and
dedicated MA token for the private development-world acceptance runs on
December 4. See [the evidence](evidence/v0.8.0-live.json),
[the verification guide](TESTING.md) and [the contributor rules](AGENTS.md).
| Work | Candidate implementation |
| --- | --- |
| AM-005 browser compatibility | Staged, token-free transport diagnostics. Live Chromium and Firefox use the private development route. Linux WebKit provides an engine check. |
| AM-007 audio continuity | A bounded sample-contiguous PCM timeline and persistent established WebRTC media across signaling expiry. Live measurements count silent render blocks, verify rate and reject prolonged silence. |
| AM-008 trusted-device credentials | Explicit browser-local AES-GCM retention with reconnect, Disconnect and Forget Credentials. Account address and portable references retain their v0.7.2 formats. |
| AM-009 native Foundry integration | Native Scene Configuration fields, draggable MA catalog, world/boss defaults and real scene/combat hooks. Native soundtracks remain under Foundry's controller. |
| AM-010 gameplay controls | Token toolbar and sidebar launch points, transport, volume, repeat, manual override and return to scene music. The one dedicated MA queue uses sequential fades. |
## Results and open acceptance
- The original Firefox report is preserved under
`.local/v080-original-firefox-soak.json`. It recorded 1,800 wall-clock
measurement seconds and successful ambient restoration at 37 seconds.
Both listeners then recorded about 763 seconds of continuous terminal
silence and the Stop/Enable check failed. The first ZIP preview passed initial
ambient playback but timed out selecting Repeat. The repeat field now has an
explicit accessible name for Firefox and for the harness.
- The first Chromium GUI review connected to MA, then timed out in the sidebar
and scene configuration workflow. The refreshed sidebar updates an existing
render and preserves its expanded state. The review now reports individual
stages, verifies the pointer drag and measures both listeners. Current raw
reports and logs are in `.local/foundry-v080-review-chromium.json`,
`.local/v080-audit-chromium-review.log` and
`.local/v080-audit-firefox-soak.log`. Match the UTC start time and ZIP hash
before attributing results to a given run.
- Chromium's headless run exercised the real Foundry native UI, including
pointer drag, two scene assignments, both controls launch points, combat,
a boss override and ambient restoration. A first combat choice was rejected
during playlist preparation. For a reproducible review, set
`AM_REVIEW_PLAYLIST_INDEXES` to the three comma-separated zero-based catalog
entries that passed preparation in `.local/v080-catalog-readiness.json`.
- The corrected Firefox continuity run started at 00:29 UTC on December 5 and
passed 1,800 measured seconds, including ordered restoration at 37 seconds,
listener Stop/Enable and reload. The development-world cleanup passed. The
Chromium review uses the same tested ZIP and runtime asset hash. See the
sanitized JSON for phase measurements and the raw report under `.local/`.
- The Chromium review passed native scene assignment and pointer drag, both
playback launchers, combat and boss cues, ambient restoration at 10 seconds,
manual override and return, pause, resume, seek, skip and stop. It reconnected
the same receiver after reload without replacing its queue. Disconnect and
Forget Credentials both prevented automatic reconnection after another reload.
The final headed review disabled Playwright focus emulation in a private test
tool copy. A real cover tab hid the GM document for 12 seconds. Its audio clock
advanced, the GM output analyser measured audio, and both listeners continued
receiving audio. Earlier trials with focus emulation kept the page visible.
See `.local/v080-normal-visibility-playwright/focus-fixture.json` for the tool
modification and hashes.
- The isolated WebRTC fixture passed signaling expiry and revocation in
Chromium and Firefox. Linux WebKit's default ICE did not connect. Forced
relay via local coturn passed audio and expiry/revocation without microphone
access. The extracted binary and signed-package hashes are in
`.local/v080-turn-fixture/`. Future runs can set `AM_LOOPBACK_TURN_CONFIG`
to a private fixture grant and use `--webkit-only`.
- These v0.8.0 automated browser previews exercised real Foundry and MA with
archive assets while the server reported v0.7.2. See the separate installed
v0.8.0 manual results above.
The bundle is locally staged under
`dist/releases/v0.8.0/`. The install ZIP is `adaptive-music.zip` and the
outer archive also includes complete source, checksums, licenses and evidence.
The prior review restored the development world's active scene, automation
setting and account connection and removed temporary combats. The final audit
prepared the two demo scenes and activated Christmas for the operator.
The prior hostname override was restored from its saved backup. The focused
Firefox check used a process-local DNS mapping with normal TLS validation.
## Findings and source map
- MA 2.10.6 assigns all authenticated API sessions using a restricted token to
the newest Sendspin browser receiver using the same token. This was directly
reproduced when the native MA reference player and the Foundry receiver shared
the test token. Foundry kept receiving audio but `players/get` returned
`InsufficientPermissions` (22), preventing combat control. Run those tests
serially, or use separately authorized tokens. The matching upstream code is
`set_sendspin_player_for_token` in MA's tagged webserver controller. Adaptive
Music keeps its original API session and reports queue-rights loss in
`src/audio/gm-host.mjs`, `src/providers/ma/websocket.mjs` and
`src/foundry/connection-wizard.mjs`. This explains the reproduced permission
failure. The cause of the Mac Firefox failure remains open.
- The v0.7.2 per-packet time mapping causes edge gaps and overlaps when Web Audio
time advances in render quanta. The rendered-tone fixture detected 86–97
short dropouts per seven-second measurement across the tested rate pairs and
engines. The new scheduler detected zero in the same fixture. A prior
two-minute live Firefox interval also detected zero short digital dropouts at
the GM and both players. See `src/audio/pcm-timeline.mjs`,
`src/audio/gm-host.mjs`, `src/audio/peer-audio.mjs` and
`scripts/browser-continuity-worklet.mjs`. Natural track silence, an intentional
transition, a network concealment event and a scheduler gap are different signals.
- A headed installed-baseline Chromium attempt authenticated and paired but timed
out waiting for a newly registered MA queue. Retain that result alongside the
operator’s working Mac baseline. Setup already retries a successful null queue
lookup briefly. Check `src/providers/ma/client.mjs` and `src/audio/gm-host.mjs`
if it recurs.
- Credential lifecycle and auto-reconnect are in `src/foundry/receiver-vault.mjs`,
`src/foundry/account-connection.mjs`, `src/foundry/module.mjs` and
`src/foundry/connection-wizard.mjs`. The browser profile and enabled same-origin
modules are trusted. The token cannot follow a GM account to a different
browser without that GM entering it there. Token rotation can require
reassigning older token-derived playlist references.
- Native UI and automation are in `src/foundry/configuration.mjs`,
`src/foundry/music-editor.mjs`, `src/foundry/runtime.mjs`,
`src/core/scene-music.mjs` and `src/core/controller.mjs`. Playback UI is in
`src/foundry/playback-panel.mjs` and `src/foundry/setup.mjs`. True simultaneous
crossfade between arbitrary playlists would require both streams to be
independently available at the same time. MA track-to-track crossfade within
one queue is separate. GM logout or closing the last GM tab ends live playback.
## Environment and commands
Use Ubuntu, Python 3, Node 24.23.0 or newer within the supported release line,
and the existing Playwright tools. System `node` on this machine is Node 18.
The development browser tools and browser binaries are ignored local paths.
The headless tests exercise isolated browser APIs. The headed tests use Xvfb with
software GL for the actual Foundry graphical workflows.
```sh
export PATH="/home/ubuntu/.nvm/versions/node/v24.23.0/bin:$PATH"
export PLAYWRIGHT_BROWSERS_PATH="$PWD/.local/browsers"
npm test
python3 -m unittest discover -s tests -v
python3 scripts/audit_repository.py
python3 scripts/verify_upstream.py
npm audit --json
node scripts/check_setup_browser.mjs
export AM_PLAYWRIGHT_MODULE="$PWD/.local/dev-browser-tools/node_modules/playwright/index.mjs"
export LIBGL_ALWAYS_SOFTWARE=1
xvfb-run -a node scripts/check_pcm_continuity.mjs --headed --webkit
node scripts/check_device_credentials_browser.mjs --webkit
# Run the desktop review after any background playback test has exited.
umask 077
AM_PLAYWRIGHT_MODULE="$PWD/.local/v080-normal-visibility-playwright/node_modules/playwright/index.mjs" \
xvfb-run -a -s '-screen 0 1600x1050x24 +extension GLX' \
node scripts/check_foundry_private_route.mjs --headed --playback --package-preview dist/releases/v0.8.0/adaptive-music.zip --review \
> .local/v080-candidate-chromium-review.log 2>&1
# Start another soak when changes require a retest.
xvfb-run -a -s '-screen 0 1600x1050x24 +extension GLX' \
node scripts/check_foundry_private_route.mjs --headed --firefox --playback --package-preview dist/releases/v0.8.0/adaptive-music.zip --continuity \
> .local/v080-candidate-firefox-soak.log 2>&1
# Build the current candidate from the clean local release checkout.
python3 .local/v080-release-checkout/scripts/release.py --output "$PWD/dist/releases/v0.8.3"
python3 scripts/release.py --validate dist/releases/v0.8.3/adaptive-music.zip
(cd dist/releases/v0.8.3 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.3.zip.sha256)
```
The headed browser tests use the authorized private Nginx HTTPS route and retain
normal TLS validation. Firefox and WebKit used a temporary Ubuntu hostname
override which has been restored. After an authorized future test, restore an
identical temporary override with
`cmp -s /etc/hosts .local/v080-hosts.new && sudo -n install -m 0644 -o root -g root .local/v080-hosts.before /etc/hosts`.
If the comparison fails, preserve subsequent edits and remove only the test
change marked `adaptive-music-test-v080` using the backup as a reference.
## Authorization and private configuration
- Use the dedicated Foundry development world and the three test accounts listed
in the ignored development-world configuration. The runner checks whether the
GM account is available before joining.
- Use only the authorized private HTTPS proxy and the dedicated MA test credential
and receivers. GM authorization covers isolated development scenes, test
combatants, playlists, diagnostics, receiver creation and playback. Leave
production campaigns, core, other modules, network infrastructure and
household MA/Sonos targets untouched.
- `.local/live-environment.json` contains the private HTTPS origins and proxy
address. `.local/foundry-development.json` holds the test-world/account mapping.
`.local/ma-token` holds the dedicated token. The private runners read them
directly and load the token through `loadMAToken('.local')` from
`gateway/private-config.mjs`. Pass the directory or file path to tools and
retain the value in process memory. Avoid printing configuration values or raw
auth frames. Do not paste them into an Ollama prompt, transcript or issue.
- Keep `.local/` mode 0700 and private input files mode 0600. Use sanitized
aggregate evidence in Git. Local browser profiles, raw reports, screenshots
and route backups belong under `.local/`. Run the repository audit before
staging or committing anything newly generated.
- Keep source commits and bundles local. Do not access, fetch from, push to,
or publish a release on the Gitea repository.
+100 -29
View File
@@ -1,4 +1,4 @@
# Install and connect — 0.7.2
# Install and connect — 0.8.3 candidate
## Normal setup
@@ -7,34 +7,56 @@
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**,
enter the private **HTTPS Music Assistant server address** and the dedicated
account’s access token. Use the server origin and select **Connect** to create or
reconnect the campaign receiver, pair it, and load playlists.
3. Select **Choose scene music**. In **Scene Music**, choose the scene and save its
ambient, combat, boss and native fallback assignments. You can also set world
defaults and individual boss overrides.
4. Open **Playback** to enable automation, see the current track and listeners, or
adjust campaign volume and control the dedicated MA queue.
5. Players connect automatically. If a browser requires activation, open Campaign
audio and select **Enable Audio** once. Keep one audio tab per account.
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
**Connect** to authenticate, provision the receiver and load the catalog.
3. Open a scene’s native **Configure Scene** window. Assign music under
**Adaptive Music** and select **Save assignments**. The Playlists sidebar
also lists draggable MA catalog entries for the scene’s playlist fields.
Use static playlists with available tracks. MA can list an entry whose
tracks are unavailable when Adaptive Music prepares it for playback.
Use the setup window’s **Scene Music** tab for world defaults and optional
combatant-specific boss overrides. For a boss encounter, check **Boss
encounter** in the native Combat Tracker before clicking **Start Combat**
to use the scene’s default boss music.
4. Open **Adaptive Music controls** from the token toolbar or Playlists sidebar.
Enable automation once. The controls show the current track, active playlist
when known, volume, position and listeners. Skip, pause, resume, stop and
repeat control the dedicated queue. The Playback panel and Combat Tracker
show the current music mode. Select **Return to automation** in the tracker
or **Return to scene music** in Playback to clear a manual override.
5. Players, Trusted Players and Assistant GMs can open **Campaign audio** in the
Playlists sidebar. Select **Enable Audio** if the browser requires activation.
Mute and listening volume affect only that user's sound. Foundry saves those
preferences for the user. The GM can use **Enable GM audio** in Playback after
an automatic connection.
After a successful connection, the GM’s Foundry account remembers the encrypted
server address and receiver name. On another computer or after reload, enter the
same MA token and select **Connect** to unlock the saved address. Reload and
**Disconnect** clear the in-memory token. If the token changes, enter the server
address with the replacement token. **Advanced → Forget saved connection** clears
the account record. The receiver identity remains encrypted in its browser vault.
The opted-in browser can reconnect on world entry. **Disconnect** ends its live
session and pauses automatic reconnection until you connect again.
**Forget Credentials** also removes the stored token. Reload without retention
requires the token again. The Foundry account remembers an encrypted address and
receiver name. On a different browser, use the same token to unlock the account
record and choose whether that browser may remember it. For a replacement
token, enter the server address again. Revoke obsolete tokens in MA’s Profile
settings. **Advanced → Forget saved connection** clears the encrypted account
record in addition to the device credential.
New MA playlist assignments resolve across browsers using the same MA token and
origin. To update a legacy assignment, connect from the browser that originally
saved it and save the scene again. From a different browser, reselect its playlists.
Keep the active GM browser open for live MA playback and listener forwarding.
MA 2.10.6 assigns a restricted token’s API sessions to its most recently connected
web receiver. Use a different token for a simultaneously running native MA web
player. New MA playlist assignments are portable across browsers with the same
token, origin and Foundry world. A legacy reference can be migrated by saving
its assignment again in the browser that created it. Another browser can reselect
the playlist. A replaced token can require reassigning the old references.
Reconnecting to an owned nonempty queue preserves it. Enable automation in Playback
when ready to resume scene control. Unknown mutation outcomes stop automation and
require review. Pause preserves a stopped queue’s index and position for the active
GM session.
Keep the GM tab open while serving audio. The setup window is independent of
playback. Automatic reattachment preserves a populated queue until the next
scene or combat music cue. You can also select **Return to scene music** to take
control immediately. If you use Adaptive Music for a scene, leave the scene’s
native soundtrack playlist unset. Foundry still controls sound effects and
AmbientSound documents. Sequential fades use one dedicated queue, and pause
remembers the position for the active GM session.
## Connection diagnostics
@@ -54,6 +76,7 @@ keys or playlist titles. No browser developer console is required.
| Frames arrive but audio is suspended | Select Enable GM audio or the player’s Enable Audio once. |
| Listener fails negotiation | Check its diagnostics and existing network/ICE route. It is automatically retried after timeout. |
| MA error 2 on playlist startup | MA could not find playable media even if catalog metadata exists. Check that content/provider in MA; this is separate from a WebSocket upgrade failure. |
| Receiver queue access withdrawn | Ensure another web receiver is not using the same MA token. Review dedicated receiver access before reconnecting. |
| Unknown queue write | Review the dedicated queue, then deliberately reconnect; no blind retry occurs. |
Use trusted HTTPS for Foundry and private HTTPS/WSS for both MA `/ws` and `/sendspin`.
@@ -62,19 +85,67 @@ Keep MA raw-frame VERBOSE logging disabled. No public API/proxy, core modificati
additional container, service, VM or LXC is required by this module. A direct HTTP MA
address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
remote players still need a viable existing WebRTC path.
If your listeners need an existing private relay, enter it under Connection →
Advanced. Relay credentials expire and stay in the active GM tab. Enter a fresh
relay credential after reloading the GM tab.
See TESTING.md for private-route evidence and the outstanding installed, Mac and WAN checks.
See [TESTING.md](TESTING.md) for private-route evidence and
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the Mac checklist.
## Install the candidate on an isolated development instance
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 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
development-only `Data` directory and the extracted release directory.
Stop the development instance with its normal service controls before swapping
the module directory.
```sh
(
set -eu
FOUNDRY_DEV_DATA='/absolute/path/to/development-only/Data'
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-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
mv "$FOUNDRY_DEV_DATA/modules/adaptive-music" "$AM_STAGE/previous-adaptive-music"
fi
if ! mv "$AM_STAGE/adaptive-music" "$FOUNDRY_DEV_DATA/modules/adaptive-music"; then
if [ -d "$AM_STAGE/previous-adaptive-music" ]; then
mv "$AM_STAGE/previous-adaptive-music" "$FOUNDRY_DEV_DATA/modules/adaptive-music"
fi
exit 1
fi
printf 'Rollback directory: %s\n' "$AM_STAGE"
)
```
Restart the development instance, launch the development world and confirm
**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
`Data/modules/adaptive-music`.
## Manual Gitea publication
The existing stable manifest and versioned download mechanism is preserved:
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
- v0.7.2 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/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.7.2`, 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
+158 -14
View File
@@ -1,10 +1,148 @@
# Adaptive Music progress — 0.7.2 staged acceptance
# Adaptive Music progress — 0.8.3 music bar
Standalone module work now includes automatic campaign receiver provisioning and
account-bound pairing, remembered encrypted browser-local identity, memory-only token
retention/retry, scene assignments, listener bootstrap, guarded transitions and queue
restoration. Existing Gitea URLs/manual release mechanism are preserved. No Git host
was accessed and no production infrastructure/core versions were changed.
## v0.8.3 floating controls
The floating bar gives players a direct route to activation, local volume and
mute. The GM has independent local listening controls, shared campaign volume,
track skip and a shortcut to the detailed Playback window. Campaign pause
holds automated music cues and preserves the active queue's position. Play
selects the current cue when it changed during the hold.
Development-world acceptance is pending. The test route returned Foundry's
no-active-game message. See [TESTING.md](TESTING.md) for the automated scope
and [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the installed checks.
## v0.8.2 release-blocking regression
The operator passed v0.8.1 combat, initiative, boss, restoration, manual controls
and audio quality. They then reported that a late join stopped the host and
emptied the catalog. Development GUI tests kept audio running for Player and
Trusted Player, and reproduced the failure with an Assistant GM while the
original GM's Foundry socket stayed connected. The v0.8.1 host predicate used
the broader Foundry `isGM` flag for exclusive Music Assistant authority.
The v0.8.2 predicate considers the full Gamemaster role and treats the
Assistant GM as a listener for this module. Join and logout reconciliation
uses Foundry's connection event as well as User updates. Campaign audio
offers per-user mute, volume and status through one existing listening window.
Independent Chrome and Firefox sessions in the development world passed late
and simultaneous joins. All three regular listeners received decoded audio, and
the Assistant GM's join and departure kept the host playing. Player-side mute
and volume affected only that player and persisted across logout and login.
Combat, Boss, Ambient restoration, scene changes and manual playback passed
with three listeners connected. Across six minutes of playback the GM and
all listeners had measurable audio at 30 of 30 checks. The GM's remembered
credential reopened the same receiver with the queue intact, and all three
listeners recovered. The v0.8.2 bundle is staged under `dist/releases/v0.8.2/`.
See [TESTING.md](TESTING.md) for scope and [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md)
for the exact installed build. The separate macOS Firefox connection failure
still needs the operator's private-route diagnostics.
## Installed v0.8.0 manual acceptance
The operator confirmed on macOS that Chrome connected and retained credentials
after a full quit and reopen. Automatic scene playlist activation, background-tab
audio, WAN player audio and smooth transitions passed. The operator reported
that stuttering and crackling were resolved in their testing. Firefox
connectivity failed. A follow-up confirmed the battle playlist played when
assigned to ambient, while tracked combat left ambient unchanged. The operator
could not find boss designation. The operator subsequently passed the corrected
workflow in v0.8.1.
## v0.8.1 combat correction
The installed v0.8.0 reproduction used the native token HUD and Combat Tracker
on Foundry 14.371 and D&D 5e 6.1.2. Start Combat committed round 1 and turn 0
for an unlinked encounter with a token in the active scene. The module required
an explicit encounter scene and kept its ambient queue. The correction considers
the unlinked encounter's combatant scenes and reconciles from the committed
lifecycle. The Combat Tracker now lets the GM mark a boss encounter and return
to automation. Both the tracker and Playback panel identify the current cue.
The Chromium candidate preview verified the native tracker workflow with three
distinct playlists. Turn and round changes kept the combat cue, canceled End
Combat kept the encounter running, and confirmed end restored ambient after
normal, boss, and manual-override encounters. The scene excursion preserved the
interrupted ambient position. The manual override was visible in the tracker and
released to Combat through **Return to automation**.
The headed Firefox preview repeated the normal tracker lifecycle and restored
ambient at 9 seconds. The operator passed the v0.8.1 combat acceptance.
## v0.8.1 status
The clean local v0.8.0 release commit was reconciled against the original
workspace and the installed runtime. The original Git metadata is read-only
and the operator's published commit `95b0427` is absent locally. Both local
trees had identical source before v0.8.1 work. The installed v0.8.0 manifest
and all 28 runtime files matched the local release baseline.
Stock Firefox 161.0.1 on Ubuntu opened both private WSS routes from the
anonymous Foundry page and the MA origin. The isolated policy fixture
distinguished enforced CSP and kept Origin and certificate failures opaque.
The v0.8.1 diagnostic candidate records route timing, permissions after
the probe and the failed Connect stage without copying arbitrary error text.
The source change is confined to the connection diagnostics and their UI.
The macOS failure remains open pending the
[Firefox capture](USER-ACCEPTANCE.md#capture-the-firefox-failure).
The v0.8.1 regressions passed 115 JavaScript and 17 Python tests, plus the
Chromium, Firefox and Linux WebKit setup fixtures. Repository and upstream
verification passed. npm audit reported zero vulnerabilities. The complete
diagnostic candidate bundle is staged locally under `dist/releases/v0.8.1/`.
## Historical v0.8.0 automated audit
The operator confirmed that installed v0.7.2 plays MA audio in Chrome on a Mac.
The v0.8.0 work uses that baseline and retains the dedicated receiver architecture.
The release bundle is generated locally using the existing manifest mechanism.
The independent audit reproduced the three-engine PCM, credential and setup fixtures.
The original Firefox soak restored the ambient queue at index 0 and 37 seconds,
then ended with roughly 763 seconds of continuous listener silence. Its
listener re-enable step failed. The revised test enables repeat on the dedicated
queue and fails an interval when digital silence exceeds four seconds, rendered
frames stall or a playback meter disappears. A 30-minute timer alone never
satisfies continuity acceptance.
The corrected headed Firefox run passed 1,800 seconds in the actual development
world using runtime assets served from the validated ZIP. It restored the queue
order, track index and 37-second position. The GM and both listeners rendered
throughout the measured phases. Listener Stop/Enable and reload recovered audio.
The GM recorded zero scheduler underruns and both listener meters counted 608
near-zero runs of 0.75–80 ms in restored ambient. Their longest digital silence
was 449 ms. RTP concealment stayed flat during the measured phases.
The audit fixed catalog updates in an already rendered Playlists sidebar,
preserved the playback position when ambient and combat share a playlist,
allowed finished static queues to survive interruptions without briefly
playing on restore, and tightened receiver permission and credential recovery.
The release validator checks the complete ZIP inventory and the pinned SDK
provenance. The browser harness can serve runtime assets from that ZIP while
Foundry continues to report its server-installed version.
Chromium verified native scene assignment and dragging, both playback launchers,
combat and boss rules, ambient restoration, manual override and transport.
It reconnected the same receiver with the device credential after reload and
preserved the dedicated queue. Disconnect and Forget Credentials prevented
automatic reconnection.
The headed Chromium review verified continued audio for the hidden GM tab and
both listeners over a 12-second measurement.
The Firefox follow-up measured live listener audio before switching tabs. The
GM document continued reporting visible under automation. Firefox hidden-tab
continuity remains open.
The final audit configured **Christmas — Adaptive Music demo** and
**Dûr-Khazrak — Adaptive Music demo** as the two existing demo scenes. Christmas
is active with its seasonal MA playlist. Dûr-Khazrak has distinct ambient,
combat and boss cues and an unstarted encounter. Its ambient cue uses a
development playlist as a stand-in for a dwarven soundtrack.
The pre-commit release regressions passed 110 JavaScript and 17 Python tests.
Repository privacy and attribution, pinned upstream provenance and both npm
audit scopes passed. A three-engine Linux browser fixture verified full profile
restarts, remembered credentials, forgetting and denial after synthetic-token
revocation. Live MA-side token revocation and actual Mac browser tests remain
open.
## Defects
@@ -12,11 +150,14 @@ was accessed and no production infrastructure/core versions were changed.
| --- | --- | --- |
| AM-001 layout | Actual Foundry v14.371 ApplicationV2 at 380/640px; Chromium fixture at 380/640/1000px | Operator’s logged-in-world theme |
| AM-002 provisioning | SDK-created identity, authenticated dedicated web-receiver pairing, no normal JSON import; real MA tests | Normal installed-world flow on Mac |
| AM-003 diagnostics | Per-route upgrade/CSP checks, staged auth/pair/sync errors, output counters and copyable secret-free listener report | Original Mac failure report if it persists |
| AM-003 diagnostics | Per-route upgrade/CSP checks, staged auth/pair/sync errors, output counters and copyable GM connection report | Original Mac failure report if it persists |
| AM-004 retry retention | Tab-private draft; encrypted receiver vault; token/identity origin binding; Firefox and Chromium reattached after transport loss and reload without replacing the queue | Mac reload/retry/network lifecycle |
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox. Chromium authenticated and paired in the installed Foundry world. The MA front end’s unauthenticated Sendspin interceptor explains the failing control probe. | Original Mac-specific pre-upgrade failure remains unresolved |
| AM-006 setup usability | The v0.7.1 browser preview passed layout at 380 and 760 pixels, one-click connection, scene assignment and real playback controls in the development world. | Retry the same workflow with v0.7.1 installed on the server |
| Account persistence | The v0.7.2 preview saved an encrypted connection record in the Foundry GM account and connected from a fresh browser with the token alone. New scene references are portable across browsers using that token. | v0.7.2 server installation and Mac acceptance |
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox, including stock Firefox 161.0.1. Chromium authenticated and paired in the earlier installed-world run. The MA front end’s unauthenticated Sendspin interceptor explains the failing historical control probe. | Mac Firefox connectivity fails. The current failure stage awaits browser capture. |
| AM-006 setup usability | The three browser engines passed the narrow setup fixture. The v0.8.0 ZIP preview exercised real connection, scene assignment and transport. | Exact v0.8.1 installed-world acceptance |
| AM-007 continuity | Firefox ZIP preview passed 30 minutes across real combat and restoration. Three-engine renders at 44.1 and 48 kHz passed the PCM comparison. The operator confirmed macOS background audio, physical output during testing and WAN audio. | Firefox hidden tab and suspend/wake |
| AM-008 credentials | Three-engine encrypted device storage across browser restarts and synthetic auth denial. Real Chromium token-free reload, Disconnect and Forget Credentials. | Separate Mac profiles, live disposable-token revocation and token rotation |
| AM-009 native integration | The Chromium ZIP preview saved native scene assignments with a pointer drag and exercised scene, combat and boss transitions. The operator confirmed scene auto-activation in v0.8.0. | Manual combat, boss and ambient restoration |
| AM-010 controls | Token-toolbar and playlist-sidebar launch points, transport, manual override, return to scene and fades through the dedicated MA queue. | True overlapping playlist crossfade |
| MA catalog playback | The installed module delivered audio to two real Foundry players during ambient, combat and restoration to a seven-second offset. Stop/Enable and reload were exercised. | Physical devices, invitation renewal and WAN acceptance |
## Technical findings
@@ -50,7 +191,10 @@ startup failed with MA `MediaNotFoundError` in both engines. The cause of those
failures remains unconfirmed. The controller preserves the failed command and skips
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
The installed-world evidence is in `evidence/v0.7.0-foundry-private.json`. Publication
remains pending Mac, physical-device, WAN and invitation-renewal checks in TESTING.md.
Crossfade, durable crash restoration, seamless handover and WAN synchronization
remain unsupported.
The earlier server-installed evidence is in `evidence/v0.7.0-foundry-private.json`.
The installed v0.8.0 manual results and remaining checklist are in
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md). See [TESTING.md](TESTING.md)
for the v0.8.1 fixture results and investigation.
The single queue supports sequential
fades. Durable crash restoration, seamless handover and WAN synchronization remain
unsupported.
+32 -23
View File
@@ -1,29 +1,38 @@
# Adaptive Music — 0.7.2
# 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. System-independent; one Foundry module
ZIP, no other required module, container, VM/LXC or companion service.
Foundry v14.371 and Music Assistant 2.10.6. The module runs independently of the game
system and uses a single installable Foundry ZIP.
Enter your private HTTPS MA address and token in **Connection**, then select
**Connect**. Assign playlists in **Scene Music** and enable automation in
**Playback**. Players receive WebRTC audio
automatically, with one Enable Audio click if their browser requires it. No receiver
identity export or JSON import is part of setup.
In **Connection**, enter your private HTTPS Music Assistant address and a revocable
Music Assistant token. On a trusted GM device, opt in to **Remember credentials and
reconnect on this trusted device**. Assign ambient, combat and boss playlists in
native **Scene Configuration**. Enable automation once. Open **Adaptive Music
controls** from the token toolbar or the Playlists sidebar during play. The setup
window can close.
The signed-in GM account remembers the encrypted Music Assistant address. Enter the
MA token and select **Connect** to unlock it in a new browser session. MA tokens
stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
is encrypted in that browser’s IndexedDB so reconnecting does not create another
receiver. Players receive individually encrypted invitations, not MA credentials.
Only that dedicated receiver and explicitly owned Foundry music playlists are
controlled. Household speakers, grouping, queue transfers, sound effects and
AmbientSound documents are outside the control surface.
The active scene starts its assigned music. Starting an encounter in the Combat
Tracker interrupts ambient and ending it restores the saved track and position.
Check **Boss encounter** before starting to use the scene's default boss cue.
The tracker and playback controls show Ambient, Combat, Boss or Manual Override.
GMs can pause, resume,
skip, stop, set repeat, adjust volume, apply a manual playlist and return to scene music.
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 v0.7.1 browser preview passed the new graphical setup and playback workflow
in a real Foundry v14.371 development world with two listeners. See TESTING.md
for the test scope and remaining installed-build checks.
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.
See INSTALL.md for setup/manual publication, TESTING.md for the consolidated Mac
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status.
Crossfade, seamless GM handover, durable crash restore and WAN synchronization
claims are not implemented. Attribution and licenses remain in THIRD-PARTY-NOTICES.
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
the GM opted in. An additional device can unlock the Foundry account’s remembered
address with the same token and choose its own retention preference.
See [INSTALL.md](INSTALL.md) for setup, [SECURITY.md](SECURITY.md) for credential
scope, and [TESTING.md](TESTING.md) for measured behavior and remaining acceptance.
+40 -24
View File
@@ -1,32 +1,35 @@
# Adaptive Music security — 0.7.2
# Adaptive Music security — 0.8.3
## Credentials and browser trust
The MA access token remains in the trusted GM tab’s closure memory. It is excluded
from Foundry settings, flags, sockets, URLs, console logging, IndexedDB serialization
and release archives. Setup failures retain it in this tab; disconnect or reload
forgets it. Tokens are never reused after an origin change. Use a restricted MA
account with only the intended music providers and dedicated receiver permissions.
By default the MA access token remains in the GM tab’s memory. A GM can opt in
to an encrypted IndexedDB record for this trusted browser profile. A separate,
non-extractable AES-GCM key and random nonce protect the record, which is bound to
the Foundry origin, world and user. Use a dedicated, high-entropy, revocable token
from Music Assistant’s Profile settings. Tokens are excluded from Foundry
settings, flags, sockets, URLs, diagnostic output and release archives.
The Foundry User Setting stores only a version, random nonce and encrypted MA
address and receiver name. The encryption key is derived from the user-entered MA
token for this account and world. Use a generated, high-entropy MA token. The
envelope cannot be unlocked after rotating that token. Connect with the explicit
address and new token to replace it. Forget saved connection removes the envelope.
Local encryption protects against casual inspection of plaintext storage. Same-origin
scripts, enabled modules and the browser profile owner can use the retained key.
The device credential does not travel to another browser with a Foundry login.
Use a separate browser profile for accounts that should never share local trust.
Disconnect ends playback and disables automatic reconnect until the GM connects
again. Forget Credentials removes the device credential and ends the connection.
More extensive cleanup is available under Advanced → Forget saved connection.
Receiver private identity and pairing material are encrypted in the GM browser’s
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and
a non-extractable key stored in the same browser. It avoids plaintext receiver
storage; it cannot protect against same-origin scripts, a compromised enabled
module, the local profile owner or theft of a complete browser profile. Use separate
browser profiles for trusted GM and untrusted accounts. Forget remembered receiver
removes the local record only; it does not delete MA resources or touch queues.
Foundry’s user-scoped address record still holds only a version, nonce and
ciphertext. It can be unlocked on another device with the same token. Rotating the
token requires entering the MA address again. MA catalog references created with
the former token can need reassignment. Receiver private material has its own
encrypted browser record, paired to the dedicated target.
Private development endpoints, tokens, identities, account/catalog results and
snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket
frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled;
the module does not change production log settings. Expanded operator authorization
covers the dedicated live development tests; no production infrastructure was changed.
The release audit checks nested archives for private test inputs and keeps the
development-world account mapping in its ignored configuration file.
## Network and authority
@@ -35,6 +38,8 @@ security, Origin and private access controls remain enabled. No public MA endpoi
Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics
send no explicit MA auth frame; browsers may still send their normal ambient cookies.
The copyable report adds route timing and an allowlisted setup failure code and
stage. Arbitrary error strings and connection inputs stay out of those fields.
Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
those causes.
@@ -46,20 +51,31 @@ 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 and
replay protected, and validated for one audio direction with media-level SDP
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
the installed development world. SDP is encrypted, bounded, replay protected and validated for a single audio
direction with media-level inheritance. Expiry ends the signaling capability.
An established media stream remains tied to the authorized listener and active
GM session. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
Recipients can record audio or disclose their own capability. Direct peers can
learn network addresses. No public STUN/TURN is silently configured. Optional existing ICE URLs and short-lived TURN credentials are entered in the GM interface, kept in tab memory, and delivered only inside the encrypted per-player invitation.
## Recovery and distribution
API/Sendspin loss stops automation and listener forwarding. Retained tab inputs
support a deliberate reconnect; the owned queue is not replaced during reattachment.
No blind mutation retry or automatic crash restoration is promised. Logical pause
support deliberate reconnect. A trusted device can also reauthenticate after a
transport outage. Attachment preserves an owned nonempty queue. Unknown writes
and loss of dedicated queue permission require review before restoring automation. Logical pause
and interruption snapshots do not survive a reload. Native fallback cannot silently
resolve an uncertain remote queue.
+1 -1
View File
@@ -1 +1 @@
1ccdd229e40e1e02f0fa76d8fc553877c66c9494
1ed6b4c8ccd35e1187b83003379fe05d3cbeed8a
+254 -6
View File
@@ -1,9 +1,252 @@
# Adaptive Music verification — 0.7.2
# Adaptive Music verification — 0.8.3
## Executed evidence
The source archive includes sanitized evidence separately from private .local inputs.
### v0.8.3 floating music bar
The JavaScript regression suite covers cue changes while paused, same-queue
resume, native ambient position, failed transitions and canceled authority.
The GM audio graph test checks that the local monitor and the listener output
are on separate branches. Chromium, Firefox and WebKit DOM fixtures exercise
player and GM controls, personal and campaign volume, pause and play, and the
bar's collapse and drag controls. All 122 JavaScript and 17 Python tests passed.
Repository and upstream checks passed, and npm audit reported zero vulnerabilities.
The development server reported no active game session at the join screen, so
live v0.8.3 acceptance remains pending.
### Installed v0.8.1 operator follow-up
The operator confirmed combat automation, initiative advancement, boss music,
ambient restoration, manual controls and audio quality. The multiplayer report
was a separate failure. When another user joined, playback stopped and Scene
Music lost its catalog until that user left.
### v0.8.2 multiplayer reproduction
With v0.8.1, the GM started audio and had a populated catalog before any other
account joined. Independent GUI logins as Player and Trusted Player kept the
GM catalog and each listener received audio. Joining as Assistant GM reproduced
the reported audio and catalog failure. Foundry reported one active full
Gamemaster and two active `isGM` users. The GM's two MA sockets closed while the
Foundry socket remained connected. The previous authority check counted
`isGM` users and its User update handler closed the GM audio host and emptied
the catalog when the count rose above one.
Earlier multiplayer runs joined the GM and two ordinary players before starting
music. Those runs exercised real audio and permissions, and missed both the
late join during active playback and Foundry's Assistant GM role distinction.
v0.8.2 uses the full Gamemaster role for the exclusive controller and uses the
documented connection hook to reconcile listener joins and departures.
The role of the account in the operator's original report was unspecified.
[Foundry User API](https://foundryvtt.com/api/v14/classes/foundry.documents.User.html),
[role constants](https://foundryvtt.com/api/variables/CONST.USER_ROLES.html),
and [userConnected hook](https://foundryvtt.com/api/functions/hookEvents.userConnected.html).
### v0.8.2 live multiplayer candidate
The authorized Foundry 14.371 development world ran the package's runtime via
browser preview on Ubuntu using Chrome for Testing and Firefox. Foundry still
reported the server-installed v0.8.1, which independently matched all 28 files
from the local v0.8.1 runtime. The preview used normal browser TLS checks and
real Foundry accounts. It measured the host output and decoded listener audio.
The GM started music alone. A Chrome Player joined first, then a Firefox
Trusted Player and Chrome Player joined together. An additional Assistant GM
joined and left in Firefox. The GM kept its receiver, both MA sockets and all
13 catalog choices. A Player's 25% volume yielded about one quarter of its
input RMS. Mute brought that player's local output to zero while it continued
receiving audio, and the GM and other listeners kept hearing audio. A fresh
login retained the Player's mute and volume. Both Player and Trusted Player
were denied changes to shared automation and a test scene's music flags.
The world used distinct ambient, combat and boss playlists. All three listeners
followed the native tracker cues, ambient restoration, scene activation and
manual playback. The normal encounter used an unstarted Foundry fixture after
the automation pointer missed the token HUD. The boss encounter used the
native token HUD. Both used the native Combat Tracker to roll initiative,
start and end combat. Ambient restored to track index 0 at 41 and 66 seconds.
Over 360 seconds, the GM catalog and sockets stayed stable. The GM and all
three listeners had a measurable signal at 30 of 30 checks, and each listener's
received bytes and audio samples advanced at every interval. The remembered GM
credential reattached to the same receiver after reload, kept the queue and
restored audio to all three listeners. Player sessions made zero requests to
MA. The test restored the development world, and all MA queue writes targeted
the dedicated receiver.
The automated suite passed 117 JavaScript and 17 Python tests. The Chromium,
Firefox and WebKit setup and credential fixtures passed, including browser
restart and fixture revocation. Repository and upstream audits passed. npm
audit reported zero vulnerabilities. Measurements and scope are recorded in the
[sanitized v0.8.2 evidence](evidence/v0.8.2-live.json).
### Installed v0.8.0 manual macOS acceptance
The operator confirmed Chrome connectivity, retention after a full Chrome quit
and reopen, automatic scene playlist activation, background-tab audio, WAN
player audio and smooth transitions. Stuttering and crackling were resolved
during testing. Firefox connectivity failed. In the combat follow-up, the
operator reported that a battle playlist played when assigned to ambient,
while native combat use left the ambient cue playing. They could not find
the boss designation. The operator later passed the corrected combat flow and
manual playback controls in v0.8.1.
### v0.8.1 native Combat Tracker investigation
Tested Foundry **14.371** and D&D 5e **6.1.2** in the authorized development
world. The baseline used installed v0.8.0 and the GM entered a token into
combat through its native HUD. The tracker created an active, unlinked
encounter with one combatant belonging to the active scene. On **Start Combat**,
`combatStart` arrived at round 0 with `started=false`. The subsequent
`updateCombat` and `combatTurnChange` reported round 1, turn 0 and
`started=true`. The baseline made no dedicated queue transition, reproducing
the failure without calling a module API or injecting encounter state.
Foundry v14's `Combat.scene` is optional in practice and its unlinked encounters
are visible across scenes. `Combatant.sceneId` identifies the token's scene.
D&D 5e's `Combat5e` at `75750bf1b8bd79f8448af40495c8bb5c99f49551`
delegates start, end and update/delete processing to Foundry core and adds
system-specific resource and token behavior. Adaptive Music uses
the committed document hooks and accepts explicit scene links or the token
scenes in an unlinked encounter. A turn or round change leaves the cue intact.
The Chromium package preview used three distinct playlists. A native token HUD
and native tracker controls verified adding combatants, rolling initiative,
starting an encounter, advancing turns and rounds, and canceling or confirming
End Combat. Neither preparation nor canceled End Combat changed the cue.
Confirmed End Combat restored the ordered ambient queue at track index 0 and
30 seconds. The **Boss encounter** checkbox selected the scene's default boss
cue on the next encounter. A scene excursion using Foundry's scene activation
operation played the other scene's ambient, then selected Boss on return.
Ending the boss restored the original ambient at 33 seconds. A manual silence
override displayed an explicit warning during the next encounter. **Return to
automation** selected Combat, and End Combat restored ambient at 46 seconds.
The test measured GM output and restored the development world afterward.
Headed Ubuntu Firefox 159 repeated the native token HUD, initiative, start,
turn and round, canceled end, and confirmed end checks against the same
candidate runtime. It measured GM output and restored ambient at index 0
and 9 seconds. Both candidate previews ran on Foundry 14.371 and D&D 5e 6.1.2
with server-installed metadata reporting v0.8.0.
[Foundry Combat Tracker guide](https://foundryvtt.com/article/combat/),
[combatStart hook](https://foundryvtt.com/api/v14/functions/hookEvents.combatStart.html),
[Combatant API](https://foundryvtt.com/api/v14/classes/foundry.documents.Combatant.html),
and [D&D 5e 6.1.2 Combat implementation](https://raw.githubusercontent.com/foundryvtt/dnd5e/75750bf1b8bd79f8448af40495c8bb5c99f49551/module/documents/combat.mjs).
### v0.8.1 Firefox transport investigation
The downloaded Mozilla Firefox 161.0.1 Linux archive matched Mozilla's SHA-512
listing. Real stock Firefox over the authorized private route opened native
`/ws` and `/sendspin` WebSockets with HTTP 101 from the anonymous Foundry
page and the MA origin. The test used a process-local mapping to the authorized
private proxy and normal certificate verification. No credentials were entered.
The MA page replaces its WebSocket constructor, so its control used the
native constructor retained before page script execution.
Separate live runs with stock Firefox 161.0.1 on Ubuntu also signed into the
development world, authenticated to MA and measured scene audio at the GM and
a second Foundry login. Those runs covered installed v0.8.0 and the earlier
diagnostics-only v0.8.1 browser preview.
Seven isolated stock-Firefox policy cases covered trusted cross-origin and
same-origin upgrades, enforced and report-only CSP, server-side Origin
rejection and a mismatched WSS certificate. Origin and TLS failures remained
opaque to page script. The permission API reported `prompt` even on a private
route that worked, so that reported state does not determine the cause.
Firefox's site-level local network permission and the macOS app-level permission
are separate. Record whether MA's normal HTTPS page works in the failing Firefox
profile. If it fails, verify the displayed error and compare the profile's
existing DNS and proxy settings. If MA loads, compare the two Foundry WSS routes
and look for local-network or CSP console messages. A reverse proxy's
timestamped path and response status can distinguish a received handshake
from a failure before it reached the proxy. The pinned MA 2.10.6 handlers
authenticate after upgrade. Ordinary HTTP CORS settings do not establish
authorization for a WebSocket Origin. Keep browser, TLS and proxy policy in place.
See [the Firefox capture instructions](USER-ACCEPTANCE.md#capture-the-firefox-failure),
[Mozilla local-network permissions](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [MDN's CSP connect-src reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/connect-src).
### v0.8.0 handoff checkpoint
The v0.8.0 browser preview reached the actual Foundry development world through
the private HTTPS proxy. Earlier native MA reference playback reproduced a
restricted-token receiver reassignment during the Firefox test. The handoff
soak restored the ambient order and the saved position at 37 seconds, but both
listeners recorded about 763 seconds of terminal digital silence and Stop/Enable
could not verify renewed audio. The original result fails the continuity gate.
The updated soak enables repeat on its dedicated playlist and measures GM and
listener output, including silent render blocks. Each phase requires at least
95% of the expected output frames and no digital silence longer than four
seconds. See [HANDOFF.md](HANDOFF.md) and `evidence/v0.8.0-live.json`.
The corrected Firefox 159 run passed in the real development world with one GM
and two players. The validated archive supplied the v0.8.0 runtime assets. The
continuity phases totaled 1,800 measured seconds. Across the full session,
the GM scheduled 74,261 PCM chunks with zero late or early drops, source gaps,
overlaps, overruns or underruns. Ambient order and
index 0 at 37 seconds were restored after combat. Listener Stop/Enable and reload
recovered audio. RTP concealment stayed flat within the measured phases. Both
listener meters counted 608 near-zero runs of 0.75–80 ms in restored ambient,
with a longest digital silence of 449 ms. The test measured the digital playback
graphs in the browser.
The Chromium package preview passed native scene rendering and saved assignments
in two scenes, including a pointer drag from the Playlists sidebar. Both the
sidebar and token toolbar opened the controls. Real scene, combat and boss cues
reached both players and restored the saved ambient track and offset. A prior
review stopped at preparation for an unsupported catalog entry before writing the
queue. The review uses three prepared static playlists from the dedicated
catalog. Chromium also passed token-free reload to the same receiver, preserved
the queue, and verified Disconnect and Forget Credentials across reloads.
In headed Chromium the GM page was actually hidden behind another tab for
12 seconds. The GM audio clock advanced and its output analyser measured audio
while both listeners continued playing. This check disabled Playwright's
automatic focus emulation. The longer AudioWorklet measurements were collected
in Firefox.
The focused Firefox background follow-up measured real GM-to-listener audio
before changing tabs. The automation still reported the GM document visible
after a desktop tab switch. Firefox hidden-tab continuity therefore remains an
open acceptance check. The development world's state was restored.
The review restored the development world's settings and active scene. The
final audit configured the Christmas and Dûr-Khazrak demo scenes and activated
Christmas for handoff. The Dûr-Khazrak ambient cue uses an existing development
playlist as a stand-in for a dwarven soundtrack.
[Playwright focus emulation details](https://github.com/microsoft/playwright/issues/31890).
Independently repeated OfflineAudioContext renders in Chromium, Firefox and Linux WebKit
detected gaps with the v0.7.2 packet timing and none in the corresponding
v0.8.0 runs at 44.1 and 48 kHz. Browser IndexedDB and Web Crypto fixtures
verified per-user/world lookup, forgetting, and retained authentication across
full persistent-profile browser restarts in all three engines. The real
WebSocket client rejected the previously saved synthetic token after fixture
revocation. The real MA server was not modified for this check.
The later installed v0.8.0 Mac results are recorded above. Mac Firefox and
native Safari still require device-specific acceptance.
In the loopback WebRTC fixture, Chromium and Firefox both rendered audio across
signaling expiry and closed the sender after listener revocation. Linux WebKit
completed offer/answer with default ICE and timed out before the connection
opened. With a process-local coturn relay and ephemeral credentials it rendered
audio before and after expiry, then closed on revocation. The relay test covers
the existing optional TURN configuration in a local fixture. Native Safari and
the actual WAN route need separate verification.
[Playwright browser coverage](https://playwright.dev/docs/browsers) and
[WebKit ICE candidate considerations](https://webkit.org/blog/7763/a-closer-look-into-webrtc/).
For the live package preview, pass `--package-preview dist/releases/v0.8.0/adaptive-music.zip`
to the private-route runner. It validates and extracts the archive locally,
serves its module assets to the test browsers and records the ZIP SHA-256.
The server's module metadata still reflects the installed version. The preview
exercises the packaged assets and the logged-in development world.
The release metadata also carries an installed asset SHA-256 across `src/`,
`styles/` and `vendor/` so results can be matched across documentation updates.
### Account persistence and v0.7.0 GUI review
The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive
@@ -92,6 +335,10 @@ runs used dedicated MA development receivers exclusively.
## One consolidated Mac / logged-in-world acceptance
Use [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the step-by-step Firefox and
Chrome checks against the prepared demo scenes. The following procedure records
the broader installed-world and WAN acceptance scope.
Run this in an isolated test world with the actual Foundry v14.371 host and existing
private HTTPS MA endpoint. It needs no developer console or diagnostic shell commands.
@@ -116,15 +363,16 @@ private HTTPS MA endpoint. It needs no developer console or diagnostic shell com
draft/receiver should remain; after a browser reload only the token needs reentry.
Reconnect the same owned receiver and confirm its queue is not replaced. Apply the
automation setting explicitly if a nonempty queue was retained.
6. Continue listening for at least 30 minutes across invitation renewal. Exercise one
6. Continue listening for at least 30 minutes across signaling invitation expiry. Exercise one
brief network interruption, reconnect, and one background/suspend cycle. Report
failures with Copy connection diagnostics. Repeat on the actual WAN player route;
loopback/LAN signal does not establish NAT/TURN reachability or synchronization.
The installed-world run covered real Foundry hooks, socket delivery and User
permissions. Public release acceptance still requires audibility on the actual
Mac/player devices, the original Mac connection, invitation renewal and WAN checks.
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp
The development-world runs covered real Foundry hooks, socket delivery and User
permissions. The v0.8.0 preview verified continued playback through the
signaling lifetime and listener reconnection. For v0.8.1, verify the exact
installed candidate and prioritize the unresolved Mac Firefox connection.
For AM-005, correlate the reported browser stage and timestamp
with the private proxy’s request and upstream status or TCP counters. The procedure
and temporary VM-to-proxy access rollback are in ignored .local/PRIVATE-ROUTE-REQUEST.md.
+86
View File
@@ -0,0 +1,86 @@
# 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
[TESTING.md](TESTING.md) for automated browser and development-world evidence.
| Result | Scope |
| --- | --- |
| Pass | Chrome connectivity, Chrome credentials after a full quit and reopen, automatic scene playlist activation, background-tab audio, remote player audio over WAN, and smooth transitions. The operator heard no stuttering or crackling during testing. |
| Fail | Firefox connectivity on macOS. The operator also reported that the assigned battle playlist played when used as ambient, while normal Combat Tracker use left the ambient cue playing. |
| Usability finding | The operator could not find a way to designate a boss. Their normal combat and default boss assignments used the same playlist. |
| Passed in v0.8.1 | Combat start and end, ambient restoration, boss designation, and manual playback controls. |
## Capture the Firefox failure
1. Note the Firefox and macOS versions. In the same Firefox profile and network,
open the normal MA HTTPS page and record whether it loads or shows a
certificate or connection error.
2. Return to the Foundry world. Open **Adaptive Music setup → Connection** and
reproduce **Connect** once. Note the exact error and the time with timezone.
Run **Check browser connection**, then select **Copy connection diagnostics**.
3. If either route fails, record the Foundry site's local network permission
from Firefox's site permissions or **Settings → Privacy & Security →
Permissions → Local network devices**. Also record the Firefox entry under
**System Settings → Privacy & Security → Local Network** on macOS. Leave
these settings as they are for the initial capture.
4. If available, copy the relevant Web Console line for `/ws` or `/sendspin`
using **⌘⌥K**, especially a Local Network Access, CSP or certificate error.
Share the result privately with the copied module diagnostics. Omit tokens,
cookies, raw WebSocket frames and full network exports.
See [Mozilla’s Firefox local-network permission guide](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [Apple’s macOS Local Network settings guide](https://support.apple.com/guide/mac-help/mchla4f49138/mac).
## Candidate checklist
Run the relevant checks against the exact candidate being accepted. Use the
private development world and sign in as **CodexDEV**, with one GM browser
connected at a time. Use the same approved development MA token in both
browsers so the existing scene assignments resolve. Put on headphones and
record your browser and macOS versions.
Before starting 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 |
| --- | --- | --- |
| ☐ Connect | Open **Settings → Adaptive Music setup → Connection**. Enter the approved private MA address and token. On a trusted profile, select **Remember credentials and reconnect on this trusted device** and click **Connect**. | The catalog loads and the dedicated receiver connects. Once connected, the token field is empty. Click **Enable GM audio** if prompted. |
| ☐ Christmas ambience | Activate **Christmas — Adaptive Music demo**. Open **Adaptive Music controls** from the token toolbar and enable automation if needed. | Christmas music starts. The controls show the currently playing track and its position. |
| ☐ Native assignment | Open **Configure Scene** on the Christmas scene. In **Playlists → Adaptive Music**, drag its current Christmas playlist onto **Ambient playlist** and click **Save assignments**. Reopen Configure Scene. | The dropped value survives saving and reopening. The scene's native soundtrack remains unset. |
| ☐ Combat | Activate **Dûr-Khazrak — Adaptive Music demo** or another scene with three distinct ambient, combat, and boss playlists. Note the ambient track and position. Add tokens with **Enter Combat**, roll initiative, then click **Start Combat** in the Combat Tracker. Click **Next Turn** and **Next Round**. | Adding combatants and rolling initiative leave ambient playing. Starting the encounter switches to **Combat**. Advancing turns and rounds continues the cue without a restart. |
| ☐ Boss | In a fresh encounter, check **Boss encounter** in the Combat Tracker before clicking **Start Combat**. | The scene's default boss cue starts and the tracker and Playback panel show **Boss**. A scene with the same combat and boss playlist can change mode while the music continues. |
| ☐ Cancel and restore | Open **End Combat** and cancel the confirmation, then open it again and confirm. Repeat with a second encounter. | Cancel keeps the encounter and its music running. Confirm restores the ambient queue order, track and approximate saved position. A later encounter captures a fresh position. |
| ☐ Switch scenes during combat | During an active encounter, activate another scene with its own ambient cue and no participants in that encounter. Reactivate the original scene and end the encounter. | The other scene uses its own ambient. The encounter cue returns on reactivation. Ending the encounter restores the original scene's interrupted ambient position. |
| ☐ Manual controls | Open **Music controls** from the Playlists sidebar and apply a **Manual playlist override**. Start combat and use **Return to automation** in the Combat Tracker. Also try pause, resume, seek, skip, volume, repeat, and stop. | The tracker and Playback panel show **Manual Override** while automatic cues are on hold. Return to automation takes up the currently applicable cue. Transport controls affect the dedicated receiver. |
| ☐ Late and simultaneous joins | Start music with the GM alone. Join as a Player, then join two more sessions together, including a Trusted Player. Use Chrome and Firefox. Repeat with an Assistant Gamemaster if that role is used in your world. | The GM keeps the same cue, receiver and catalog. Each player hears current audio after any needed browser activation. A Foundry account is sufficient for listening. |
| ☐ Personal listening controls | In the Playlists sidebar open **Campaign audio**. Change one listener to 25% and toggle **Mute**. Log out and back in as that user, then unmute. | Only that user changes level. The user's mute and volume survive reentry. The GM and the other listeners continue playing. |
| ☐ Floating music bar | As a player, drag the bar and select **Hide**, then **Show**. Set **My volume** and mute. As the GM, mute your own output and change **Campaign volume**. | The bar stays available on the map. Personal controls affect only the current browser, and Campaign volume affects the shared Music Assistant stream. |
| ☐ Pause and play all | As the GM, pause and play once on the same cue. Pause again and activate a scene with a different playlist before selecting Play. | The group hears silence while paused. The first Play resumes at the saved position. The second Play starts the new scene's cue. Native effects continue under Foundry's own controls. |
| ☐ Multiplayer cues | Keep the group connected through combat, boss, End Combat, a scene change and a manual override. | All listeners hear the same cue changes while retaining their own volume settings. |
| ☐ Continuity | Listen on GM and player output through steady playback, cue changes and at least one track boundary. Cover each Foundry tab with another tab for at least one minute. Include one 30-minute play session and a Mac sleep/wake test across the two browsers. | Steady audio has no audible pops, crackle or unexpected gaps. Cue changes use a short sequential fade. Track/position continue while the tab is hidden. Record what happens during and after sleep. |
| ☐ Restart and reconnect | Quit the browser fully, reopen the same profile and return to the development world. With a working session, briefly drop and restore the test device's network. | The remembered receiver reconnects without token entry. A populated queue is preserved on attachment. Select **Return to scene music** to resume scene cues immediately if needed. |
| ☐ Disconnect and forget | Click **Disconnect**, restart the browser and verify it stays disconnected. Reconnect intentionally, click **Forget Credentials**, then restart again. | Disconnect pauses automatic reconnect. Forgetting removes the stored device token. The next connection requires token entry. |
| ☐ MA revocation | If testing revocation, use a disposable development token. At the end of that test, revoke only that token in MA Profile and retry from the same browser. | The revoked token cannot authenticate and the setup reports auth denial. Re-enter the approved token and private address before using the prepared scenes again. |
If a check fails, record local time with timezone, the browser and OS version,
the scene and cue, and whether the GM, a player or both were affected. For 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**
before copying diagnostics and note whether the normal MA page loads in the
same browser. Share the copied reports privately and keep tokens, raw WebSocket
logs and browser profiles out of the report.
File diff suppressed because it is too large. Load diff
+701
View File
@@ -0,0 +1,701 @@
{
"version": "0.8.1",
"scope": "Firefox diagnostics and native Combat Tracker candidate. Private development-world package previews, transport checks and browser fixtures.",
"publicationReady": false,
"serverInstalledExactVersion": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"macFirefoxRootCauseConfirmed": false,
"operatorAcceptanceV080": {
"source": "Operator-reported manual acceptance on installed Adaptive Music v0.8.0 on macOS",
"installedVersion": "0.8.0",
"passed": [
"Chrome connectivity",
"No stuttering or crackling during testing",
"Chrome credential retention after full quit and reopen",
"Automatic scene playlist activation",
"Background-tab audio continuity",
"Remote player audio over WAN",
"Smooth music transitions"
],
"failed": [
"Firefox connectivity on macOS"
],
"notTested": [
"Automatic combat music",
"Ambient restoration",
"Boss music",
"Manual playback controls"
],
"combatFollowUp": {
"scope": "Operator follow-up from their actual Foundry scene",
"ambientPlayback": "pass",
"battlePlaylistPlayableWhenAssignedToAmbient": true,
"combatCueSwitch": "fail: ambient continued",
"bossDesignationDiscoverability": "fail",
"combatAndBossUsedSamePlaylist": true,
"candidateManualRetest": "pending"
}
},
"localHistory": {
"originalHead": "987122ffee17ddbdb6266a12d4d8beb29903b838",
"localV080Release": "1ed6b4c8ccd35e1187b83003379fe05d3cbeed8a",
"v080SourceFilesIdentical": 157,
"reportedPublishedCommit": "95b0427",
"publishedObjectAvailableLocally": false,
"v081Branch": "v0.8.1-firefox"
},
"installedBaselineComparison": {
"scope": "anonymous exact-path read of installed Foundry module files over trusted private HTTPS",
"manifestStatus": 200,
"installedVersion": "0.8.0",
"runtimeFilesCompared": 28,
"runtimeFilesIdentical": 28,
"runtimeMismatches": []
},
"stockFirefox": {
"version": "161.0.1",
"platform": "Linux x86-64",
"archiveSha512": "9ef6ccc1b0e4376980ab88a49408924e75d3cafca248becfb8893424c6f025a58d715bf05f1f5397a4a997059de4c054a3e6490a140bdf4dc8795ec78b26e02a",
"download": "https://archive.mozilla.org/pub/firefox/releases/161.0.1/linux-x86_64/en-US/firefox-161.0.1.tar.xz",
"archiveVerifiedAgainstMozillaSha512Listing": true,
"privateRoute": {
"scope": "official Mozilla Firefox on Ubuntu, anonymous private Foundry and MA HTTPS pages, fixed unauthenticated WSS routes",
"browser": "161.0.1",
"tlsValidation": true,
"checks": {
"foundryOrigin": {
"status": 200,
"cspHeaderPresent": false,
"reportOnlyHeaderPresent": false,
"secureContext": true,
"cspMetaPresent": false,
"replaced": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 9,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
},
"maOrigin": {
"secureContext": true,
"cspMetaPresent": false,
"replaced": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 195,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
}
},
"completed": true
},
"isolatedPolicyChecks": {
"scope": "isolated real Firefox HTTPS/WSS policy tests; local transport server, no MA, no Foundry, no credentials or audio",
"browser": "161.0.1",
"mozillaStockBuild": true,
"tls": "local CA trusted in disposable Firefox profile; no certificate bypass",
"checks": [
{
"name": "Trusted HTTPS cross-origin WSS allowed",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 11,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Enforced CSP blocks cross-origin before upgrade",
"results": [
{
"path": "/ws",
"code": "csp-blocked",
"elapsedMs": 1,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "csp-blocked",
"elapsedMs": 0,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same MA origin control",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Report-only CSP does not block",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Server Origin rejection stays opaque",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 31,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same origin still succeeds under Origin restriction",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 2,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Mismatched WSS certificate stays opaque and connection closed",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 28,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
}
],
"passed": true
}
},
"offlineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
],
"regression": {
"javascriptPassed": 115,
"javascriptFailed": 0,
"pythonPassed": 17,
"pythonFailed": 0,
"repositoryPrivacyAndAttribution": "pass",
"upstreamProvenance": "pass",
"npmAuditReportedVulnerabilities": 0
},
"remainingAcceptance": [
"Capture the failure on the operator Mac and identify its WebSocket or subsequent setup stage",
"Verify the exact server-installed v0.8.1 candidate in the affected Firefox profile and the working Chrome profile",
"Retest the corrected combat, ambient restoration, boss designation and manual playback controls on the operator Mac"
],
"combatTrackerAcceptance": {
"scope": "Authorized private development world; the candidate ZIP supplied runtime assets to the browser",
"dnd5eReviewedCommit": "75750bf1b8bd79f8448af40495c8bb5c99f49551",
"installedV080Reproduction": {
"at": "2026-12-05T18:15:47.932Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"cleanup": true,
"nativeHudAndStartCombat": true,
"encounter": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1
},
"ambientQueueChanged": false,
"lifecycle": [
{
"event": "createCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 0,
"participantsInActiveScene": 0,
"updateKeys": []
},
{
"event": "createCombatant",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1
},
{
"event": "combatStart",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "updateCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "combatTurnChange",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
}
]
},
"candidateNormalEncounter": {
"at": "2026-12-05T18:20:56.093Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.04104
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 30
},
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.0348
}
},
"harnessResult": "Normal encounter checks passed. The first scene-navigation locator timed out and the focused follow-up exercised the scene edge cases.",
"postCommitEvents": [
"combatRound",
"combatStart",
"combatTurn",
"combatTurnChange",
"createCombat",
"createCombatant",
"deleteCombat",
"updateCombat",
"updateCombatant"
]
},
"candidateBossSceneAndOverride": {
"at": "2026-12-05T18:29:02.740Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.11936
},
"sceneExcursionDuringCombat": {
"passed": true,
"outwardMethod": "native-scene-activation",
"returnMethod": "native-scene-activation"
},
"bossRestoration": {
"index": 0,
"seconds": 33
},
"manualOverrideAndTrackerReturn": true,
"repeatedRestoration": {
"index": 0,
"seconds": 46
}
},
"onlyDedicatedQueueWritten": true
},
"candidateFirefox": {
"completed": true,
"at": "2026-12-05T18:32:54.490Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.03617
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 9
}
}
}
},
"combatCandidateOfflineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
],
"operatorAcceptanceV081": {
"source": "Operator-reported installed v0.8.1 manual testing",
"passed": [
"Automatic combat music",
"Initiative progression",
"Boss music",
"Ambient restoration",
"Manual controls",
"Audio quality"
],
"releaseBlockingFailure": "A player login stopped GM playback and removed the catalog; logout restored fetching.",
"reportedPlayerRole": "Not specified"
}
}
+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.7.2",
"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.7.2/adaptive-music.zip"
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.3/adaptive-music.zip"
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "adaptive-music",
"version": "0.5.0",
"version": "0.8.0",
"license": "MIT",
"dependencies": {
"@sendspin/sendspin-js": "5.0.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "adaptive-music",
"version": "0.5.0",
"version": "0.8.0",
"private": true,
"type": "module",
"license": "MIT",
+61
View File
@@ -0,0 +1,61 @@
// Test instrumentation only. Report counts; never record or retain audio.
class AdaptiveContinuityMeter extends AudioWorkletProcessor {
frames=0;
channelSamples=0;
zeroRun=0;
maxZeroRun=0;
shortDropouts=0;
nearFullScale=0;
jumps=0;
maxStep=0;
last=0;
nextReport=0;
audible=false;
constructor(){
super();
this.port.onmessage=event=>{
if(event.data!=='start-phase')return;
this.zeroRun=this.maxZeroRun=0;
this.port.postMessage({...this.metrics(),phaseStarted:true});
};
}
metrics(){
return {sampleRate,frames:this.frames,channelSamples:this.channelSamples,shortDropouts:this.shortDropouts,
maxZeroRun:this.maxZeroRun,trailingZeroRun:this.zeroRun,nearFullScale:this.nearFullScale,jumps:this.jumps,maxStep:this.maxStep};
}
process([input],[output]) {
const length=output[0].length;
for(let i=0;i<length;i++){
let peak=0;
for(const channel of input){
peak=Math.max(peak,Math.abs(channel[i]));
if(Math.abs(channel[i])>=0.999)this.nearFullScale++;
this.channelSamples++;
}
if(peak<=0.000001)this.zeroRun++;
if(peak>0.000001){
if(this.audible){
this.maxZeroRun=Math.max(this.maxZeroRun,this.zeroRun);
if(this.zeroRun>=sampleRate*0.00075&&this.zeroRun<=sampleRate*0.08)this.shortDropouts++;
}
this.zeroRun=0;
this.audible=true;
}
const sample=input[0]?.[i]??0;
const step=Math.abs(this.last-sample);
this.maxStep=Math.max(this.maxStep,step);
if(step>0.35)this.jumps++;
this.last=sample;
}
this.frames+=length;
if(currentFrame>=this.nextReport){
this.nextReport=currentFrame+sampleRate;
this.port.postMessage(this.metrics());
}
return true;
}
}
registerProcessor('adaptive-continuity-meter',AdaptiveContinuityMeter);
+66 -10
View File
@@ -1,16 +1,25 @@
// Browser interoperability checks for encrypted signaling and audio-only SDP.
import {createServer} from 'node:http';
import {readFile,writeFile} from 'node:fs/promises';
import {readFile,stat,writeFile} from 'node:fs/promises';
import {resolve} from 'node:path';
const {firefox,chromium}=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
const playwright=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
const engines=process.argv.includes('--webkit-only')?['webkit']:process.argv.includes('--webkit')?['firefox','chromium','webkit']:['firefox','chromium'];
const relayFile=process.env.AM_LOOPBACK_TURN_CONFIG;
let relay;
if(relayFile){
if(!resolve(relayFile).startsWith(resolve('.local')+'/')||((await stat(relayFile)).mode&0o777)!==0o600)throw Error('private TURN fixture file required');
relay=JSON.parse(await readFile(relayFile,'utf8'));
if(typeof relay?.urls!=='string'||!/^turn:127\.0\.0\.1:\d{1,5}\?transport=udp$/.test(relay.urls))throw Error('loopback TURN fixture required');
}
const root=resolve(import.meta.dirname,'..');
const server=createServer(async(req,res)=>{if(req.url==='/'){res.end('<!doctype html><title>Signal check</title>');return;}const path=resolve(root,'.'+new URL(req.url,'http://localhost').pathname);if(!path.startsWith(root+'/src/')){res.writeHead(404);res.end();return;}try{res.setHeader('Content-Type','text/javascript');res.end(await readFile(path));}catch{res.writeHead(404);res.end();}});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const reports=[];
try{
for(const [name,type]of [['firefox',firefox],['chromium',chromium]]){
const browser=await type.launch({headless:true,...(name==='chromium'?{args:['--no-sandbox']}: {})});
for(const name of engines){
const browser=await playwright[name].launch({headless:!process.argv.includes('--headed'),...(name==='chromium'?{args:['--no-sandbox']}: {})});
let pages=[],stage='browser-setup';
try{
const context=await browser.newContext(),pages=[await context.newPage(),await context.newPage()];
const context=await browser.newContext();pages=[await context.newPage(),await context.newPage()];
for(const page of pages)await page.goto('http://127.0.0.1:'+server.address().port);
const invite=await pages[0].evaluate(async()=>{const {newAudioInvite,SignalCodec}=await import('/src/audio/signal-codec.mjs');const invite=newAudioInvite({session:'browser-test',userId:'test-listener'});window.codec=new SignalCodec(invite,'gm');return invite;});
await pages[1].evaluate(async invite=>{const {SignalCodec}=await import('/src/audio/signal-codec.mjs');window.codec=new SignalCodec(invite,'listener');},invite);
@@ -19,14 +28,61 @@ try{
const sdp=await pages[1].evaluate(async()=>{const pc=new RTCPeerConnection({iceServers:[]});pc.addTransceiver('audio',{direction:'recvonly'});const offer=await pc.createOffer();pc.close();return {media:offer.sdp.split(/\r?\n/).filter(l=>l.startsWith('m=')),directionLines:offer.sdp.split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l)),unsafe:/a=sendrecv|a=sendonly/.test(offer.sdp)};});
for(let i=0;i<pages.length;i++){
await pages[i].exposeFunction('signal',async frame=>pages[1-i].evaluate(frame=>window.receiveSignal?.(frame),frame));
await pages[i].evaluate(async isGM=>{const {PeerAudio}=await import('/src/audio/peer-audio.mjs');const handlers=new Map();const socket={on:(event,fn)=>handlers.set(event,fn),off:event=>handlers.delete(event),emit:(event,frame)=>window.signal(frame)};window.receiveSignal=frame=>handlers.get('module.adaptive-music')?.(frame);window.peer=new PeerAudio({socket,userId:isGM?'gm':'test-listener',isGM:()=>isGM,createPeer:config=>{window.createdPC=new RTCPeerConnection(config);return window.createdPC;}});if(isGM){window.ctx=new AudioContext();window.peer.setSource(window.ctx.createMediaStreamDestination().stream);}},i===0);
await pages[i].evaluate(async isGM=>{
const {PeerAudio}=await import('/src/audio/peer-audio.mjs');
const handlers=new Map();
const socket={on:(event,fn)=>handlers.set(event,fn),off:event=>handlers.delete(event),emit:(event,frame)=>window.signal(frame)};
window.receiveSignal=frame=>handlers.get('module.adaptive-music')?.(frame);
window.authorized=true;
const audio=new AudioContext();
const element=document.createElement('audio');element.muted=true;element.autoplay=true;document.body.append(element);
const activate=document.createElement('button');activate.textContent='Start test audio';
activate.onclick=()=>{void audio.resume();void element.play().catch(()=>{});};document.body.append(activate);
const analyser=audio.createAnalyser(),silent=audio.createGain();silent.gain.value=0;
analyser.connect(silent).connect(audio.destination);
window.signalLevel=()=>{
const samples=new Float32Array(analyser.fftSize);analyser.getFloatTimeDomainData(samples);
return Math.sqrt(samples.reduce((sum,sample)=>sum+sample*sample,0)/samples.length);
};
window.peer=new PeerAudio({socket,userId:isGM?'gm':'test-listener',isGM:()=>isGM,isAuthorizedUser:()=>window.authorized,
onStream:stream=>{
element.srcObject=stream;void element.play().catch(()=>{});
window.testSource=audio.createMediaStreamSource(stream);
window.testSource.connect(analyser);
},
createPeer:config=>{window.createdPC=new RTCPeerConnection(config);return window.createdPC;}});
if(isGM){
const destination=audio.createMediaStreamDestination(),tone=audio.createOscillator();
tone.connect(destination);tone.connect(analyser);tone.start();
window.peer.setSource(destination.stream);
}
const peerInvite=await pages[0].evaluate(()=>window.peer.invite('test-listener'));await pages[1].evaluate(invite=>window.peer.listen(invite),peerInvite);
await pages[0].waitForFunction(()=>window.peer.diagnostics().peers[0]?.connection==='connected',{},{timeout:8000}).catch(()=>{});
},i===0);
await pages[i].getByRole('button',{name:'Start test audio'}).click();
}
stage='peer-connection';
const peerInvite=await pages[0].evaluate(relay=>window.peer.invite('test-listener',{
ttlMs:16000,...(relay&&{iceServers:[relay],relayOnly:true})
}),relay);
await pages[1].evaluate(invite=>window.peer.listen(invite),peerInvite);
await pages[0].waitForFunction(()=>window.peer.diagnostics().peers[0]?.connection==='connected',null,{polling:100,timeout:10000});
stage='rendered-audio';
const beforeExpiry=await pages[1].waitForFunction(()=>window.signalLevel()>0.05,null,{polling:100,timeout:7500}).then(()=>true);
const finalSDP=await pages[1].evaluate(()=>({media:window.createdPC.localDescription.sdp.split(/\r?\n/).filter(l=>l.startsWith('m=')),directions:window.createdPC.localDescription.sdp.split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l)),sessionHeader:window.createdPC.localDescription.sdp.split('m=')[0].split(/\r?\n/).filter(l=>/^a=(send|recv|inactive)/.test(l))}));
const peers=await Promise.all(pages.map(page=>page.evaluate(()=>window.peer.diagnostics())));
reports.push({browser:name,cryptoResult,frameKeys:Object.keys(frame),sdp,finalSDP,peers});
await pages[1].waitForFunction(expires=>Date.now()>expires+500,peerInvite.expires,{polling:100});
const afterExpiry=await pages[1].evaluate(()=>window.createdPC.connectionState==='connected'&&window.signalLevel()>0.05);
await pages[0].evaluate(()=>{window.authorized=false;window.peer.reconcile();});
const revoked=await pages[0].evaluate(()=>window.createdPC.connectionState==='closed'&&window.peer.diagnostics().peers.length===0);
if(cryptoResult!=='pass'||!beforeExpiry||!afterExpiry||!revoked)throw Error('browser signaling or audio assertion failed');
reports.push({browser:name,version:browser.version(),cryptoResult,frameKeys:Object.keys(frame),sdp,finalSDP,peers,beforeExpiry,afterExpiry,revoked,relayOnly:Boolean(relay)});
}catch(error){
const diagnostics=await Promise.all(pages.map(page=>page.evaluate(()=>({
peer:window.peer?.diagnostics(),rms:window.signalLevel?.(),tracks:window.createdPC?.getReceivers().map(r=>({state:r.track.readyState,muted:r.track.muted}))
})).catch(()=>null)));
reports.push({browser:name,version:browser.version(),stage,error:error.name,diagnostics,relayOnly:Boolean(relay)});
process.exitCode=1;
}finally{await browser.close();}
}
console.log(JSON.stringify(reports,null,2));await writeFile('.local/browser-signaling.json',JSON.stringify(reports,null,2),{mode:0o600});
console.log(JSON.stringify(reports,null,2));
await writeFile(relay?'.local/browser-signaling-relay.json':'.local/browser-signaling.json',JSON.stringify(reports,null,2),{mode:0o600});
}finally{await new Promise(resolve=>server.close(resolve));}
@@ -0,0 +1,115 @@
// Exercise persisted browser credentials and API auth against an isolated fixture.
import assert from 'node:assert/strict';
import {mkdtemp,readFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {resolve} from 'node:path';
const playwright=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
const engines=process.argv.includes('--webkit')?['chromium','firefox','webkit']:['chromium','firefox'];
const origin='https://fixture.invalid';
const allow=new Set(['/src/foundry/receiver-vault.mjs','/src/core/controller.mjs','/src/providers/ma/websocket.mjs']);
const scope={campaign:'demo-world',userId:'demo-gm'};
const credential={maUrl:'https://ma.example.test',token:'synthetic-credential-fixture',targetName:'Demo receiver',auto:true};
async function startProfile(engine,profile){
const context=await playwright[engine].launchPersistentContext(profile);
const fixture={revoked:false,attempts:0};
try{
await context.routeWebSocket('wss://ma.example.test/ws',socket=>{
socket.onMessage(data=>{
const frame=JSON.parse(data);
assert.equal(frame.command,'auth');
fixture.attempts++;
socket.send(JSON.stringify({message_id:frame.message_id,
result:{authenticated:!fixture.revoked&&frame.args?.token===credential.token}}));
});
});
await context.route(origin+'/**',async route=>{
const path=new URL(route.request().url()).pathname;
if(path==='/')return route.fulfill({body:'<!doctype html><title>Credential fixture</title>',contentType:'text/html'});
if(!allow.has(path))return route.abort();
return route.fulfill({body:await readFile(resolve(import.meta.dirname,'..','.'+path)),contentType:'text/javascript'});
});
const page=context.pages()[0]??await context.newPage();
await page.goto(origin);
return {context,page,fixture};
}catch(error){
await context.close();
throw error;
}
}
async function connectWithSavedCredential(page){
return page.evaluate(async scope=>{
const {ReceiverVault}=await import('/src/foundry/receiver-vault.mjs');
const {GMMAWebSocket}=await import('/src/providers/ma/websocket.mjs');
const saved=await new ReceiverVault().loadCredential(scope);
if(!saved?.auto)return 'no-auto-credential';
const transport=new GMMAWebSocket({baseUrl:saved.maUrl,token:saved.token});
try{await transport.connect();return 'authenticated';}
catch(error){return error.code;}
finally{transport.close();}
},scope);
}
for(const engine of engines){
const profile=await mkdtemp(resolve(tmpdir(),'adaptive-music-vault-'));
let active;
try{
active=await startProfile(engine,profile);
const {page}=active;
const before=await page.evaluate(async({scope,credential})=>{
const {ReceiverVault}=await import('/src/foundry/receiver-vault.mjs');
const vault=new ReceiverVault();
await vault.saveCredential(scope,credential);
await vault.save({...scope,maUrl:credential.maUrl},{token:credential.token,identityStorage:{'sendspin-identity-sk':'fictional-device-only-identity'},targetName:credential.targetName});
const receiver=await vault.load({...scope,maUrl:credential.maUrl});
const keys=await new Promise((resolve,reject)=>{
const request=indexedDB.open('adaptive-music-private-receivers',1);
request.onerror=()=>reject(request.error);
request.onsuccess=()=>{
const connection=request.result;
const scan=connection.transaction('records').objectStore('records').getAll();
scan.onerror=()=>reject(scan.error);
scan.onsuccess=()=>{
resolve(scan.result.map(({key,data,iv})=>[key.extractable,data instanceof ArrayBuffer,iv.length]));
connection.close();
};
};
});
return {receiverHasToken:Object.hasOwn(receiver,'token'),keys};
},{scope,credential});
assert.deepEqual(before,{receiverHasToken:false,keys:[[false,true,12],[false,true,12]]});
assert.equal(await connectWithSavedCredential(page),'authenticated');
await active.context.close();
active=await startProfile(engine,profile);
assert.equal(await connectWithSavedCredential(active.page),'authenticated');
active.fixture.revoked=true;
assert.equal(await connectWithSavedCredential(active.page),'ws-auth-denied');
assert.equal(active.fixture.attempts,2);
const checks=await active.page.evaluate(async({scope,credential})=>{
const {ReceiverVault}=await import('/src/foundry/receiver-vault.mjs');
const vault=new ReceiverVault();
const reopened=await vault.loadCredential(scope);
const differentUser=await vault.loadCredential({...scope,userId:'ordinary-player'});
const differentWorld=await vault.loadCredential({...scope,campaign:'another-world'});
await vault.saveCredential(scope,{...reopened,auto:false});
const paused=(await vault.loadCredential(scope)).auto===false;
await vault.forgetCredential(scope);
return {reopened:reopened.token===credential.token&&reopened.maUrl===credential.maUrl&&reopened.auto,
differentUser,differentWorld,paused,forgotten:await vault.loadCredential(scope),
receiverRetained:!!await vault.load({...scope,maUrl:credential.maUrl})};
},{scope,credential});
assert.deepEqual(checks,{reopened:true,differentUser:null,differentWorld:null,paused:true,forgotten:null,receiverRetained:true});
await active.context.close();
active=await startProfile(engine,profile);
assert.equal(await connectWithSavedCredential(active.page),'no-auto-credential');
assert.equal(active.fixture.attempts,0);
console.log(JSON.stringify({engine,browser:active.context.browser().version(),lockedKeys:true,scopeIsolation:true,
authenticatedAfterBrowserRestart:true,revokedAuthDeniedByFixture:true,pause:true,forgetSurvivedBrowserRestart:true}));
}finally{
await active?.context.close();
await rm(profile,{recursive:true,force:true});
}
}
+88 -19
View File
@@ -1,5 +1,7 @@
// Browser diagnostics on the actual private HTTPS hosts. Records metadata only.
import {readFile, stat, writeFile} from 'node:fs/promises';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {mkdtemp, readFile, rm, stat, writeFile} from 'node:fs/promises';
import {lookup} from 'node:dns/promises';
import {isIP} from 'node:net';
import {resolve} from 'node:path';
@@ -7,10 +9,16 @@ import {probeWebSockets} from '../src/providers/ma/diagnostics.mjs';
const report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
const playback = process.argv.includes('--playback');
const layoutOnly = process.argv.includes('--layout-only');
const nativeSheet = process.argv.includes('--native-sheet');
const layoutOnly = process.argv.includes('--layout-only')||nativeSheet;
const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium';
const previewModule = process.argv.includes('--preview-module');
const engine = process.argv.includes('--firefox')?'firefox':process.argv.includes('--webkit')?'webkit':'chromium';
const packageOption=process.argv.indexOf('--package-preview');
const previewModule = process.argv.includes('--preview-module')||packageOption!==-1;
let packageDirectory;
const headed = process.argv.includes('--headed');
const long = process.argv.includes('--continuity');
const review = process.argv.includes('--review');
const expect = (ok, code) => { if (!ok) throw new Error(code); };
async function privateJSON(name) {
@@ -115,19 +123,43 @@ async function collectTransport(page, response, ma) {
async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password}, progress) {
expect(typeof name === 'string' && name && typeof password === 'string' && typeof gm === 'boolean', 'invalid-test-account');
const page = await browser.newPage({viewport: {width: 1440, height: 1000}, screen: {width: 1440, height: 1000}});
const context=await browser.newContext({viewport:{width:1440,height:1000},screen:{width:1440,height:1000}});
const page=await context.newPage();
if (previewModule) {
const prefix='/modules/adaptive-music/';
const root=resolve(import.meta.dirname,'..');
const root=packageDirectory?resolve(packageDirectory,'adaptive-music'):resolve(import.meta.dirname,'..');
await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
const file=new URL(route.request().url()).pathname.slice(prefix.length);
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..'))return route.continue();
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..')){
return packageDirectory?route.abort():route.continue();
}
await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
});
}
page.setDefaultTimeout(20000);
if(playback) await page.context().route(`${foundry.origin}/adaptive-continuity-test.mjs`,route=>route.fulfill({
path:resolve(import.meta.dirname,'browser-continuity-worklet.mjs'),contentType:'text/javascript',
}));
await retainBrowserWebSocket(page);
if (playback) await page.addInitScript(() => {
const timeline = {gaps:0, overlaps:0, maxGapMs:0, maxOverlapMs:0, contiguous:0};
let prior;
const start = AudioBufferSourceNode.prototype.start;
AudioBufferSourceNode.prototype.start = function(when, offset, duration) {
const {buffer,context}=this;
if (buffer && context===window.__adaptiveMusicTestAudio.contexts[0]?.context && Number.isFinite(when) && when>0) {
const length=(duration??buffer.duration-(offset??0))/this.playbackRate.value;
if (prior?.context===context && when>=prior.start && Math.abs(when-prior.end)<0.2) {
const delta=(when-prior.end)*1000;
if(delta>0.1){timeline.gaps++;timeline.maxGapMs=Math.max(timeline.maxGapMs,delta);}
else if(delta < -0.1){timeline.overlaps++;timeline.maxOverlapMs=Math.max(timeline.maxOverlapMs,-delta);}
else timeline.contiguous++;
}
prior={context,start:when,end:when+length};
}
return start.apply(this,arguments);
};
window.__adaptiveMusicTestTimeline=timeline;
const peers = [];
const contexts = [];
const analysers = [];
@@ -140,9 +172,26 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
return destination;
};
const createAnalyser = AudioContext.prototype.createAnalyser;
const modules = new WeakMap();
function measure(context,analyser,report) {
if(!context.audioWorklet)return;
if(!modules.has(context))modules.set(context,context.audioWorklet.addModule('/adaptive-continuity-test.mjs'));
modules.get(context).then(()=>{
const node=new AudioWorkletNode(context,'adaptive-continuity-meter');
const sink=context.createGain();sink.gain.value=0;
report.meterPort=node.port;
node.port.onmessage=event=>{
report.continuity=event.data;
if(event.data.phaseStarted)report.phaseStarted=event.data;
};
analyser.connect(node).connect(sink).connect(context.destination);
}).catch(()=>{report.meterFailed=true;});
}
AudioContext.prototype.createAnalyser = function () {
const analyser = createAnalyser.call(this);
analysers.push(analyser);
const report=contexts.find(entry=>entry.context===this);
if(report&&!report.measuring){report.measuring=true;report.analyser=analyser;measure(this,analyser,report);}
return analyser;
};
const createSource = AudioContext.prototype.createMediaStreamSource;
@@ -150,7 +199,9 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
const source = createSource.call(this, stream);
const analyser = createAnalyser.call(this);
source.connect(analyser);
listenerAnalysers.push({context: this, stream, analyser});
const report={context: this, stream, analyser};
listenerAnalysers.push(report);
measure(this,analyser,report);
return source;
};
window.__adaptiveMusicTestPeers = peers;
@@ -203,7 +254,7 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
expect(state.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
// Keep the unattended canvases from saturating the shared headless renderer.
state.canvasTickerPaused = await page.evaluate(() => {
state.canvasTickerPaused = (!headed||review) && await page.evaluate(() => {
const ticker = globalThis.canvas?.app?.ticker;
if (!ticker?.started) return false;
ticker.stop();
@@ -214,24 +265,38 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
let browser, stage = 'configuration';
try {
if(packageOption!==-1){
stage='package-preview-validation';
const archive=process.argv[packageOption+1];
expect(archive&&!archive.startsWith('-'),'package-preview-path-required');
packageDirectory=await mkdtemp('.local/v080-package-preview-');
report.runtimeAssetsSHA256=execFileSync('python3',[resolve(import.meta.dirname,'release.py'),'--runtime-sha256',archive],{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();
execFileSync('python3',['-m','zipfile','-e',archive,packageDirectory],{stdio:'ignore'});
report.packageSHA256=createHash('sha256').update(await readFile(archive)).digest('hex');
}
const config = await privateJSON('live-environment');
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
const proxyIP = config.proxy_ip;
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
stage = 'browser-launch';
if (engine === 'firefox') {
if (engine !== 'chromium') {
for (const host of [foundry.hostname, ma.hostname]) {
const answers = await lookup(host, {all: true});
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required');
}
}
browser = await playwright[engine].launch(engine === 'chromium' ? {args: ['--no-sandbox', '--no-proxy-server',
browser = await playwright[engine].launch(engine === 'chromium' ? {headless: !headed,
...(review&&headed&&{ignoreDefaultArgs:['--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows','--disable-renderer-backgrounding']}),
args: ['--no-sandbox', '--no-proxy-server',
`--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} :
{firefoxUserPrefs: {'network.trr.mode': 5, 'network.proxy.type': 0}});
{headless: !headed,...(engine==='firefox'&&{firefoxUserPrefs:{'network.trr.mode':5,'network.proxy.type':0}})});
report.engine = engine;
report.browser = browser.version();
report.moduleAssets = previewModule ? 'workspace module assets in the test browser' : 'installed module assets';
report.headed = headed;
report.moduleAssets = packageDirectory?'validated ZIP assets in the test browser':previewModule?
'workspace module assets in the test browser':'installed module assets';
for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
stage = name;
@@ -265,24 +330,28 @@ try {
}
if(layoutOnly){
stage='foundry-graphical-layout';
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs');
report.layout=await checkFoundryLayout(pages[0],ma);
const {checkFoundryLayout,checkNativeSceneSheet}=await import('./live_foundry_playback.mjs');
if(nativeSheet)await checkNativeSceneSheet(pages[0],report);
else report.layout=await checkFoundryLayout(pages[0],ma);
}
if (playback) {
stage = 'installed-world-playback';
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs');
stage = 'development-world-playback';
const {checkFoundryPlayback,checkFoundryV080Review} = await import('./live_foundry_playback.mjs');
report.playback = {};
await checkFoundryPlayback({pages, ma, world, report: report.playback});
const run=review?checkFoundryV080Review:checkFoundryPlayback;
await run({pages, ma, world, report: report.playback, long});
}
}
report.completed = true;
} catch (error) {
if(error.name==='SyntaxError')console.error(error.stack);
report.completed = false;
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
process.exitCode = 1;
} finally {
await browser?.close();
const resultName=previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
if(packageDirectory)await rm(packageDirectory,{recursive:true,force:true});
const resultName=nativeSheet?`foundry-native-sheet-${engine}`:review?`foundry-v080-review-${engine}`:headed?`foundry-headed-${previewModule?'candidate':'installed'}-${engine}`:previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
console.log(JSON.stringify(report, null, 2));
}
+71
View File
@@ -0,0 +1,71 @@
// Measure the v0.7.2 per-packet clock mapping and the new scheduler in actual
// OfflineAudioContexts against the same deterministic stereo PCM and clock trace.
import {readFile} from 'node:fs/promises';
const playwright=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
const engines=process.argv.includes('--webkit')?['chromium','firefox','webkit']:['chromium','firefox'];
const source=await readFile(new URL('../src/audio/pcm-timeline.mjs',import.meta.url),'utf8');
for(const engine of engines){
const browser=await playwright[engine].launch({headless:!process.argv.includes('--headed')});
try{
const page=await browser.newPage();
await page.route('https://fixture.invalid/**',route=>route.fulfill({
contentType:route.request().url().endsWith('.mjs')?'text/javascript':'text/html',
body:route.request().url().endsWith('.mjs')?source:'<!doctype html><title>PCM fixture</title>'
}));
await page.goto('https://fixture.invalid/');
const cases=await page.evaluate(async()=>{
const {PcmTimeline}=await import('/pcm.mjs');
async function run(legacy,inputRate,outputRate){
const context=new OfflineAudioContext(2,Math.round(outputRate*9),outputRate);
let now=0;
const playback={
get currentTime(){return now;}, state:'running',
createBuffer:(...args)=>context.createBuffer(...args),
createBufferSource:()=>context.createBufferSource()
};
const timeline=new PcmTimeline(playback,context.destination);
const length=inputRate/50;
const fraction=128/outputRate;
for(let packet=0;packet<400;packet++){
const samples=[new Float32Array(length),new Float32Array(length)];
for(let i=0;i<length;i++){
samples[0][i]=0.45*Math.cos(2*Math.PI*997*(packet*length+i)/inputRate);
samples[1][i]=0.45*Math.sin(2*Math.PI*997*(packet*length+i)/inputRate);
}
const sent=packet/50+0.367+0.012*Math.sin(packet);
now=Math.floor((sent-0.367)/fraction)*fraction;
const serverNowUs=(sent-0.367)*1e6;
const serverTimeUs=(packet/50+0.367)*1e6;
if(legacy){
const buffer=context.createBuffer(2,length,inputRate);
samples.forEach((channel,index)=>buffer.copyToChannel(channel,index));
const node=context.createBufferSource();node.buffer=buffer;node.connect(context.destination);
node.start(Math.max(now+0.01,now+(serverTimeUs-serverNowUs)/1e6));
}else timeline.push({samples,sampleRate:inputRate,serverTimeUs},serverNowUs);
}
const rendered=await context.startRendering();
const left=rendered.getChannelData(0),right=rendered.getChannelData(1);
let dropouts=0,clipped=0,nearSilenceSamples=0,run=0,largestRun=0,jumps=0;
for(let i=outputRate;i<outputRate*8;i++){
const quiet=Math.hypot(left[i],right[i])<0.05;
if(quiet){run++;nearSilenceSamples++;}
else if(run){
if(run>=outputRate*0.00075)dropouts++;
largestRun=Math.max(largestRun,run);
run=0;
}
if(Math.max(Math.abs(left[i]),Math.abs(right[i]))>=0.999)clipped++;
if(Math.hypot(left[i]-left[i-1],right[i]-right[i-1])>0.23)jumps++;
}
return {dropouts,clipped,nearSilenceSamples,largestRun,jumps};
}
const result=[];
for(const [sourceRate,contextRate] of [[48000,48000],[44100,48000],[48000,44100]]){
result.push({sourceRate,contextRate,baseline:await run(true,sourceRate,contextRate),candidate:await run(false,sourceRate,contextRate)});
}
return result;
});
console.log(JSON.stringify({engine,version:browser.version(),cases}));
if(cases.some(({baseline,candidate})=>baseline.dropouts===0||candidate.dropouts!==0||candidate.clipped!==0||candidate.jumps>=baseline.jumps))process.exitCode=1;
}finally{await browser.close();}
}
+90 -9
View File
@@ -1,14 +1,27 @@
// Offline Chromium UI fixture. No Foundry, MA, Git host, token or production access.
import {createServer} from 'node:http';
import {readFile,mkdir} from 'node:fs/promises';
import {readFile,mkdir,realpath} from 'node:fs/promises';
import {resolve,extname} from 'node:path';
import {chromium} from 'playwright';
import assert from 'node:assert/strict';
const playwright=await import(process.env.AM_PLAYWRIGHT_MODULE??'playwright');
const engine=process.argv.includes('--firefox')?'firefox':process.argv.includes('--webkit')?'webkit':'chromium';
const root=resolve(import.meta.dirname,'..');
const server=createServer(async(req,res)=>{try{const path=resolve(root,'.'+new URL(req.url,'http://localhost').pathname);if(!path.startsWith(root+'/'))throw Error();const data=await readFile(path);res.setHeader('Content-Type',extname(path)==='.mjs'?'text/javascript':extname(path)==='.css'?'text/css':'text/html');res.end(data);}catch{res.writeHead(404);res.end();}});
const isFixtureAsset=path=>path==='/tests/browser/setup.html'||/^\/src\/[\w/-]+\.mjs$/.test(path)||path==='/styles/adaptive-music.css';
const server=createServer(async(req,res)=>{
try{
const asset=new URL(req.url,'http://localhost').pathname;
if(req.method!=='GET'||!isFixtureAsset(asset))throw Error();
const path=await realpath(resolve(root,'.'+asset));
if(path!==root+asset)throw Error();
const data=await readFile(path);
res.setHeader('Content-Type',extname(path)==='.mjs'?'text/javascript':extname(path)==='.css'?'text/css':'text/html');
res.end(data);
}catch{res.writeHead(404);res.end();}
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));let browser;
try{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});const page=await browser.newPage({viewport:{width:1000,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
browser=await playwright[engine].launch({headless:true,...(engine==='chromium'&&{args:['--no-sandbox']})});
const page=await browser.newPage({viewport:{width:1000,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}/tests/browser/setup.html`);await page.waitForFunction(()=>window.ready);
assert.equal(await page.getByText('Connect optional companion',{exact:true}).count(),0);
for(const width of [380,640,1000]){
@@ -16,9 +29,38 @@ try{
assert.equal(await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollWidth<=el.clientWidth+1),true,'setup must fit narrow window');
assert.equal(await page.getByLabel('ICE server URL').isVisible(),false,'advanced fields must remain hidden');
}
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
await page.evaluate(()=>window.nativeConfiguration());
const sidebar=page.locator('#fixture-playlists');
await sidebar.locator('summary').click();
assert.equal(await sidebar.locator('li').count(),0);
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');
await page.evaluate(()=>Object.defineProperty(navigator.clipboard,'writeText',{value:async text=>{window.copiedDiagnostics=text;}}));
await page.getByLabel('Private GM access token').fill('synthetic-secret-sentinel');
const copyDiagnostics=page.getByRole('button',{name:'Copy connection diagnostics'});
await page.getByRole('button',{name:'Connect',exact:true}).click();
await page.getByText(/^Connection failed\./).waitFor();
await copyDiagnostics.click();
let copied=await page.evaluate(()=>window.copiedDiagnostics);
const {at,...failure}=JSON.parse(copied).lastConnectFailure;
assert.ok(Number.isFinite(Date.parse(at)));
assert.deepEqual(failure,{code:'ws-upgrade-failed',stage:'API authentication'});
assert.doesNotMatch(copied,/synthetic-secret-sentinel|ma\.example\.test/);
await page.getByLabel('Private GM access token').fill('fixture-token');
await page.getByRole('button',{name:'Connect',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
await copyDiagnostics.click();
copied=await page.evaluate(()=>window.copiedDiagnostics);
assert.equal(JSON.parse(copied).lastConnectFailure,undefined);
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
await page.evaluate(()=>window.refreshNativeConfiguration());
const source=sidebar.getByText('Forest at night',{exact:true}),scene=page.locator('#fixture-scene');
await source.waitFor();
const ambient=scene.getByLabel('Ambient playlist');
const target=ambient.locator('..');
await source.dragTo(target);
assert.equal(await ambient.inputValue(),'["ma","ambient"]');
await scene.getByRole('button',{name:'Save assignments'}).click();
assert.deepEqual(await page.evaluate(()=>window.saved.ambient),{provider:'ma',id:'ambient'});
await page.evaluate(()=>window.closeNativeConfiguration());
await page.getByRole('button',{name:'Choose scene music',exact:true}).click();
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})});
await panel.locator('select').nth(0).selectOption('["ma","ambient"]');await panel.locator('select').nth(1).selectOption('["ma","combat"]');await panel.getByRole('button',{name:'Save assignments'}).click();
@@ -27,11 +69,50 @@ try{
await page.getByText('2 connected listeners',{exact:true}).waitFor();
await page.getByRole('button',{name:'Pause',exact:true}).click();await page.getByRole('button',{name:'Resume',exact:true}).click();
await page.getByLabel('Playback position').press('ArrowRight');await page.getByText('0:13 / 1:30',{exact:true}).waitFor();
await page.getByLabel('Repeat',{exact:true}).selectOption('all');
await page.waitForFunction(()=>document.querySelector('select[aria-label="Repeat"]').value==='all');
await page.getByLabel('Campaign volume').press('ArrowLeft');
assert.equal(await page.getByLabel('Campaign volume').inputValue(),'99');
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','stop']);
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',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','three setup tabs','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','track and listeners','pause/resume/seek/volume/stop','listener activation'],pageErrors:errors},null,2));
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: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));}
+462 -12
View File
@@ -1,4 +1,4 @@
// Exercises the installed module through the authorized development world.
// Exercises module playback in the authorized Foundry development world.
import {randomUUID} from 'node:crypto';
import {setTimeout as delay} from 'node:timers/promises';
import {loadMAToken} from '../gateway/private-config.mjs';
@@ -48,8 +48,8 @@ function observeMA(page, ma) {
if (entry.command === 'auth') entry.authenticated = frame.result?.authenticated === true;
if (entry.command === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
if (entry.command === 'player_queues/get' && frame.result) {
const {state, current_index, elapsed_time} = frame.result;
entry.queue = {state, index: current_index, position: elapsed_time};
const {state, current_index, elapsed_time, ended, repeat_mode} = frame.result;
entry.queue = {state, index: current_index, position: elapsed_time, ended, repeat:repeat_mode};
}
});
});
@@ -89,6 +89,7 @@ async function gmAudioDiagnostics(page, setup) {
return {
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead,
underruns:d.underruns,sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,bufferOverruns:d.bufferOverruns,
signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
};
@@ -105,7 +106,7 @@ async function openMenu(page, name) {
}, `${moduleId}.${name}`);
}
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat'].map(action => 'player_queues/' + action));
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat', 'pause', 'resume', 'seek', 'next', 'shuffle'].map(action => 'player_queues/' + action));
export async function checkFoundryLayout(page,ma){
await openMenu(page,'setup');
@@ -155,16 +156,83 @@ export async function checkFoundryLayout(page,ma){
return {resizable,layout,keyboardTabs:true,advancedCollapsed:true,invalidAddressRejected:true,missingTokenRejected:true,routeDiagnostics};
}
export async function checkFoundryPlayback({pages, ma, world, report}) {
export async function checkNativeSceneSheet(gm,report){
const details=await gm.evaluate(async()=>{
const scene=game.scenes.active??game.scenes.contents[0];
const app=scene?.sheet;
if(!app)return null;
await app.render({force:true});
return {type:app.constructor.name,documentName:app.document?.documentName,id:app.id,tag:app.element?.tagName};
});
check(details?.id,'native-scene-sheet-unavailable');
report.nativeSheet={type:details.type,documentName:details.documentName,tag:details.tag};
const shell=gm.locator(`[id="${details.id}"]`);
await shell.waitFor({state:'attached'});
const panel=shell.locator('[data-adaptive-music="assignments"]');
await panel.waitFor({state:'attached'});
report.nativeSheet.tab=await panel.evaluate(node=>node.closest('.tab')?.dataset.tab??null);
report.nativeSheet.navigationTabs=await shell.locator('nav [data-tab]').evaluateAll(nodes=>nodes.map(node=>node.dataset.tab));
if(report.nativeSheet.tab&&!await panel.isVisible()){
await gm.evaluate(({id,tab})=>foundry.applications.instances.get(id)?.changeTab(tab,'sheet'),{id:details.id,tab:report.nativeSheet.tab});
}
await panel.waitFor({state:'visible'});
report.nativeSheet.visible=true;
}
export async function checkFoundryPlayback({pages, ma, world, report, long=false}) {
const [gm, ...players] = pages;
const run = randomUUID().slice(0, 8);
const receiverName = `Adaptive Music integration ${run}`;
const fixtureName = `Adaptive Music verification ${run}`;
const setup = gm.locator('#adaptive-music-setup');
const wire = observeMA(gm, ma);
const continuity=(reset=false)=>Promise.all(pages.map(page=>page.evaluate(async reset=>{
const {contexts,listenerAnalysers}=window.__adaptiveMusicTestAudio;
const active=[...contexts.filter(item=>item.context.state==='running'),
...listenerAnalysers.filter(item=>[...document.querySelectorAll('audio')].some(audio=>audio.srcObject===item.stream))];
if(reset){
await Promise.all(active.map(async item=>{
const deadline=Date.now()+10000;
while(!item.meterPort&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,100));
if(!item.meterPort)return;
item.phaseStarted=null;
item.meterPort.postMessage('start-phase');
while(!item.phaseStarted&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,100));
}));
}
const meters=active.map(item=>reset?item.phaseStarted:item.continuity).filter(Boolean);
const rtp=(await game.modules.get('adaptive-music').api.peerStats()).filter(item=>item.type==='inbound-rtp');
return {meters,rtp,timeline:window.__adaptiveMusicTestTimeline,visible:!document.hidden};
},reset)));
const soak=async duration=>{
const initial=await continuity(true),start=performance.now(),checkpoints=[];
check(initial.every(client=>client.meters.length===1),'missing-continuity-meter');
do{
await delay(Math.min(5000,Math.max(1,duration-(performance.now()-start))));
const progress=await continuity();
checkpoints.push(progress);
if(checkpoints.length%12===0)console.error(`Continuity measurement: ${Math.round((performance.now()-start)/1000)} seconds in phase`);
if(progress.some(client=>client.meters.length!==1||client.meters[0].trailingZeroRun/client.meters[0].sampleRate>4))break;
}while(performance.now()-start<duration);
const seconds=(performance.now()-start)/1000,final=checkpoints.at(-1);
const clients=final.map((client,index)=>{
const first=initial[index].meters[0],last=client.meters[0];
const silenceSeconds=Math.max(0,...checkpoints.flatMap(point=>point[index].meters
.map(meter=>Math.max(meter.trailingZeroRun,meter.maxZeroRun)/meter.sampleRate)));
return {
renderedSeconds:last?(last.frames-first.frames)/last.sampleRate:0,
longestDigitalSilenceSeconds:silenceSeconds,
shortDropouts:last?last.shortDropouts-first.shortDropouts:null,
metersRetained:checkpoints.every(point=>point[index].meters.length===1),
rtpAudio:!index||((client.rtp[0]?.totalSamplesReceived??0)>(initial[index].rtp[0]?.totalSamplesReceived??0)),
};
});
return {seconds,initial,final,clients,passed:seconds>=duration/1000&&clients.every(client=>
client.metersRetained&&client.rtpAudio&&client.renderedSeconds>=seconds*0.95&&client.longestDigitalSilenceSeconds<=4)};
};
const stage = name => {
report.stage = name;
console.error(`Installed-world playback stage: ${name}`);
console.error(`Development-world playback stage: ${name}`);
};
let baseline, sceneId, combatId, receiver;
@@ -193,7 +261,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
game.modules.get(moduleId).api.stopDevelopment();
await game.settings.set(moduleId, 'enabled', false);
}
return {enabled, scene};
return {enabled, scene, connection:game.settings.get(moduleId,'savedConnection')};
}
if (data.action === 'cleanup') {
const api = game.modules.get(moduleId).api;
@@ -203,6 +271,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
if (data.baseline.scene && game.scenes.active?.id !== data.baseline.scene) await game.scenes.get(data.baseline.scene)?.activate();
if (data.sceneId) await game.scenes.get(data.sceneId)?.delete();
if (game.settings.get(moduleId, 'enabled') !== data.baseline.enabled) await game.settings.set(moduleId, 'enabled', data.baseline.enabled);
await game.settings.set(moduleId,'savedConnection',data.baseline.connection);
return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
}
@@ -260,16 +329,19 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
stage('user-document-permissions');
const gmId = await gm.evaluate(() => game.user.id);
const probeFlag = `integrationProbe${run}`;
report.playerCannotWriteGMFlag = await players[0].evaluate(async ({gmId, moduleId, probeFlag}) => {
report.playerFlagDenials = await Promise.all(players.map(player=>player.evaluate(async ({gmId, moduleId, probeFlag}) => {
try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
catch { return true; }
}, {gmId, moduleId, probeFlag});
}, {gmId, moduleId, probeFlag})));
report.playerCannotWriteGMFlag=report.playerFlagDenials.every(Boolean);
if (!report.playerCannotWriteGMFlag) await gm.evaluate(({moduleId, probeFlag}) => game.user.unsetFlag(moduleId, probeFlag), {moduleId, probeFlag});
check(report.playerCannotWriteGMFlag,'player-wrote-gm-user-flag');
stage('create-test-scene');
baseline = await fixture({action: 'baseline'});
sceneId = await fixture({action: 'scene', fixtureName});
await fixture({action: 'activate-scene', sceneId});
await gm.waitForFunction(id=>game.scenes.active?.id===id,sceneId,{polling:100});
await openMenu(gm, 'setup');
await gm.evaluate(()=>{
window.__adaptiveTestNotifications=[];
@@ -297,7 +369,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:50000});
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:85000});
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
check(receiver,'receiver-identity-not-verified');
report.oneClickConnection=true;
@@ -322,6 +394,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
stage('scene-assignments');
if(tabbed)await setup.getByLabel('Scene',{exact:true}).selectOption(sceneId);
const assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
const ambient = assignments.getByLabel('Ambient playlist');
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",')));
@@ -330,6 +403,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
await ambient.selectOption(references[0]);
await assignments.getByLabel('Combat playlist').selectOption(references[1]);
if(tabbed)await assignments.getByLabel('Default boss music').selectOption(references[1]);
check(await ambient.inputValue()===references[0],'ambient-selection-lost-before-save');
await assignments.getByRole('button', {name: 'Save assignments', exact: true}).click();
await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{
@@ -357,6 +431,18 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
report.ambient = await audio();
await delay(6500);
if(long){
stage('enable-dedicated-queue-repeat');
const repeat=wire.commands.length;
const repeatSelect=setup.getByLabel('Repeat',{exact:true});
report.repeatControl={visible:await repeatSelect.isVisible(),enabled:await repeatSelect.isEnabled().catch(()=>false),
queueRepeat:wire.commands.findLast(entry=>entry.queue)?.queue.repeat};
await repeatSelect.selectOption('all');
await command(repeat,'repeat',args=>args.repeat_mode==='all'&&args.queue_id===receiver);
stage('continuous-ambient');
report.continuity={ambient:await soak(30000)};
check(report.continuity.ambient.passed,'ambient-continuity-failed');
}
stage('actual-combat');
combatId = await fixture({action: 'combat', sceneId, fixtureName});
@@ -366,6 +452,11 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
await delay(4500);
report.combat = await audio();
if(long){
stage('continuous-combat');
report.continuity.combat=await soak(30000);
check(report.continuity.combat.passed,'combat-continuity-failed');
}
stage('ambient-restoration');
const restore = wire.commands.length;
@@ -379,6 +470,12 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
await delay(4500);
report.restoredAmbient = await audio();
if(long){
stage('continuous-restored-ambient');
report.continuity.restoredAmbient=await soak(1740000);
report.continuity.totalMeasuredSeconds=Object.values(report.continuity).reduce((total,phase)=>total+phase.seconds,0);
check(report.continuity.restoredAmbient.passed,'restored-ambient-continuity-failed');
}
report.onlyDedicatedQueueWritten = wire.commands.filter(entry => writes.has(entry.command)).every(entry => entry.args?.queue_id === receiver);
check(report.ambientOrderRestored && report.ambientIndexAndOffsetRestored && report.onlyDedicatedQueueWritten, 'queue-restore-or-ownership-mismatch');
@@ -415,7 +512,6 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
report.queueWrites = wire.commands.filter(entry => writes.has(entry.command)).map(({command, reply, error}) => ({command, reply: reply === true, error}));
if(report.stage!=='passed')report.playbackFailureDetails={
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})),
@@ -428,9 +524,10 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
const diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
return {
timeline: window.__adaptiveMusicTestTimeline,
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
signaling: window.__adaptiveMusicTestSignaling,
contexts: contexts.map(({context, destination}) => ({state: context.state, time: context.currentTime, track: destination.stream.getAudioTracks()[0]?.readyState})),
contexts: contexts.map(({context, destination,continuity}) => ({state: context.state, time: context.currentTime, continuity, track: destination.stream.getAudioTracks()[0]?.readyState})),
analyserRMS: analysers.map(analyser => {
const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples);
@@ -454,5 +551,358 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
report.temporaryWorldChangesRestored = await fixture({action: 'cleanup', sceneId, combatId, baseline}).catch(() => false);
}
}
const queueWrites=wire.commands.filter(entry=>writes.has(entry.command));
report.onlyDedicatedQueueWritten=Boolean(receiver)&&queueWrites.length>0&&queueWrites.every(entry=>entry.args?.queue_id===receiver);
report.queueWrites=queueWrites.map(({command,reply,error})=>({command,reply:reply===true,error}));
}
check(report.temporaryWorldChangesRestored,'test-world-cleanup-not-verified');
check(report.onlyDedicatedQueueWritten,'non-dedicated-write');
}
// Candidate GUI acceptance. Public Foundry document APIs create and activate the
// dedicated fixtures. Assignment, transport, and credential actions use the GUI.
export async function checkFoundryV080Review({pages,ma,world,report}) {
const [gm,...players]=pages;
const namespace='adaptive-music';
const receiverName='Adaptive Music integration '+randomUUID().slice(0,8);
const names=['Adaptive Music v0.8 — Ambience','Adaptive Music v0.8 — Combat and boss'];
const setup=gm.locator('#adaptive-music-setup');
const controls=gm.locator('#adaptive-music-controls');
const playlistIndexes=(process.env.AM_REVIEW_PLAYLIST_INDEXES??'0,1,2').split(',').map(Number);
check(playlistIndexes.length===3&&new Set(playlistIndexes).size===3&&playlistIndexes.every(index=>Number.isSafeInteger(index)&&index>=0),
'three-distinct-review-playlist-indexes-required');
const token=await loadMAToken('.local');
const wire=observeMA(gm,ma);
const stage=name=>{report.stage=name;console.error('v0.8.0 GUI review stage:',name);};
let saved,scenes=[],combatId;
const documentAction=(action,args={})=>gm.evaluate(async({action,args,world,namespace})=>{
if(!game.ready||game.world.id!==world||!game.user.isGM)throw Error('wrong-development-world');
const module=game.modules.get(namespace);
if(action==='baseline'){
const state={scene:game.scenes.active?.id,enabled:game.settings.get(namespace,'enabled'),
connection:game.settings.get(namespace,'savedConnection'),nativePlaylists:game.playlists.map(playlist=>playlist.id).sort()};
if(state.enabled){module.api.stopDevelopment();await game.settings.set(namespace,'enabled',false);}
return state;
}
if(action==='add-scene'){
const scene=await CONFIG.Scene.documentClass.create({name:args.name,width:1200,height:1000,navigation:true,tokenVision:false});
return scene.id;
}
if(action==='activate')return !!(await game.scenes.get(args.scene)?.activate());
if(action==='open-scene'){
const sheet=game.scenes.get(args.scene).sheet;
await sheet.render({force:true,position:{left:120,top:100}});
return sheet.id;
}
if(action==='close-scene')return game.scenes.get(args.scene).sheet.close();
if(action==='add-combat'){
const combat=await CONFIG.Combat.documentClass.create({scene:args.scene,active:true});
await combat.createEmbeddedDocuments('Combatant',[{name:'Development boss',initiative:12}]);
return combat.id;
}
if(action==='start-combat')return game.combats.get(args.combat).startCombat();
if(action==='delete-combat')return game.combats.get(args.combat)?.delete();
if(action==='cleanup'){
module.api.stopDevelopment();
await module.api.closeGMHost();
if(args.combat)await game.combats.get(args.combat)?.delete();
if(args.baseline.scene&&game.scenes.active?.id!==args.baseline.scene)await game.scenes.get(args.baseline.scene)?.activate();
if(game.settings.get(namespace,'enabled')!==args.baseline.enabled)await game.settings.set(namespace,'enabled',args.baseline.enabled);
if(JSON.stringify(game.settings.get(namespace,'savedConnection'))!==JSON.stringify(args.baseline.connection)){
await game.settings.set(namespace,'savedConnection',args.baseline.connection);
}
for(const [index,id] of args.scenes.entries()){
const scene=game.scenes.get(id);
if(!args.keepScenes||game.scenes.some(other=>other.id!==id&&other.name===args.names[index]))await scene?.delete();
else await scene?.update({name:args.names[index],navigation:true});
}
return {demonstrationScenes:args.names.filter(name=>game.scenes.some(scene=>scene.name===name)).length,
activeSceneRestored:(game.scenes.active?.id??null)===(args.baseline.scene??null),
automationRestored:game.settings.get(namespace,'enabled')===args.baseline.enabled,
accountEnvelopeRestored:JSON.stringify(game.settings.get(namespace,'savedConnection'))===JSON.stringify(args.baseline.connection),
nativePlaylistInventoryUnchanged:JSON.stringify(game.playlists.map(playlist=>playlist.id).sort())===JSON.stringify(args.baseline.nativePlaylists),
temporaryCombatRemoved:!args.combat||!game.combats.has(args.combat)};
}
throw Error('invalid-fixture-action');
},{action,args,world:world.id,namespace});
const selectTab=label=>setup.getByRole('tab',{name:label,exact:true}).click();
const connected=()=>setup.getByText(/^Connected · \d+ catalog choices$/).waitFor({timeout:65000});
const openSetup=async()=>{
if(await setup.isVisible())return;
await openMenu(gm,'setup');
};
const openPlaylists=async()=>{
const catalog=gm.locator('.adaptive-catalog');
if(!await catalog.isVisible()){
report.sidebarState=await gm.evaluate(()=>{
const directory=ui.playlists;
ui.sidebar?.expand();
directory?.activate();
return {directoryAvailable:Boolean(directory),expanded:ui.sidebar?.expanded,
renderState:directory?.rendered,elementConnected:directory?.element?.isConnected};
});
}
await catalog.waitFor({state:'visible'});
if(!await catalog.getByRole('button',{name:'Music controls'}).isVisible())await catalog.locator('summary').click();
return catalog;
};
const openControls=async()=>{
if(await controls.isVisible()){
await gm.evaluate(()=>foundry.applications.instances.get('adaptive-music-controls')?.bringToFront());
return;
}
const list=await openPlaylists();
await list.getByRole('button',{name:'Music controls'}).click();
};
const reload=async()=>{
await gm.reload({waitUntil:'domcontentloaded'});
await gm.waitForFunction(id=>game.ready&&game.world.id===id&&game.user.isGM&&game.socket?.connected,world.id,{polling:250,timeout:60000});
};
const command=(index,action,predicate=()=>true)=>until(()=>wire.commands.slice(index).find(entry=>
entry.command==='player_queues/'+action&&entry.reply&&entry.error===null&&predicate(entry.args)),
Boolean,'ma-'+action.replaceAll('_','-')+'-not-verified',65000);
const heard=async()=>Promise.all(players.map(async player=>{
const initial=await safeStats(player);
const end=await until(()=>safeStats(player),value=>value.bytes>initial.bytes&&
(value.rms>0.001||value.energy>initial.energy+1e-6),'review-listener-audio-missing',30000);
return {rms:end.rms,energyDelta:end.energy-initial.energy};
}));
let receiver;
try{
stage('setup-menu');
await gm.bringToFront();
saved=await documentAction('baseline');
await openSetup();
await gm.evaluate(()=>{
window.__adaptiveReviewWarnings=[];
new MutationObserver(()=>{
for(const notice of document.querySelectorAll('#notifications .notification')){
const message=notice.textContent.trim();
if(message.startsWith('Adaptive Music: ')&&!window.__adaptiveReviewWarnings.includes(message))window.__adaptiveReviewWarnings.push(message);
}
}).observe(document.body,{childList:true,subtree:true});
});
stage('graphical-connection');
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
await setup.getByLabel('Private GM access token').fill(token);
await setup.getByLabel('Remember credentials and reconnect on this trusted device').check();
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await connected();
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
check(receiver,'dedicated-review-receiver-not-confirmed');
report.guiConnection=true;
await gm.evaluate(()=>foundry.applications.instances.get('adaptive-music-setup').close());
stage('native-scene-assignments-and-playlist-sidebar');
for(const name of names)scenes.push(await documentAction('add-scene',{name:name+' '+receiverName.split(' ').at(-1)}));
stage('playlist-sidebar');
const catalog=await openPlaylists();
await catalog.locator('li').first().waitFor();
const priorities=['Ambient playlist','Combat playlist','Default boss music'];
let keys;
let usedPointerDrag=false;
for(const [index,scene] of scenes.entries()){
stage('scene-config-'+(index+1));
const sheetId=await documentAction('open-scene',{scene});
const shell=gm.locator(`[id="${sheetId}"]`);
const fieldset=shell.locator('fieldset[data-adaptive-music="assignments"]');
await fieldset.waitFor({state:'attached'});
const tab=await fieldset.evaluate(node=>node.closest('.tab')?.dataset.tab);
if(tab&&!await fieldset.isVisible())await gm.evaluate(({sheetId,tab})=>
foundry.applications.instances.get(sheetId)?.changeTab(tab,'sheet'),{sheetId,tab});
stage('scene-config-catalog-'+(index+1));
const options=await fieldset.getByLabel('Ambient playlist').locator('option').evaluateAll(items=>items
.filter(item=>item.value.startsWith('["ma",')).map(item=>({value:item.value,name:item.textContent.replace(/^Music Assistant: /,'')})));
check(playlistIndexes.every(index=>options[index]),'review-playlist-index-out-of-range');
keys??=playlistIndexes.map(index=>options[index]);
for(const [slot,label] of priorities.entries()){
const choice=keys[(index+slot)%keys.length],target=fieldset.getByLabel(label);
if(index===0&&slot===0){
stage('scene-config-pointer-drag');
const entries=catalog.locator('li');
const row=await entries.evaluateAll((nodes,value)=>nodes.findIndex(node=>node.dataset.reference===value),choice.value);
check(row>=0,'assigned-playlist-missing-from-foundry-sidebar');
const source=entries.nth(row),destination=target.locator('..');
report.dragEndpoints={sourceVisible:await source.isVisible(),destinationVisible:await destination.isVisible()};
await source.dragTo(destination,{targetPosition:{x:15,y:8}});
usedPointerDrag=await target.inputValue()===choice.value;
check(usedPointerDrag,'native-playlist-pointer-drag-failed');
}
stage('scene-config-select-'+(index+1)+'-'+(slot+1));
await target.selectOption(choice.value);
}
stage('save-scene-config-'+(index+1));
await fieldset.getByRole('button',{name:'Save assignments'}).click();
await fieldset.getByText('Assignments saved.',{exact:true}).waitFor();
await documentAction('close-scene',{scene});
}
report.nativeAssignments=2;
report.playlistSidebarEntries=await catalog.locator('li').count();
report.pointerDragAssigned=usedPointerDrag;
check(usedPointerDrag,'native-playlist-pointer-drag-failed');
stage('gameplay-controls-and-scene-automation');
await documentAction('activate',{scene:scenes[0]});
const toolbar=gm.locator('button[data-tool="adaptiveMusic"],button[data-control="adaptiveMusic"],button[data-tooltip="Adaptive Music controls"]').filter({visible:true});
await toolbar.first().click();
await controls.waitFor();
report.toolbarOpened=true;
await gm.evaluate(()=>foundry.applications.instances.get('adaptive-music-controls').close());
await openControls();
await controls.waitFor();
report.sidebarOpened=true;
const writeIndex=wire.commands.length;
await controls.getByRole('button',{name:'Enable automation'}).click();
const ambientFirst=await command(writeIndex,'play_media',args=>args.option==='replace');
await Promise.all(players.map(async page=>{
await openMenu(page,'listen');
await page.locator('#adaptive-music-listener').getByRole('button',{name:'Enable Audio'}).click();
}));
await controls.getByText('2 connected listeners',{exact:true}).waitFor({timeout:40000});
report.listenerAudio={firstScene:await heard()};
const sceneChange=wire.commands.length;
await documentAction('activate',{scene:scenes[1]});
const ambientSecond=await command(sceneChange,'play_media',args=>args.option==='replace');
check(JSON.stringify(ambientFirst.args.media)!==JSON.stringify(ambientSecond.args.media),'scene-ambient-did-not-change');
report.listenerAudio.secondScene=await heard();
await delay(8500);
stage('combat-then-boss-then-restoration');
combatId=await documentAction('add-combat',{scene:scenes[1]});
const beforeCombat=wire.commands.length;
await documentAction('start-combat',{combat:combatId});
const combat=await command(beforeCombat,'play_media',args=>args.option==='replace');
check(JSON.stringify(ambientSecond.args.media)!==JSON.stringify(combat.args.media),'combat-did-not-change-playlist');
await delay(3500);
stage('boss-override');
await openSetup();
await selectTab('Scene Music');
await setup.getByText('World defaults and boss combatants',{exact:true}).click();
const boss=setup.getByLabel('Boss combatant');
const combatantId=await gm.evaluate(id=>game.combats.get(id)?.combatants.contents[0]?.id,combatId);
check(combatantId,'review-combatant-unavailable');
await boss.selectOption(`${combatId}:${combatantId}`);
await setup.getByLabel('Boss override',{exact:true}).check();
const beforeBoss=wire.commands.length;
await setup.getByRole('button',{name:'Save boss override'}).click();
const bossTrack=await command(beforeBoss,'play_media',args=>args.option==='replace');
check(JSON.stringify(combat.args.media)!==JSON.stringify(bossTrack.args.media),'boss-did-not-change-playlist');
report.listenerAudio.boss=await heard();
stage('restoration-after-boss');
const beforeRestore=wire.commands.length;
await documentAction('delete-combat',{combat:combatId});combatId=null;
const seek=await command(beforeRestore,'play_index');
const restored=await command(beforeRestore,'play_media',args=>args.option==='add');
const snapshot=wire.commands.slice(beforeCombat,wire.commands.indexOf(combat)).findLast(entry=>entry.queue?.state==='playing')?.queue;
check(JSON.stringify(ambientSecond.args.media)===JSON.stringify(restored.args.media)&&snapshot&&seek.args.index===snapshot.index&&
Math.abs(seek.args.seek_position-snapshot.position)<=2&&seek.args.seek_position>0,'ambient-restore-not-verified');
report.sceneCombatBossAndRestoration=true;
report.restoredSeconds=seek.args.seek_position;
report.listenerAudio.restored=await heard();
stage('manual-override-and-playback-actions');
await openControls();
await controls.getByText('Manual playlist override',{exact:true}).click();
const beforeManual=wire.commands.length;
await controls.getByLabel('Override playlist').selectOption(keys[0].value);
await controls.getByRole('button',{name:'Apply override'}).click();
await command(beforeManual,'play_media',args=>args.option==='replace');
stage('return-to-scene-music');
await controls.getByRole('button',{name:'Return to scene music'}).click();
await controls.getByText('Automation active',{exact:true}).waitFor();
stage('pause-and-resume');
await controls.getByRole('button',{name:'Pause',exact:true}).click();
await controls.getByText('Paused',{exact:true}).waitFor();
await controls.getByRole('button',{name:'Resume',exact:true}).click();
await controls.getByText('Playing',{exact:true}).waitFor();
stage('seek-and-skip');
const seekStart=wire.commands.length;
await controls.getByLabel('Playback position').press('ArrowRight');
await command(seekStart,'seek');
const skip=wire.commands.length;
await controls.getByRole('button',{name:'Skip track'}).click();
await command(skip,'next');
await controls.getByLabel('Campaign volume').press('ArrowLeft');
stage('background-gm-tab');
const [cover]=await Promise.all([
gm.waitForEvent('popup'),gm.evaluate(()=>{window.open('about:blank','_blank');}),
]);
await cover.bringToFront();
const time=()=>gm.evaluate(()=>{
const context=window.__adaptiveMusicTestAudio.contexts.at(-1);
const meter=context?.continuity;
const analyser=context?.analyser,samples=new Float32Array(analyser?.fftSize??1);
analyser?.getFloatTimeDomainData(samples);
return {visible:!document.hidden,time:context?.context.currentTime??0,frames:meter?.frames??0,
trailingSilence:meter?meter.trailingZeroRun/meter.sampleRate:null,
outputRMS:Math.sqrt(samples.reduce((sum,sample)=>sum+sample*sample,0)/samples.length)};
});
const [beforeBackground,beforeListeners]=await Promise.all([time(),Promise.all(players.map(safeStats))]);
await delay(12000);
const [afterBackground,afterListeners]=await Promise.all([time(),Promise.all(players.map(safeStats))]);
report.backgroundTab={hidden:!afterBackground.visible,contextSeconds:afterBackground.time-beforeBackground.time,
outputFrameDelta:afterBackground.frames-beforeBackground.frames,trailingSilenceSeconds:afterBackground.trailingSilence,
gmOutputRMS:afterBackground.outputRMS,
listenersWithContinuedAudio:afterListeners.map((listener,index)=>listener.bytes>beforeListeners[index].bytes&&
(listener.rms>0.001||listener.energy>beforeListeners[index].energy+1e-6))};
await cover.close();await gm.bringToFront();
await controls.getByRole('button',{name:'Stop playback'}).click();
await controls.getByText('Stopped',{exact:true}).waitFor();
report.manualAndPlayback=true;
stage('device-reconnect-disconnect-and-forget');
const beforeReload=wire.commands.length;
await reload();
await openSetup();await connected();
check(wire.commands.slice(beforeReload).some(entry=>entry.player?.id===receiver),'remembered-receiver-did-not-reconnect');
check(!wire.commands.slice(beforeReload).some(entry=>writes.has(entry.command)),'auto-reconnect-replaced-dedicated-queue');
check(await setup.getByLabel('Private GM access token').inputValue()==='','credential-field-leaked');
report.tokenFreeReload=true;
await setup.getByRole('button',{name:'Disconnect',exact:true}).click();
await setup.getByText(/Automatic reconnection is paused/).waitFor();
const disconnected=wire.commands.length;
await reload();
await openSetup();
await setup.getByRole('button',{name:'Connect',exact:true}).waitFor();
await delay(1800);
check(!wire.commands.slice(disconnected).some(entry=>entry.command==='auth'),'automatic-reconnect-after-disconnect');
await setup.getByRole('button',{name:'Connect',exact:true}).click();await connected();
await setup.getByRole('button',{name:'Forget Credentials',exact:true}).click();
await setup.getByText('Credentials removed from this device.',{exact:true}).waitFor();
const forgotten=wire.commands.length;
await reload();
await openSetup();
await setup.getByRole('button',{name:'Connect',exact:true}).waitFor();
await delay(1800);
check(!wire.commands.slice(forgotten).some(entry=>entry.command==='auth'),'automatic-reconnect-after-forgetting');
check(!await setup.getByRole('button',{name:'Forget Credentials'}).isVisible(),'device-credential-remains-after-forgetting');
report.disconnectPausesAutoReconnect=true;
report.forgetPreventsAutoReconnect=true;
const browserRenderedAudio=report.backgroundTab.outputFrameDelta>0&&report.backgroundTab.trailingSilenceSeconds<=4||
report.backgroundTab.gmOutputRMS>0.001;
check(report.backgroundTab.hidden&&report.backgroundTab.contextSeconds>=10&&browserRenderedAudio&&
report.backgroundTab.listenersWithContinuedAudio.every(Boolean),'background-render-not-verified');
stage('passed');
}finally{
report.onlyDedicatedQueueWritten=Boolean(receiver)&&wire.commands.filter(entry=>writes.has(entry.command)).every(entry=>entry.args?.queue_id===receiver);
report.queueWrites=wire.commands.filter(entry=>writes.has(entry.command)).map(({command,reply,error})=>({command,reply:reply===true,error}));
if(report.stage!=='passed')report.connectionVerification={
apiAuthenticated:wire.commands.some(entry=>entry.authenticated),
sendspinAuthenticated:wire.sendspinAuthenticated(),
lastCommandError:wire.commands.filter(entry=>entry.reply&&entry.error!==null).map(({command,error})=>({command,error})).at(-1),
recentMACommands:wire.commands.slice(-24).map(({command,reply,error})=>({command,reply:reply===true,error})),
notifications:await gm.evaluate(()=>window.__adaptiveReviewWarnings??[]).catch(()=>[]),
combatState:combatId?await gm.evaluate(id=>{
const combat=game.combats.get(id);
return {active:combat?.active,started:combat?.started,onActiveScene:(combat?.scene?.id??combat?.scene)===game.scenes.active?.id,
hasCombatCue:Boolean(game.scenes.active?.getFlag('adaptive-music','music')?.combat)};
},combatId).catch(()=>null):null,
};
if(saved)report.cleanup=await documentAction('cleanup',{combat:combatId,baseline:saved,scenes,names,
keepScenes:report.nativeAssignments===2&&report.sceneCombatBossAndRestoration===true}).catch(()=>null);
}
check(report.onlyDedicatedQueueWritten,'non-dedicated-write');
check(report.cleanup&&Object.entries(report.cleanup).every(([key,value])=>key==='demonstrationScenes'?value===2:value),'review-cleanup-not-verified');
}
+50 -10
View File
@@ -4,8 +4,9 @@ import argparse
import hashlib
import ipaddress
import json
from pathlib import Path
from pathlib import Path, PurePosixPath
import re
import stat
import subprocess
import sys
import urllib.parse
@@ -13,6 +14,8 @@ import zipfile
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music'
ZIP_TIME=(2000,1,1,0,0,0)
RELEASE_DOCS=('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md',
'TESTING.md','PROGRESS.md','HANDOFF.md','USER-ACCEPTANCE.md','LICENSE','THIRD-PARTY-NOTICES')
if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts'))
def public_url(value):
@@ -85,14 +88,20 @@ def validate_package(path,manifest=None):
from audit_repository import findings
with zipfile.ZipFile(path) as archive:
names=archive.namelist()
if len(names)!=len(set(names)) or any(not n.startswith('adaptive-music/') or '..' in Path(n).parts or '/.local/' in n or '/node_modules/' in n or '/gateway/' in n for n in names):raise ValueError('unsafe package inventory')
expected={'adaptive-music/'+name for name in module_files()}
if len(names)!=len(set(names)) or set(names)!=expected or any(
str(PurePosixPath(n))!=n or '\\' in n or any(part in ('..','.local','node_modules','gateway') for part in PurePosixPath(n).parts)
for n in names
) or any(
stat.S_IFMT(item.external_attr>>16) not in (0,stat.S_IFREG) for item in archive.infolist()
):raise ValueError('unsafe or incomplete package inventory')
actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual)
if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch')
for name in names:
data=archive.read(name);problems=findings(name,data.decode(errors='replace'))
if problems:raise ValueError('private content in release: '+name)
if name.endswith('.mjs'):
text=data.decode();relative_imports=re.findall(r"(?:from\s*|import\s*\()['\"](\.[^'\"]+)['\"]",text)
text=data.decode();relative_imports=re.findall(r"""\b(?:from\s*|import\s*(?:\(\s*)?)['"](\.[^'"]+)['"]""",text)
import posixpath
for relative in relative_imports:
resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative))
@@ -100,22 +109,48 @@ def validate_package(path,manifest=None):
for asset in actual['esmodules']+actual.get('styles',[]):
if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset')
provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json'))
if provenance!=json.loads((ROOT/'vendor/provenance.json').read_bytes()):raise ValueError('SDK provenance mismatch')
if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch')
required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt']
if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license')
return actual
def runtime_assets_sha256(path):
"""Fingerprint the installed browser assets independently of documentation."""
digest=hashlib.sha256()
prefixes=('adaptive-music/src/','adaptive-music/styles/','adaptive-music/vendor/')
with zipfile.ZipFile(path) as archive:
for name in sorted(n for n in archive.namelist() if n.startswith(prefixes)):
digest.update(name.encode('utf8')+b'\0')
digest.update(hashlib.sha256(archive.read(name)).digest())
return digest.hexdigest()
def local_revision():
try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError,FileNotFoundError):
file=ROOT/'SOURCE_REVISION.txt'
return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)'
def source_revision_status(manifest):
try:
status=subprocess.check_output(['git','status','--porcelain=v1','--untracked-files=all'],
cwd=ROOT,text=True,stderr=subprocess.DEVNULL)
except (subprocess.CalledProcessError,FileNotFoundError):
return 'source archive without Git metadata'
if status:
return 'working tree changes included; sourceCommit identifies the base revision'
manifest_bytes=(json.dumps(manifest,indent=2)+'\n').encode()
if (ROOT/'module.json').read_bytes()!=manifest_bytes:
return 'clean Git checkout with generated release manifest'
return 'clean Git checkout'
def source_entries(manifest):
from audit_repository import findings
try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0')
except (subprocess.CalledProcessError,FileNotFoundError):
names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in {'.gitignore','AGENTS.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','module.json','package.json','package-lock.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','SOURCE_REVISION.txt'}]
root_files={*RELEASE_DOCS,'.gitignore','AGENTS.md','MODEL-EVALUATION.md',
'module.json','package.json','package-lock.json','SOURCE_REVISION.txt'}
names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in root_files]
for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'):
names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc')
entries={}
@@ -135,7 +170,8 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
output=Path(output).resolve()
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
output.mkdir(parents=True,exist_ok=True)
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
allowed={*RELEASE_DOCS,'adaptive-music.zip','module.json','adaptive-music-source.zip','release.json',
'SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
evidence_name=f'evidence/v{version}-live.json'
if (ROOT/evidence_name).is_file():allowed.add(evidence_name)
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
@@ -149,16 +185,19 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
if evidence is not None:
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
(output/evidence_name).write_bytes(evidence)
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
for name in RELEASE_DOCS:(output/name).write_bytes(source['adaptive-music-source/'+name])
for path in (ROOT/'licenses').rglob('*'):
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
'sourceCommit':local_revision(),'sourceRevisionStatus':'base revision; included source archive is authoritative','sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False}
'sourceCommit':local_revision(),'sourceRevisionStatus':source_revision_status(manifest),'sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'runtimeAssetsSHA256':runtime_assets_sha256(output/'adaptive-music.zip'),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','networkAccessRequired':False}
acceptance=json.loads(evidence) if evidence is not None else {}
metadata['publicationReady']=acceptance.get('publicationReady') is True
metadata['foundryLiveVerified']=acceptance.get('serverInstalledExactVersion') is True
metadata['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') is True
metadata['acceptanceStatus']='staged; operator Mac and logged-in-world acceptance required' if not metadata['publicationReady'] else 'operator acceptance recorded'
metadata['publicationReady']=acceptance.get('publicationReady') is True and all(
metadata[key] for key in ('foundryLiveVerified','maCoreFlowDemonstrated','macPrivateRouteVerified')
)
metadata['acceptanceStatus']='staged; exact installed version and device acceptance pending' if not metadata['publicationReady'] else 'operator acceptance recorded'
(output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n')
files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')}
(output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items())))
@@ -167,6 +206,7 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
return bundle
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);args=parser.parse_args()
parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);parser.add_argument('--runtime-sha256',type=Path);args=parser.parse_args()
if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses')
elif args.runtime_sha256:validate_package(args.runtime_sha256);print(runtime_assets_sha256(args.runtime_sha256))
else:print(build_release(args.repository,args.version,args.output))
+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||[...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);
+65 -22
View File
@@ -1,3 +1,4 @@
import {PcmTimeline} from './pcm-timeline.mjs';
import {MusicError} from '../core/controller.mjs';
import {MAReadClient} from '../providers/ma/client.mjs';
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
@@ -11,10 +12,17 @@ export function gmAccessPolicy(baseUrl,pageUrl){
return target;
}
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[k];}};}
function browserAudioContext(){
const Constructor=globalThis.AudioContext??globalThis.webkitAudioContext;
if(!Constructor)throw new MusicError('audio-context-unavailable');
try{return new Constructor();}
catch{throw new MusicError('audio-context-unavailable');}
}
export class GMAudioHost{
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#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; #scheduled=0; #late=0; #ahead=0; #lastLead=0; #bufferedBytes=0; #meter;
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),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',scheduledFrames:this.#scheduled,droppedLate:this.#late,droppedAhead:this.#ahead,lastLeadSeconds:this.#lastLead,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
#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};}
get catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;}
get stream(){return this.#destination?.stream;}
@@ -81,9 +89,9 @@ export class GMAudioHost{
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
if(!profile.targetName||typeof profile.target!=='string'||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
this.#lastError=undefined;this.#attachedQueue=false;this.#context=audioContext??this.createContext();const unlocked=audioContext?null:this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
this.#lastError=undefined;this.#attachedQueue=this.#transitioning=this.#fadeNext=false;this.#context=audioContext??this.createContext();if(!audioContext)void this.#context.resume().catch(()=>{});this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=0;
try{
this.#sdk=await this.loadSDK();await unlocked;check();
this.#sdk=await this.loadSDK();check();
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
@@ -93,8 +101,16 @@ export class GMAudioHost{
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket,onDisconnect:()=>this.#connectionLost(epoch,'API connection lost')});
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:250,minBufferMs:250,useHardwareVolume:false,unpairedAccess:false,reconnect:{enabled:false}});
this.#gain=this.#context.createGain();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.#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);
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');
@@ -142,29 +158,56 @@ export class GMAudioHost{
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
this.#frames++;this.#lastAudio=Date.now();for(const channel of chunk.samples)for(const sample of channel){this.#samples++;this.#energy+=sample*sample;}
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
this.#lastLead=lead;if(!Number.isFinite(lead)||this.#nodes.size>=512||this.#bufferedBytes+frames*chunk.samples.length*4>2097152)return;
if(lead>6){this.#ahead++;return;}if(lead+frames/chunk.sampleRate<0){this.#late++;return;}
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);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);node.adaptiveBytes=frames*chunk.samples.length*4;node.adaptiveServerStart=chunk.serverTimeUs;node.adaptiveServerEnd=chunk.serverTimeUs+frames/chunk.sampleRate*1000000;node.onended=()=>{if(this.#nodes.delete(node))this.#bufferedBytes-=node.adaptiveBytes;};this.#nodes.add(node);this.#bufferedBytes+=node.adaptiveBytes;node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));this.#scheduled++;
const start=this.#timeline.push(chunk,this.#core.getCurrentServerTimeUs());
if(start!==false&&this.#fadeNext&&!this.#transitioning){
this.#fadeNext=false;
const gain=this.#transitionGain.gain;
gain.setValueAtTime(0,start);
gain.linearRampToValueAtTime(1,start+0.35);
}
}
#clear(fromTimestampUs){
if(Number.isFinite(fromTimestampUs)){
const when=Math.max(this.#context.currentTime,this.#context.currentTime+(fromTimestampUs-this.#core.getCurrentServerTimeUs())/1000000);
for(const node of this.#nodes)if(node.adaptiveServerEnd>fromTimestampUs){try{node.stop(node.adaptiveServerStart>=fromTimestampUs?0:when);}catch{}}
return;
this.#timeline?.clear(fromTimestampUs);
if(!Number.isFinite(fromTimestampUs)&&this.#transitioning)this.#fadeNext=true;
}
async fade(audible, ctx){
const context=this.#context,param=this.#transitionGain?.gain;
if(!param||context.state!=='running')return;
const now=context.currentTime,duration=audible?0.35:0.22;
this.#transitioning=!audible;
if(audible&&this.#fadeNext)return;
if(typeof param.cancelAndHoldAtTime==='function')param.cancelAndHoldAtTime(now);
else {param.cancelScheduledValues(now);param.setValueAtTime(param.value,now);}
param.linearRampToValueAtTime(audible?1:0,now+duration);
if(!audible){
await new Promise(resolve=>setTimeout(resolve, duration*1000));
ctx?.check();
}
for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();this.#bufferedBytes=0;
}
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
snapshot(ctx){return this.#ready().snapshot(ctx);}
async #observe(operation){try{return await operation();}catch(error){this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(error.code==='uncertain')this.#phase='queue reconciliation required';throw error;}}
snapshot(ctx){return this.#observe(()=>this.#ready().snapshot(ctx));}
async #observe(operation){
try{return await operation();}
catch(error){
if(error.upstreamCode===22&&['players/get','player_queues/get','player_queues/get_active_queue'].includes(error.command)){
error=Object.assign(new MusicError('receiver-access-lost'),{command:error.command,upstreamCode:error.upstreamCode});
}
this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};
if(['uncertain','receiver-access-lost'].includes(error.code))this.#phase='queue reconciliation required';
throw error;
}
}
apply(prepared,ctx){return this.#observe(()=>this.#ready().apply(prepared,ctx));}
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
stopOwned(ctx){return this.#observe(()=>this.#ready().stopOwned(ctx));}
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
playbackStatus(){return this.#ready().playbackStatus();}
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;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();}
}
+136
View File
@@ -0,0 +1,136 @@
// Keep the Web Audio timeline sample-continuous across Sendspin packets.
// The upstream timestamp is a stream coordinate. AudioContext.currentTime is
// quantized by the render thread, so mapping each packet independently is noisy.
const startupBuffer = 0.12;
const schedulingGuard = 0.008;
const maximumLead = 8;
const timestampToleranceUs = 1500;
const maximumBytes = 8 * 1024 * 1024;
export class PcmTimeline {
#context;
#output;
#sources = new Set();
#bytes = 0;
#nextTime;
#nextTimestamp;
#format;
#paused = false;
#stats = {scheduledFrames:0, droppedLate:0, droppedAhead:0, bufferOverruns:0,
underruns:0, sourceGaps:0, sourceOverlaps:0, gapMs:0, overlapMs:0, lastLeadSeconds:0};
constructor(context, output) {
this.#context = context;
this.#output = output;
}
get diagnostics() {
return {...this.#stats, bufferedMs:Math.round(Math.max(0, (this.#nextTime ?? 0) - this.#context.currentTime) * 1000)};
}
push({samples,sampleRate,serverTimeUs}, serverNowUs) {
const now = this.#context.currentTime;
if (this.#context.state === 'suspended' || this.#context.state === 'interrupted') {
if (!this.#paused) this.clear();
this.#paused = true;
return false;
}
this.#paused = false;
const lead = (serverTimeUs - serverNowUs) / 1e6;
if (!Number.isFinite(lead)) return false;
this.#stats.lastLeadSeconds = lead;
if (lead > maximumLead) { this.#stats.droppedAhead++; return false; }
const frames = samples[0].length;
const duration = frames / sampleRate;
if (lead + duration + startupBuffer <= 0) { this.#stats.droppedLate++; return false; }
// Count actual discontinuities in the source separately from render starvation.
let offset = 0;
let time = this.#nextTime;
const format = `${sampleRate}:${samples.length}`;
const timestampDelta = serverTimeUs - (this.#nextTimestamp ?? serverTimeUs);
if (this.#format === format && Math.abs(timestampDelta) > timestampToleranceUs) {
if (timestampDelta < 0) {
this.#stats.sourceOverlaps++;
this.#stats.overlapMs += -timestampDelta / 1000;
offset = Math.min(frames, Math.round(-timestampDelta * sampleRate / 1e6));
if (offset === frames) return false;
} else {
this.#stats.sourceGaps++;
this.#stats.gapMs += timestampDelta / 1000;
time += timestampDelta / 1e6;
}
}
const target = now + lead + startupBuffer + offset / sampleRate;
if (time === undefined || this.#format !== format) {
time = Math.max(now + schedulingGuard, this.#nextTime ?? 0, target);
} else if (time < now + schedulingGuard) {
this.#stats.underruns++;
time = Math.max(now + schedulingGuard, target);
}
const bytes = (frames - offset) * samples.length * 4;
if (this.#sources.size >= 768 || this.#bytes + bytes > maximumBytes) {
this.#stats.bufferOverruns++;
return false;
}
// Correct slow drift without moving packet boundaries around. Ignore render
// quantum noise. The maximum slew (0.1%) keeps pitch changes small.
const error = target - time;
const rate = Math.abs(error) <= 0.005 ? 1 : 1 - Math.max(-0.001,Math.min(0.001,error / 8));
const buffer = this.#context.createBuffer(samples.length, frames - offset, sampleRate);
samples.forEach((channel,index) => buffer.getChannelData(index).set(channel.subarray(offset)));
const source = this.#context.createBufferSource();
source.buffer = buffer;
source.playbackRate.value = rate;
source.connect(this.#output);
const length = (frames - offset) / sampleRate / rate;
const item = {source,bytes,start:time,end:time+length,serverStart:serverTimeUs+offset/sampleRate*1e6,serverEnd:serverTimeUs+duration*1e6,rate};
this.#sources.add(item);
this.#bytes += bytes;
source.onended = () => {
source.disconnect();
if (this.#sources.delete(item)) this.#bytes -= bytes;
};
source.start(time);
this.#stats.scheduledFrames++;
this.#format = format;
this.#nextTime = item.end;
this.#nextTimestamp = item.serverEnd;
return time;
}
clear(timestamp) {
if (Number.isFinite(timestamp)) {
let retainedEnd;
let retainedTimestamp;
for (const item of this.#sources) {
if (item.serverStart >= timestamp) {
item.source.stop();
this.#sources.delete(item);
this.#bytes -= item.bytes;
} else {
const end = Math.min(item.end, item.start+(timestamp-item.serverStart)/1e6/item.rate);
if (item.serverEnd > timestamp) {
item.source.stop(Math.max(this.#context.currentTime,end));
item.end=end;
item.serverEnd=timestamp;
}
if (retainedEnd === undefined || end > retainedEnd) {
retainedEnd = end;
retainedTimestamp = Math.min(timestamp,item.serverEnd);
}
}
}
this.#nextTime = retainedEnd;
this.#nextTimestamp = retainedTimestamp;
return;
}
for (const item of this.#sources) item.source.stop();
this.#sources.clear();
this.#bytes = 0;
this.#format = this.#nextTime = this.#nextTimestamp = undefined;
}
}
+12 -4
View File
@@ -54,7 +54,8 @@ export class PeerAudio{
if(invite.relayOnly&&!iceServers.some(s=>(Array.isArray(s.urls)?s.urls:[s.urls]).some(url=>/^turns?:/.test(url))))throw new MusicError('denied');
const codec=new SignalCodec(invite,role); // Validate before allocating a browser connection.
const pc=this.#create({iceServers,iceTransportPolicy:invite.relayOnly?'relay':'all'}),entry={invite:structuredClone(invite),role,pc,codec,tail:Promise.resolve(),restarts:0,pending:0,signals:0};
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
// Expiry closes signaling. A connected stream retains its authorization until revoked.
entry.timer=setTimeout(()=>{if(pc.connectionState!=='connected')this.revoke(invite.peer);},Math.max(1,invite.expires-Date.now()));
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
pc.ondatachannel=event=>event.channel.close();
pc.onconnectionstatechange=()=>{
@@ -69,10 +70,16 @@ export class PeerAudio{
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
async #receive(frame){
const entry=this.#peers.get(frame?.peer);if(!entry||frame.session!==entry.invite.session)return;
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
if(entry.pending>=4||entry.signals>=64)throw new MusicError('denied');entry.pending++;
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
const check=()=>{
if(this.#peers.get(frame.peer)!==entry||entry.invite.expires<=Date.now())throw new MusicError('stale');
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);entry.stage='validate SDP';
};
check();
if(entry.signals>=64)throw new MusicError('denied');
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);
check();entry.signals++;entry.stage='validate SDP';
if(payload.type==='bye'){this.revoke(frame.peer);return;}
if(entry.role==='gm'&&payload.type==='offer'){
// The listener's SDP is recvonly: reject video, data, injected outbound audio.
@@ -80,6 +87,7 @@ export class PeerAudio{
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
entry.stage='apply offer';await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
check();
entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
}else if(entry.role==='listener'&&payload.type==='answer'){
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
@@ -92,5 +100,5 @@ export class PeerAudio{
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
diagnostics(){return {rejectedSignals:this.#rejected,lastSignalError:this.#lastSignalError,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState,stage:e.stage}))};}
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;}
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,concealedSamples:item.concealedSamples,silentConcealedSamples:item.silentConcealedSamples,concealmentEvents:item.concealmentEvents,jitterBufferDelay:item.jitterBufferDelay,jitterBufferEmittedCount:item.jitterBufferEmittedCount,currentRoundTripTime:item.currentRoundTripTime});}return results;}
}
+128 -23
View File
@@ -2,45 +2,135 @@
export class MusicError extends Error {
constructor(code) { super(code); this.code = code; }
}
export function combatAppliesToScene(combat, sceneId) {
if (!combat.active || !combat.started || !sceneId) return false;
if (combat.sceneId) return combat.sceneId === sceneId;
return !combat.sceneIds?.length || combat.sceneIds.includes(sceneId);
}
const intent = (key, mode, playlist = null) => ({key: `${key}:${JSON.stringify(playlist)}`, mode, playlist});
const ambientIntent = scene => intent(`scene:${scene.id}`, 'ambient', scene.playlist);
const retainedAmbient = state => (state.retainedAmbient ?? []).filter(scene => scene.playlist).map(ambientIntent);
export function candidates(state) {
const scene = state.scene;
const combats = (state.combats ?? []).filter(c => c.active && c.started && c.sceneId === scene?.id);
const combats = (state.combats ?? []).filter(c => combatAppliesToScene(c,scene?.id))
.sort((a,b) => a.id.localeCompare(b.id));
const bosses = combats.flatMap(c => c.bosses ?? []).filter(b => b.active && b.playlist)
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
const make = (key, playlist) => ({ key, playlist: playlist ?? null });
return [
...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)),
...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)),
...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id))
.map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)),
...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []),
make('default', state.defaultPlaylist)
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` }));
...(state.overrides ?? []).slice().reverse().map(o => intent(`manual:${o.id}`, 'manual', o.playlist)),
...bosses.map(b => intent(`boss:${scene.id}:${b.id}`, 'boss', b.playlist)),
...combats.filter(c => c.bossPlaylist).map(c => intent(`boss-encounter:${scene.id}:${c.id}`, 'boss', c.bossPlaylist)),
...combats.filter(c => c.playlist).map(c => intent(`combat:${scene.id}:${c.id}`, 'combat', c.playlist)),
...(scene?.playlist ? [ambientIntent(scene)] : []),
intent('default', state.defaultPlaylist ? 'ambient' : 'silence', state.defaultPlaylist)
];
}
const samePlaylist = (a, b) => Boolean(a && b && a.provider === b.provider && a.id === b.id);
export class MusicController {
#pending;
#stateSignature;
#campaignHold;
constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
Object.assign(this, { campaign, session, providers, authority, maxFrames });
this.dirty = new Set();
this.generation = 0; this.frames = []; this.current = null; this.tail = Promise.resolve();
}
update(state) {
if (this.campaignPaused) return Promise.resolve({ unchanged: true });
const input = structuredClone(state);
const signature=JSON.stringify([...candidates(input),...retainedAmbient(input)].map(intent=>intent.key));
if(this.#pending?.signature===signature&&this.#pending.generation===this.generation)return this.#pending.task;
if(!this.#pending&&this.current&&this.#stateSignature===signature&&!this.dirty.size&&this.authority())return Promise.resolve({unchanged:true});
const context = this.#nextContext();
return this.#enqueue(() => this.transition(input, context));
const task=this.#enqueue(() => this.transition(input, context)).then(result=>{
this.#stateSignature=signature;
return result;
}).finally(()=>{
if(this.#pending?.task===task)this.#pending=undefined;
});
this.#pending={signature,generation:context.generation,task};
return task;
}
control(action, value) {
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) {
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'));
}
const expected = this.generation;
return this.#enqueue(() => {
return this.#enqueue(async () => {
if (expected !== this.generation) throw new MusicError('stale');
const context = this.#nextContext();
context.check();
return this.providers.ma.control(action, value, context);
const provider=this.providers.ma;
try{
if(['pause','stop','next','seek'].includes(action))await provider.fade?.(false,context);
return await provider.control(action,value,context);
}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();
}
@@ -56,28 +146,37 @@ export class MusicController {
const task = this.tail.catch(() => {}).then(operation);
this.tail = task; return task;
}
async transition(state, ctx) {
async transition(state, ctx, hold) {
ctx.check();
const choices = candidates(state), next = choices[0];
const valid = new Set(choices.map(i => i.key));
const active = new Set(choices.map(i => i.key));
const valid = new Set([...active,...retainedAmbient(state).map(i=>i.key)]);
this.frames = this.frames.filter(f => valid.has(f.intent.key));
if (this.current?.key === next.key) return { unchanged: true };
if(samePlaylist(this.current?.playlist,next.playlist)){
this.current=next;
return {unchanged:true};
}
const provider = next.playlist && this.providers[next.playlist.provider];
if (next.playlist && !provider) throw new MusicError('unsupported');
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 && valid.has(old.key)) {
this.frames = this.frames.filter(f => f.intent.key !== old.key);
this.frames.push({ intent: old, snapshot });
if (old && snapshot) {
const shared = choices.filter(intent => samePlaylist(intent.playlist, old.playlist));
const aliases = new Set(shared.map(intent => intent.key));
this.frames = this.frames.filter(f => !aliases.has(f.intent.key));
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 {
if (!heldSource) await outgoing?.fade?.(false,ctx);
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
ctx.check();
if (provider) {
@@ -88,15 +187,21 @@ export class MusicController {
} catch (error) {
// Stale or uncertain writes require explicit reconciliation.
this.current = null;
if (error.code !== 'stale' && error.code !== 'uncertain') {
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 {
if (!heldSource) await outgoing?.fade?.(true);
}
this.frames = this.frames.filter(f => f.intent.key !== next.key).slice(-this.maxFrames);
this.frames = this.frames.filter(f => !active.has(f.intent.key)||!samePlaylist(f.intent.playlist,next.playlist)).slice(-this.maxFrames);
this.dirty.clear();
this.current = next;
return { intent: next, restored: Boolean(frame) };
+13 -4
View File
@@ -1,6 +1,9 @@
import { MusicError } from './controller.mjs';
export const musicFields = ['ambient','combat','boss','fallback'];
export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : '';
export const musicModeLabel = mode => ({
ambient:'Ambient', combat:'Combat', boss:'Boss', manual:'Manual Override', silence:'Silence'
})[mode];
export function selection(value, choices, {nativeOnly=false}={}) {
if(value==='')return null;
const choice=choices.find(c=>referenceKey(c)===value && ['native','ma'].includes(c.provider) && typeof c.id==='string' && c.id.length<=256);
@@ -9,13 +12,19 @@ export function selection(value, choices, {nativeOnly=false}={}) {
}
// Single music layer: ambient is the base queue interrupted by combat/boss/manual.
// These assignments do not address Foundry AmbientSound or sound effects.
export function buildMusicState({scene,combats=[],defaults={},overrides=[],choose=ref=>ref}) {
export function buildMusicState({scene,retainedScenes=[],combats=[],defaults={},overrides=[],choose=ref=>ref}) {
const sceneMusic = scene => {
const config = scene?.music ?? {};
const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null;
const fallback = config.fallback ?? defaults.fallback ?? null;
const selected=ref=>ref ? choose(ref,fallback) : null;
return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(defaults.ambient),
const ambient = (Object.hasOwn(config,'ambient') ? config.ambient : config.playlist) ?? defaults.ambient;
const selected = ref => ref ? choose(ref,fallback,scene) : null;
return {config,ambient:selected(ambient),selected};
};
const {config,ambient,selected}=sceneMusic(scene);
return {scene:scene && {id:scene.id,playlist:ambient},defaultPlaylist:scene ? null : ambient,
retainedAmbient:retainedScenes.map(scene=>({id:scene.id,playlist:sceneMusic(scene).ambient})),
overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})),
combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat),
bossPlaylist:c.boss===true?selected(config.boss??defaults.boss):null,
bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))};
}
+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;
}
+138 -8
View File
@@ -1,11 +1,25 @@
import {mountMusicAssignments} from './music-editor.mjs';
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 }) {
@@ -16,9 +30,9 @@ export async function savePlaylistConfiguration({ document, game, choices, selec
await document.setFlag(namespace, 'music', { ...previous,
playlist: choice ? { provider: choice.provider, id: choice.id } : null });
}
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {} }) {
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {},sceneSheet=false }) {
if (!game.user?.isGM || container.querySelector('[data-adaptive-music]')) return null;
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError});
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError,sceneSheet});
const dom = container.ownerDocument;
const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration';
const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend);
@@ -31,7 +45,7 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
const current = document.getFlag(namespace, 'music')?.playlist;
if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable');
select.value = current ? key(current) : '';
const note = dom.createElement('p'); note.textContent = 'Music Assistant playback requires a separately configured gateway; this development module uses Foundry playlists.'; panel.append(note);
const note = dom.createElement('p'); note.textContent = 'Connect Music Assistant in Adaptive Music setup to load playlists. Saved selections remain available after reload.'; panel.append(note);
const status = dom.createElement('p'); status.setAttribute('role','status'); panel.append(status);
const save = dom.createElement('button'); save.type = 'button'; save.textContent = 'Save music playlist'; panel.append(save);
let saving = false;
@@ -47,21 +61,137 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
container.append(panel); return panel;
}
// Explicit development-only UI bootstrap. Importing this file registers nothing.
export function startConfigurationInterfaces({ game, Hooks, getChoices, onError = () => {} }) {
export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlayback, getPlaybackState = () => ({}),
returnToAutomation, onError = () => {} }) {
let disposed = false;
const panels = new Set();
const trackers = new Map();
const render = async (app, html) => {
if (!game.user?.isGM) return;
for(const panel of panels)if(panel.isConnected===false)panels.delete(panel);
const container = html?.querySelector ? html : html?.[0];
const document = app.document;
if (!document || !container) return;
try {
const choices = await getChoices();
if (disposed) return;
const panel = mountPlaylistConfiguration({document,game,container,choices,onError});
const sceneSheet=document.documentName==='Scene';
const target=sceneSheet?(container.querySelector('[data-tab="ambience"].tab,[data-tab="audio"].tab,[data-tab="basic"].tab')??container.querySelector('.window-content')??container):container;
const panel = mountPlaylistConfiguration({document,game,container:target,choices,onError,sceneSheet});
if (panel) panels.add(panel);
} catch { onError(new MusicError('unavailable')); }
};
const hooks = ['renderSceneConfig','renderCombatConfig'].map(event => [event,Hooks.on(event, render)]);
return { dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); } };
const renderDirectory=async (_app,html)=>{
const container=html?.querySelector?html:html?.[0];
if(!game.user?.isGM||!container)return;
try{
const choices=(await getChoices()).filter(choice=>choice.provider==='ma');
if(disposed||!game.user?.isGM)return;
for(const panel of panels)if(panel.isConnected===false)panels.delete(panel);
const dom=container.ownerDocument,existing=container.querySelector('.adaptive-catalog');
const details=existing??dom.createElement('details');
if(!existing){
details.className='adaptive-catalog';
const summary=dom.createElement('summary');summary.textContent='Adaptive Music';details.append(summary);
const playback=dom.createElement('button');playback.type='button';playback.textContent='Music controls';
playback.addEventListener('click',()=>openPlayback?.());details.append(playback);
const nativeList=container.querySelector('.directory-list');
if(nativeList)nativeList.before(details);else container.append(details);
panels.add(details);
}
const entries=choices.map(choice=>[referenceKey(choice),choice.name]);
const previous=details.querySelector('ul');
if(JSON.stringify(entries)===JSON.stringify([...previous?.children??[]].map(entry=>[entry.dataset.reference,entry.textContent])))return;
const list=dom.createElement('ul');
for(const [reference,name] of entries){
const entry=dom.createElement('li');entry.textContent=name;entry.draggable=true;entry.dataset.reference=reference;
entry.addEventListener('dragstart',event=>{
if(!event.dataTransfer)return;
event.dataTransfer.setData(playlistDragType,reference);event.dataTransfer.effectAllowed='copy';
});
list.append(entry);
}
previous?.remove();
if(entries.length)details.append(list);
}catch{
onError(new MusicError('unavailable'));
}
};
function refreshCombatTrackers() {
for(const [panel,refresh] of trackers){
if(panel.isConnected)refresh();
else trackers.delete(panel);
}
}
const renderCombatTracker = (app,html) => {
if(disposed||!game.user?.isGM)return;
const container = html?.querySelector ? html : html?.[0];
if(!container)return;
const existing = container.querySelector('.adaptive-combat-music');
if(existing){trackers.get(existing)?.();return;}
const dom = container.ownerDocument;
const panel = dom.createElement('section');
panel.className = 'adaptive-combat-music';
panel.setAttribute('aria-label','Adaptive Music');
const mode = dom.createElement('p');
mode.setAttribute('role','status');
const label = dom.createElement('label');
const boss = dom.createElement('input');
boss.type = 'checkbox';
label.append(boss, ' Boss encounter');
label.title = 'Use the scene’s default boss music when this encounter starts.';
const resume = dom.createElement('button');
resume.type = 'button';
resume.textContent = 'Return to automation';
panel.append(mode,label,resume);
container.prepend(panel);
let saving = false;
const refresh = () => {
const combat = app.viewed;
const state = getPlaybackState();
const cue = musicModeLabel(state.musicMode);
const text = state.campaignPaused ? 'Music: Campaign paused'
: state.overrideActive ? 'Music: Manual Override · automatic cues on hold'
: state.awaitingSceneChange ? 'Music: waiting for the next cue'
: cue ? `Music: ${cue}` : 'Music: automation off';
if(mode.textContent!==text)mode.textContent=text;
label.hidden = !combat;
boss.disabled = saving || !combat;
boss.checked = flagBoss(combat);
resume.hidden = !returnToAutomation || (!state.overrideActive && !state.awaitingSceneChange);
};
const flagBoss = combat => combat?.getFlag(namespace,'music')?.boss === true;
boss.addEventListener('change',async event=>{
event.stopPropagation();
const combat = app.viewed;
if(!game.user?.isGM || !combat?.canUserModify(game.user,'update')){refresh();return;}
const enabled = boss.checked;
saving = true;
boss.disabled = true;
try{await combat.setFlag(namespace,'music',{...combat.getFlag(namespace,'music'),boss:enabled});}
catch{onError(new MusicError('denied'));}
finally{saving=false;refresh();}
});
resume.addEventListener('click',async ()=>{
if(!game.user?.isGM)return;
resume.disabled=true;
try{await returnToAutomation();}
catch(error){onError(error);}
finally{resume.disabled=false;refresh();}
});
refreshCombatTrackers();
trackers.set(panel,refresh);
refresh();
};
const hooks = [['renderSceneConfig',render],['renderCombatConfig',render],['renderPlaylistDirectory',renderDirectory],
['renderCombatTracker',renderCombatTracker]]
.map(([event,handler])=>[event,Hooks.on(event,handler)]);
return {
refreshDirectory:app=>renderDirectory(app,app?.element),
refreshCombatTrackers,
dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id);
for (const panel of [...panels,...trackers.keys()]) panel.remove();
panels.clear();trackers.clear();
}
};
}
+66 -15
View File
@@ -4,6 +4,9 @@ import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs
const messages={
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
'private-credential-write-failed':'Connected, but the browser could not remember the credential on this device.',
'receiver-storage-write-failed':'The browser could not update the remembered receiver. Check site storage before reconnecting.',
'private-credential-corrupt':'The device credential could not be unlocked. Use Forget Credentials and enter a valid token.',
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
'token-required':'Enter a Music Assistant access token for this server.',
'token-invalid':'Remove line breaks from the access token and try again.',
@@ -18,24 +21,39 @@ const messages={
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.',
'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.',
'audio-context-unavailable':'This browser could not start Web Audio. Check the browser’s audio output and whether another device is using it exclusively.',
'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.',
'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.',
'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.',
'private-storage-unavailable':'This browser denied private receiver storage. Allow site storage for Foundry, then retry. No MA token is stored there.',
'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.',
'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.',
'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.',
'receiver-access-lost':'Music Assistant withdrew this receiver’s queue access. If another MA browser player uses this token, give the two players separate tokens. Review the dedicated receiver before reconnecting.',
'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.',
'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.',
'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.',
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
};
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
const connectionStages=new Set(['API authentication','Sendspin authentication','Noise handshake','receiver pairing',
'clock synchronization','dedicated receiver verification','catalog retrieval','dedicated queue verification']);
function diagnosticFailure(error){
return {code:Object.hasOwn(messages,error?.code)?error.code:'unavailable',
...(connectionStages.has(error?.stage)&&{stage:error.stage})};
}
export function connectionMessage(error){
if(error?.code==='ws-upgrade-failed'&&error.stage==='Sendspin authentication')return 'The browser could not open the receiver’s /sendspin WebSocket. Check both routes from this Foundry page.';
if(error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command))return 'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped after an unconfirmed queue write.';
return messages[error?.code]??messages.unavailable;
}
function failureStage(error) {
if(error?.code==='audio-context-unavailable')return 'Browser audio unavailable';
if(error?.stage==='Sendspin authentication'&&error.code==='ws-upgrade-failed')return 'Receiver connection failed';
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
@@ -75,14 +93,17 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
const initial=connection.draftFields??{};
make('h2','Connect Music Assistant');
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
if(initial.savedConnection&&!initial.deviceCredential)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
const fields=make('div');fields.className='adaptive-fields';
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
const token=input(fields,'Private GM access token','password');
const remember=input(fields,'Remember credentials and reconnect on this trusted device','checkbox');remember.checked=initial.deviceCredential===true;
make('p','Use a revocable Music Assistant token. Remembered credentials belong to this browser profile. Enable this only on a device and Foundry site you trust.');
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
const actions=make('div');actions.className='adaptive-actions';
const state=make('p');state.className='adaptive-state';
const status=make('p');status.setAttribute('role','status');
const automaticFailure=make('p');automaticFailure.hidden=true;
const advanced=make('details');make('summary','Advanced',advanced);
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
@@ -91,12 +112,13 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
const report=make('div');report.setAttribute('aria-live','polite');
let transportResults=[],busy=false;
const run=async(action,label)=>{
let transportResults=[],transportCheckAt,lastConnectFailure,busy=false,hadDeviceCredential=initial.deviceCredential;
const run=async(action,label,onFailure)=>{
if(busy||!game.user.isGM)return;
busy=true;retainError.hidden=true;render();
try{await action();}
catch(error){
onFailure?.(error);
busy=false;render();error.field?.focus?.();
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
}finally{busy=false;render();}
@@ -115,10 +137,13 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
catch{return false;}
}
const connect=button(actions,'Connect',()=>run(async()=>{
lastConnectFailure=undefined;
let maUrl;
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
const draft=connection.draftFields??{};
const usingDevice=draft.deviceCredential&&draft.maUrl===maUrl;
if(!token.value.trim()&&!usingDevice&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
const targetName=name.value.trim();
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
@@ -127,25 +152,43 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
status.textContent='Contacting Music Assistant…';
let result;
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
try{result=await connection.open({maUrl,token:token.value.trim(),remember:remember.checked,...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
address.value=connection.draftFields?.maUrl??address.value;
await onCatalog();
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error),
error=>{lastConnectFailure={at:new Date().toISOString(),...diagnosticFailure(error)};}));
connect.className='adaptive-primary';
const nextButton=button(actions,'Choose scene music',()=>next?.());
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. Automatic reconnection is paused until you connect again.';await onCatalog();
},'Disconnect failed'));
const forgetCredentials=button(actions,'Forget Credentials',()=>run(async()=>{
await connection.forgetCredentials();remember.checked=false;token.value='';status.textContent='Credentials removed from this device.';await onCatalog();
},'Could not forget credentials'));
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
report.replaceChildren();transportResults=[];transportCheckAt=undefined;
transportResults=await probeWebSockets(validatedAddress());
transportCheckAt=new Date().toISOString();
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
status.textContent='Browser checks complete.';
},'Browser connection check failed'));
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
const d=connection.status;
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
const details={
state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,
decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,
droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,bufferedMs:d.bufferedMs,
underruns:d.underruns,bufferOverruns:d.bufferOverruns,
sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,gapMs:d.gapMs,overlapMs:d.overlapMs,
muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,
listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,
transport:transportResults,transportCheckAt,lastConnectFailure,
automaticConnectFailure:d.deviceError?diagnosticFailure({code:d.deviceError}):undefined,
secureContext:globalThis.isSecureContext,
};
await navigator.clipboard.writeText(JSON.stringify(details,null,2));
status.textContent='Connection diagnostics copied.';
},'Could not copy diagnostics'));
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
@@ -156,17 +199,25 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
if(advancedContent)advanced.append(advancedContent);
function render(){
const d=connection.status,connected=d.state==='connected';
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
const connecting=busy||d.deviceReconnect;
const label=connected?'Connected':connecting?'Working':d.state==='connection-lost'?'Connection lost':d.deviceError?'Automatic connection failed':'Disconnected';
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
if(state.textContent!==summary)state.textContent=summary;
state.dataset.connected=String(connected);
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
automaticFailure.hidden=connected||connecting||!d.deviceError;
if(!automaticFailure.hidden)automaticFailure.textContent=connectionMessage({code:d.deviceError});
connect.hidden=connected;connect.disabled=connecting;connect.textContent=connecting?'Connecting…':'Connect';
disconnect.hidden=!connected;disconnect.disabled=busy;
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
const draft=connection.draftFields;
forgetCredentials.hidden=!draft?.deviceCredential&&d.deviceError!=='private-credential-corrupt';forgetCredentials.disabled=connecting;
if(!address.value&&draft?.deviceCredential&&!hadDeviceCredential)address.value=draft.maUrl;
if(draft?.deviceCredential&&!hadDeviceCredential)remember.checked=true;
hadDeviceCredential=draft?.deviceCredential;
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry,remember])field.disabled=connected||connecting;
token.placeholder=retainedToken()||connection.draftFields?.deviceCredential?'Retained for this address':'Paste your access token';
}
address.addEventListener('input',render);
render();
+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;
+259 -52
View File
@@ -1,65 +1,154 @@
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 {createSetupClass,createListenerClass} from './setup.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';
const receiverVault=new ReceiverVault();
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.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 automationRunning=false,previousController;
const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
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,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 onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
const queueNeedsReview=error=>['uncertain','receiver-access-lost'].includes(error?.code);
const onError=error=>{if(queueNeedsReview(error)){devicePaused=true;stop();}ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
function openSetup(){
const existing=foundry.applications.instances.get('adaptive-music-setup');
if(existing)return existing.bringToFront();
return new setupType().render({force:true});
}
function openPlayback(){
if(!isMusicGM(game.user))return;
if(!playbackApp){
const Playback=createPlaybackClass({game,connection,getChoices:choices,start,stop,setOverrides,onError,openSetup});
playbackApp=new Playback();
}
return playbackApp.render({force:true});
}
function ensureRuntime(){
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError,onModeChange:refreshCombatTrackers});
return runtime;
}
function start(){
function playbackMode(){
return {musicMode:runtime?.musicMode,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange,
campaignPaused:runtime?.controller.campaignPaused??false};
}
function refreshCombatTrackers(){interfaces?.refreshCombatTrackers();}
function start({preserveQueue=false}={}){
if(!gmAuthority()||automationRunning)return;
automationRunning=true;
return ensureRuntime().refresh().catch(onError);
const active=ensureRuntime();
if(preserveQueue){active.deferUntilMusicChanges();refreshCombatTrackers();return;}
return active.refresh().catch(error=>{if(error.code!=='stale')onError(error);});
}
function stop(){
automationRunning=false;
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
refreshCombatTrackers();
}
function setOverrides(value){if(!gmAuthority())throw new MusicError('denied');if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
function openListener(){
if(!isMusicListener(game.user))return;
const existing=foundry.applications.instances.get('adaptive-music-listener');
if(existing)return existing.bringToFront();
return new listenerType().render({force:true});
}
function resumeListener(){
if(!isMusicListener(game.user)||!playerOutput)throw new MusicError('denied');
listenerStopped=false;
const activated=playerOutput.enable();
if(game.socket?.connected&&!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);
return activated;
}
function listenerStatus(){
const output=playerOutput?.status??{volume:100,muted:false};
let status='Waiting for GM audio.';
if(listenerStopped)status='Audio stopped. Select Enable Audio to rejoin.';
else if(!game.socket?.connected)status='Foundry disconnected. Waiting to reconnect.';
else if(output.needsActivation)status='GM audio is ready. Select Enable Audio.';
else if(output.playing)status=output.muted?'Listening · Muted':'Listening';
else if(peers?.diagnostics().peers.length)status='Connecting to GM audio…';
return {...output,status};
}
function changeListening(value,{save=true}={}){
let preferences;
if(isMusicGM(game.user)&&gmListening){
preferences=gmListening=listeningPreferences({...gmListening,...value});
gmHost.setMonitorLevel(preferences.muted?0:preferences.volume/100);
}else if(isMusicListener(game.user)&&playerOutput){
preferences=playerOutput.setPreferences(value);
}else throw new MusicError('denied');
if(!save)return;
preferenceWrites=preferenceWrites.catch(()=>{}).then(()=>game.settings.set(id,'listenerPreferences',preferences));
return preferenceWrites;
}
function setCampaignPaused(paused){
if(!gmAuthority())throw new MusicError('denied');
if(!paused)return runtime?.resumeCampaign();
if(!automationRunning&&!gmHost.connected)throw new MusicError('unavailable');
return ensureRuntime().pauseCampaign({attachedMA:gmHost.connected});
}
function startMusicBar(){
const controller=isMusicGM(game.user);
if(!globalThis.document?.body||(!controller&&!isMusicListener(game.user)))return;
disposeMusicBar=mountMusicBar({document,getPreferences:()=>game.settings.get(id,'musicBar'),
savePreferences:preferences=>game.settings.set(id,'musicBar',preferences),
getListening:controller?()=>gmListening:listenerStatus,changeListening,
enableAudio:controller?connection.resume:resumeListener,onError,
gm:controller?{
status:()=>{
const host=gmHost.status;
return {...playbackMode(),automationRunning,connected:gmHost.connected,canControl:gmAuthority(),volume:host.volume,
needsActivation:host.audioContext!=='running',canSkip:gmHost.connected&&!queueNeedsReview(host.lastError)&&
runtime?.controller.current?.playlist?.provider!=='native'};
},
setPaused:setCampaignPaused,skip:()=>connection.control('next'),setVolume:connection.setVolume,
returnToScene:()=>setOverrides([]),openPlayback,openSetup
}:undefined});
}
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
function ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
function attachListenerSource(stream){listenerSource?.disconnect();if(listenerContext){listenerSource=listenerContext.createMediaStreamSource(stream);listenerSource.connect(listenerContext.destination);remoteAudio.muted=true;}}
function resumeListener(){if(game.user.isGM)return gmHost.resumeAudio();listenerStopped=false;const element=ensureRemoteAudio();let resumed=Promise.resolve();if(globalThis.AudioContext){listenerContext??=new AudioContext();resumed=listenerContext.resume();if(element.srcObject)attachListenerSource(element.srcObject);}const play=element.play();play.catch(()=>{});if(!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);return resumed.then(()=>{listenerState=element.srcObject?'Campaign audio enabled.':'Audio enabled. Waiting for GM audio.';});}
function sendInvites(){
inviteTail=inviteTail.catch(()=>{}).then(async()=>{
if(!bootstrap||!gmHost?.connected||!gmAuthority())return;
for(const user of game.users){
if(!user.active||user.isGM||user.isBanned)continue;const key=bootstrap.recipientKey(user);if(!key)continue;
const previous=sentInvites.get(user.id);if(previous?.epoch===key.epoch&&previous.until>Date.now()&&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,until:Date.now()+1200000});}catch{onError();}
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();}
}
});return inviteTail;
}
const connection={
get draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};},
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};},
get draftFields(){return {maUrl:privateDraft?.maUrl??savedDevice?.maUrl,targetName:privateDraft?.targetName??savedDevice?.targetName,retainedToken:!!privateDraft?.token,deviceCredential:!!savedDevice,savedConnection:savedConnection()?.version===1};},
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),deviceReconnect,deviceError:deviceError?.code,hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning,...playbackMode()};},
async open(profile){
if(!gmAuthority()||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
if(!gmAuthority()||connectionOpening||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
// Claim browser audio activation before authentication performs asynchronous work.
const audioContext=gmHost.createContext();
connectionOpening=true;
const generation=connectionGeneration;
try{
void audioContext.resume().catch(()=>{});
if(!profile.token&&savedDevice&&(!profile.maUrl||profile.maUrl===savedDevice.maUrl)){
profile={...savedDevice,...profile,maUrl:savedDevice.maUrl,token:savedDevice.token,targetName:profile.targetName??savedDevice.targetName};
}
if(!profile.maUrl){
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
gmAccessPolicy(remembered.maUrl,location.href);
@@ -67,11 +156,26 @@ const connection={
}
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
const {target}=await connection.test(profile);
return await connection.connect(target,{audioContext});
}catch(error){
if(audioContext.state!=='closed')await audioContext.close();
throw error;
const result=await connection.connect(target,{audioContext,automatic:profile.automatic===true});
if(generation+1===connectionGeneration&&gmAuthority()){
if(profile.remember){
const credential={maUrl:privateProfile.maUrl,targetName:privateProfile.targetName,token:privateProfile.token,auto:true};
try{
savedDevice=credential;
await receiverVault.saveCredential(credentialScope(),credential);
}
catch{onError(new MusicError('private-credential-write-failed'));}
}else if(savedDevice||deviceError?.code==='private-credential-corrupt'){
try{await receiverVault.forgetCredential(credentialScope());savedDevice=null;}
catch{onError(new MusicError('private-credential-write-failed'));}
}
if(generation+1===connectionGeneration){devicePaused=false;deviceError=undefined;}
}
return result;
}catch(error){
if(!gmHost.connected&&audioContext.state!=='closed')await audioContext.close();
throw error;
}finally{connectionOpening=false;}
},
async test(profile){
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
@@ -88,12 +192,17 @@ const connection={
}catch(error){error.stage??='API authentication';throw error;}
finally{connectionTesting=false;}
},
async connect(target,{resumeAutomation=true,audioContext}={}){
async connect(target,{resumeAutomation=true,audioContext,automatic=false}={}){
if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
stop();const profile=privateProfile,generation=connectionGeneration;
let result;
try{result=await gmHost.start(profile,{audioContext});}
finally{if(generation===connectionGeneration)await receiverVault.save(receiverScope(profile),profile);}
finally{
if(generation===connectionGeneration){
try{await receiverVault.save(receiverScope(profile),profile);}
catch{onError(new MusicError('receiver-storage-write-failed'));}
}
}
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
try{
const saved=await sealAccountConnection(profile,profile.token,accountScope());
@@ -101,63 +210,162 @@ const connection={
}catch{onError(new MusicError('saved-connection-write-failed'));}
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();
if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
void interfaces?.refreshDirectory(ui.playlists);
if(resumeAutomation&&game.settings.get(id,'enabled')&&(!result.attachedExistingQueue||automatic))start({preserveQueue:result.attachedExistingQueue});
return result;
},
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});},
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
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;
const available=await choices();
const playlist=available.find(choice=>choice.provider===current?.provider&&(choice.id===current.id||choice.legacyId===current.id))?.name;
if(current?.provider==='native'){
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing);
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??''};
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??'',playlist};
}
if(gmHost.connected){
const priorError=gmHost.status.lastError?.code;
try{return {source:'Music Assistant',...await gmHost.playbackStatus(),playlist};}
catch(error){if(queueNeedsReview(error)&&priorError!==error.code)onError(error);throw error;}
}
if(gmHost.connected)return {source:'Music Assistant',...await gmHost.playbackStatus()};
return {state:'idle',title:''};
},
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);
},
async forgetCredentials(){
devicePaused=true;
await connection.disconnect({retainCredential:false});
await receiverVault.forgetCredential(credentialScope());
savedDevice=null;deviceError=undefined;
},
async forgetReceiver(){
const scope=privateDraft&&receiverScope(privateDraft);
await connection.disconnect();
const profile=privateDraft??savedDevice,scope=profile&&receiverScope(profile);
await connection.forgetCredentials();
await game.settings.set(id,'savedConnection',{});
if(scope)await receiverVault.forget(scope);
},
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
};
function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only');
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
async disconnect({retainCredential=true}={}){
devicePaused=true;connectionGeneration++;stop();peers?.reset();sentInvites.clear();
privateProfile=null;privateDraft=null;await gmHost.close();
void interfaces?.refreshDirectory(ui.playlists);
if(retainCredential&&savedDevice?.auto){
savedDevice={...savedDevice,auto:false};
await receiverVault.saveCredential(credentialScope(),savedDevice);
}
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
}
};
async function reconnectTrustedDevice(){
if(deviceReconnect||connectionOpening||devicePaused||!savedDevice?.auto||!gmAuthority()||gmHost.connected||gateway.connected)return;
deviceReconnect=true;
try{
await connection.open({...savedDevice,remember:true,automatic:true});
if(gmHost.status.audioContext!=='running')ui.notifications.info('Adaptive Music connected. Open Playback and select Enable GM audio if your browser requires it.');
}catch(error){
deviceError=error;
if(error.code==='ws-auth-denied')devicePaused=true;
onError(error);
if(game.settings.get(id,'enabled'))void start();
}finally{deviceReconnect=false;}
}
function listenWebRTC(invite){
if(!isMusicListener(game.user)||!peers||!activeMusicGM(game.users))throw new MusicError('denied');
listenerHost=activeMusicGM(game.users).id;
return peers.listen(invite);
}
function clearListener(){listenerHost=null;peers?.reset();playerOutput?.clear();}
function stopWebRTC(){listenerStopped=true;clearListener();}
Hooks.once('init',()=>{
Hooks.on('getSceneControlButtons',controls=>{
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});
game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Enable Audio',hint:'Connects automatically to GM audio. Enable sound if your browser asks.',icon:'fas fa-headphones',type:Listener,restricted:false});
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:Setup,restricted:true});
setupType=createSetupClass({game,gateway:{get status(){return gateway?.status;},connect:async code=>{if(!gmAuthority()||gmHost?.connected)throw new MusicError('denied');const result=await gateway.connect(code);await runtime?.refresh();return result;},refresh:()=>gateway.refresh(),disconnect:()=>gateway.disconnect(),audioRequest:code=>gateway.audioRequest(code)},
audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&gmAuthority(),canConfigure:()=>isMusicGM(game.user),connection});
listenerType=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus,changeListening});
}
});
Hooks.once('ready',()=>{
gmHost=new GMAudioHost({authority:gmAuthority,onDisconnect:()=>{stop();peers?.reset();sentInvites.clear();onError();}});
if(game.socket){peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&!user.isGM&&!user.isBanned;},onError,onStream:stream=>{ensureRemoteAudio().srcObject=stream;attachListenerSource(stream);(listenerContext?.state==='running'?Promise.resolve():remoteAudio.play()).then(()=>{listenerState='Campaign audio connected.';}).catch(()=>{listenerState='GM audio connected. Select Enable Audio to allow sound.';ui.notifications.info('Adaptive Music: open Campaign audio and select Enable Audio to allow sound.');});}});game.socket.on('disconnect',()=>{stop();privateProfile=null;gmHost.close();peers.reset();sentInvites.clear();latestInvite=null;listenerState='Foundry disconnected. Waiting for the GM to reconnect.';remoteAudio?.pause();});}
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(!game.user.isGM&&[...game.users].filter(u=>u.active&&u.isGM).length!==1){peers.reset();remoteAudio?.pause();latestInvite=null;listenerState='Waiting for one active GM.';}sendInvites();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
if(game.socket&&game.user.setFlag){bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{latestInvite=invite;if(listenerStopped)return;peers.reset();await listenWebRTC(invite);}});bootstrap.start().then(sendInvites).catch(onError);inviteTimer=setInterval(()=>{sendInvites();if(game.user.isGM&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);}
if(isMusicGM(game.user)){
gmListening=listeningPreferences(game.settings.get(id,'listenerPreferences'));
gmHost.setMonitorLevel(gmListening.muted?0:gmListening.volume/100);
}
if(isMusicListener(game.user)){
playerOutput=new CampaignAudio({preferences:game.settings.get(id,'listenerPreferences'),createElement:()=>{
const element=document.createElement('audio');element.autoplay=true;document.body.append(element);return element;
}});
if(listenerType)game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Open listening controls',hint:'Connects to GM audio and controls your own sound.',icon:'fas fa-headphones',type:listenerType,restricted:false});
const renderListener=(_app,html)=>mountListeningShortcut({html,game,openListener});
authorityHooks.push(['renderPlaylistDirectory',Hooks.on('renderPlaylistDirectory',renderListener)]);
renderListener(ui.playlists,ui.playlists?.element);
}
if(game.socket){
peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,
isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&isMusicListener(user);},
onError:()=>playerOutput?.clear(),
onStream:stream=>{if(!listenerStopped&&isMusicListener(game.user))void playerOutput?.attach(stream);}
});
socketHooks=[
['disconnect',()=>{stop();privateProfile=null;gmHost.close();clearListener();sentInvites.clear();}],
['connect',()=>{if(!listenerStopped)bootstrap?.start().then(sendInvites).catch(onError);}]
];
for(const [event,handler] of socketHooks)game.socket.on(event,handler);
const reconcile=()=>{
peers.reconcile();
if(listenerHost&&(!isMusicListener(game.user)||activeMusicGM(game.users)?.id!==listenerHost))clearListener();
if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();sentInvites.clear();}
else sendInvites();
};
for(const event of ['userConnected','updateUser','deleteUser'])authorityHooks.push([event,Hooks.on(event,reconcile)]);
}
if(game.socket&&game.user.setFlag&&(isMusicGM(game.user)||isMusicListener(game.user))){
bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{
if(listenerStopped)return;
clearListener();
await listenWebRTC(invite);
}});
bootstrap.start().then(sendInvites).catch(onError);
inviteTimer=setInterval(()=>{sendInvites();if(isMusicGM(game.user)&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);
}
gateway=new GatewayClient({origin:globalThis.location?.origin??'http://localhost'});audio=new ListenerAudio();
if(game.user.isGM){interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,onError});renewTimer=setInterval(()=>{if(gateway.connected&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);},10000);}
if(isMusicGM(game.user)){
if(setupType)game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:setupType,restricted:true});
interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,openPlayback,getPlaybackState:playbackMode,
returnToAutomation:()=>setOverrides([]),onError});
void interfaces.refreshDirectory(ui.playlists);
if(game.world?.id)receiverVault.loadCredential(credentialScope()).then(credential=>{
if(!devicePaused&&!connectionOpening&&connectionGeneration===0)savedDevice=credential;
if(!savedDevice?.auto&&game.settings.get(id,'enabled'))return start();
return reconnectTrustedDevice();
}).catch(error=>{deviceError=error;onError(error);if(game.settings.get(id,'enabled'))void start();});
renewTimer=setInterval(()=>{
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;},
@@ -165,9 +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;}
};
if(game.settings.get(id,'enabled'))start();
});
+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();
};
}
+23 -4
View File
@@ -1,6 +1,7 @@
import {MusicError} from '../core/controller.mjs';
import {musicFields,referenceKey,selection} from '../core/scene-music.mjs';
const namespace='adaptive-music';
export const playlistDragType='application/x-adaptive-music-playlist';
export async function saveMusicAssignments({document,game,choices,values,defaults=false}){
if(!game.user?.isGM||Object.keys(values).some(k=>!musicFields.includes(k)))throw new MusicError('denied');
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
@@ -22,15 +23,33 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
select.value=referenceKey(replacement||current);return select;
}
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{},sceneSheet=false}){
if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments';
const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':'Scene music';panel.append(legend);
const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':sceneSheet?'Adaptive Music':'Scene music';panel.append(legend);
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const labels={ambient:'Ambient playlist',combat:'Combat playlist',boss:'Default boss music',fallback:'Foundry fallback playlist'};
const controls={};
for(const field of musicFields){const label=dom.createElement('label');label.textContent=labels[field]+' ';const current=previous[field]??(field==='ambient'?previous.playlist:null);controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});label.append(controls[field]);panel.append(label);}
const note=dom.createElement('p');note.textContent='One music layer: combat interrupts ambient music. Concurrent ambient layers and crossfade are not implemented. Native AmbientSound and effects remain separate.';panel.append(note);
for(const field of musicFields){
const label=dom.createElement('label');label.textContent=labels[field]+' ';
const current=previous[field]??(field==='ambient'?previous.playlist:null);
const select=controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});
label.append(select);panel.append(label);
if(field==='fallback')continue;
label.addEventListener('dragover',event=>{if(event.dataTransfer?.types.includes(playlistDragType)){event.preventDefault();event.dataTransfer.dropEffect='copy';}});
label.addEventListener('drop',event=>{
if(!event.dataTransfer?.types.includes(playlistDragType))return;
event.preventDefault();event.stopPropagation();
const value=event.dataTransfer.getData(playlistDragType);
if(choices.some(choice=>choice.provider==='ma'&&referenceKey(choice)===value))select.value=value;
});
}
if(sceneSheet&&!choices.some(choice=>choice.provider==='ma')){
const note=dom.createElement('p');note.textContent='Connect Music Assistant to choose playlists for this scene.';panel.append(note);
}
if(document?.playlist){
const note=dom.createElement('p');note.textContent='This scene uses a Foundry soundtrack. Clear the native playlist to let Adaptive Music control the scene’s music.';panel.append(note);
}
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const button=dom.createElement('button');button.type='button';button.textContent='Save assignments';panel.append(button);
button.addEventListener('click',async()=>{button.disabled=true;try{await saveMusicAssignments({document,game,choices,defaults,values:Object.fromEntries(musicFields.map(k=>[k,controls[k].value]))});status.textContent='Assignments saved.';}catch{status.textContent='Assignments could not be saved.';onError(new MusicError('denied'));}finally{button.disabled=false;}});
+35 -8
View File
@@ -1,16 +1,18 @@
import {connectionMessage} from './connection-wizard.mjs';
import {referenceKey,selection} from '../core/scene-music.mjs';
import {musicModeLabel,referenceKey,selection} from '../core/scene-music.mjs';
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError}) {
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError,openSetup}) {
const dom=container.ownerDocument;
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
make('h2','Playback');
const now=make('section');now.className='adaptive-now';
const state=make('p','Stopped',now);state.className='adaptive-state';
const mode=make('p',null,now);mode.className='adaptive-music-mode';mode.setAttribute('role','status');
const track=make('h3','Nothing playing',now);
const playlist=make('p',null,now);
const timing=make('p',null,now);
const controls=make('div');controls.className='adaptive-actions';
const output=make('div');output.className='adaptive-fields';
@@ -18,6 +20,11 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
volume.type='range';volume.min='0';volume.max='100';volume.value='100';
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel);
seek.type='range';seek.min='0';seek.max='0';seek.step='1';seek.value='0';
const repeatLabel=make('label','Repeat',output),repeat=make('select',null,repeatLabel);
repeat.setAttribute('aria-label','Repeat');
for(const [value,label] of [['off','Off'],['all','Playlist'],['one','Track']]){
const option=make('option',label,repeat);option.value=value;
}
const summary=make('div');summary.className='adaptive-playback-summary';
const automationText=make('p',null,summary),listeners=make('p',null,summary);
const status=make('p');status.setAttribute('role','status');
@@ -29,7 +36,9 @@ 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());
const automation=button(summary,'Enable automation',async()=>{
const enable=!isRunning();
@@ -43,13 +52,18 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
const label=make('label','Override playlist',manual),select=make('select',null,label);
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions';
button(manualActions,'Apply override',()=>setOverrides([{id:'gm-manual',playlist:selection(select.value,getChoices())}]));
button(manualActions,'Clear override',()=>setOverrides([]));
const automatic=button(controls,'Return to scene music',()=>setOverrides([]));
if(openSetup)button(manualActions,'Open Adaptive Music setup',openSetup);
function isRunning(){return connection?.status.automationRunning??game.settings.get('adaptive-music','enabled');}
volume.addEventListener('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;}));
seek.addEventListener('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;}));
repeat.addEventListener('change',()=>{
const mode=repeat.value;
void run(()=>connection.control('repeat',mode));
});
async function run(action){
if(busy||!game.user.isGM)return;
@@ -60,9 +74,15 @@ 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 canControl=connected&&trackStatus?.source==='Music Assistant'&&d.lastError?.code!=='uncertain';
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
const queueError=['uncertain','receiver-access-lost'].includes(d.lastError?.code);
const canControl=connected&&trackStatus?.source==='Music Assistant'&&!queueError&&!d.campaignPaused;
state.textContent=d.campaignPaused?'Campaign music paused':states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
const cue=musicModeLabel(d.musicMode);
const modeText=cue?`Music: ${cue}`:'';
if(mode.textContent!==modeText)mode.textContent=modeText;
mode.hidden=!cue;
track.textContent=trackStatus?.title||'Nothing playing';
playlist.textContent=trackStatus?.playlist||'';
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
if(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
if(!seekEditing){
@@ -70,14 +90,21 @@ 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;
volume.disabled=busy||!connected;seek.disabled=busy||!canControl||!(playing||paused)||Number(seek.max)<=0;
repeat.disabled=busy||!canControl||!trackStatus?.repeat;
repeat.value=trackStatus?.repeat??'off';
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
const enabled=isRunning();
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
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||d.campaignPaused;
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
if(d.lastError?.code==='uncertain'){
if(queueError){
failure.textContent=`Queue needs review. ${connectionMessage(d.lastError)}`;failure.hidden=false;
}
const choices=getChoices();const display=JSON.stringify(choices.map(choice=>[referenceKey(choice),choice.name]));
+54 -3
View File
@@ -1,12 +1,27 @@
import {MusicError} from '../core/controller.mjs';
// GM browser profile only. A non-extractable key protects the stored receiver
// material; same-origin scripts and the browser profile owner remain trusted.
// MA access tokens are intentionally excluded from the serialization surface.
// Receiver records never contain the optional device credential.
export class ReceiverVault{
#database;#tail=Promise.resolve();
async #db(){
if(!globalThis.indexedDB)throw new MusicError('private-storage-unavailable');
this.#database??=new Promise((resolve,reject)=>{const request=indexedDB.open('adaptive-music-private-receivers',1);request.onupgradeneeded=()=>request.result.createObjectStore('records');request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new MusicError('private-storage-unavailable'));request.onblocked=()=>reject(new MusicError('private-storage-unavailable'));});
this.#database??=new Promise((resolve,reject)=>{
let blocked=false;
const request=indexedDB.open('adaptive-music-private-receivers',1);
request.onupgradeneeded=()=>request.result.createObjectStore('records');
request.onsuccess=()=>{
const db=request.result;
if(blocked){db.close();return;}
db.onversionchange=()=>{db.close();this.#database=undefined;};
resolve(db);
};
request.onerror=()=>reject(new MusicError('private-storage-unavailable'));
request.onblocked=()=>{blocked=true;reject(new MusicError('private-storage-unavailable'));};
}).catch(()=>{
this.#database=undefined;
throw new MusicError('private-storage-unavailable');
});
return this.#database;
}
async #scope({campaign,userId,maUrl}){
@@ -38,5 +53,41 @@ export class ReceiverVault{
await this.#transaction(id,{key,iv,data});
});this.#tail=op;return op;
}
async forget(scope){await this.#tail.catch(()=>{});await this.#transaction(await this.#scope(scope),undefined,true);}
forget(scope){
const operation=this.#tail.catch(()=>{}).then(async()=>this.#transaction(await this.#scope(scope),undefined,true));
this.#tail=operation;
return operation;
}
async #credentialId({campaign,userId}){
return 'credential:'+await this.#scope({campaign,userId,maUrl:globalThis.location.origin});
}
async loadCredential(scope){
const id=await this.#credentialId(scope);
const record=await this.#transaction(id);
if(!record)return null;
try{
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:record.iv,additionalData:new TextEncoder().encode(id)},record.key,record.data);
const value=JSON.parse(new TextDecoder().decode(bytes));
if(value.version!==1||typeof value.maUrl!=='string'||typeof value.token!=='string'||typeof value.auto!=='boolean')throw Error();
return value;
}catch{throw new MusicError('private-credential-corrupt');}
}
saveCredential(scope,{maUrl,token,targetName,auto}){
const operation=this.#tail.catch(()=>{}).then(async()=>{
const id=await this.#credentialId(scope);
const bytes=new TextEncoder().encode(JSON.stringify({version:1,maUrl,token,targetName,auto}));
if(typeof token!=='string'||!token||bytes.length>8192||typeof auto!=='boolean')throw new MusicError('private-credential-write-failed');
const key=await crypto.subtle.generateKey({name:'AES-GCM',length:256},false,['encrypt','decrypt']);
const iv=crypto.getRandomValues(new Uint8Array(12));
const data=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(id)},key,bytes);
await this.#transaction(id,{key,iv,data});
});
this.#tail=operation;
return operation;
}
forgetCredential(scope){
const operation=this.#tail.catch(()=>{}).then(async()=>this.#transaction(await this.#credentialId(scope),undefined,true));
this.#tail=operation;
return operation;
}
}
+63 -21
View File
@@ -1,13 +1,12 @@
import { MusicController } from '../core/controller.mjs';
import { candidates,combatAppliesToScene,MusicController } from '../core/controller.mjs';
import { buildMusicState } from '../core/scene-music.mjs';
import { NativeProvider } from '../providers/native/provider.mjs';
export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
import { activeMusicGM } from './authority.mjs';
// Explicit development bootstrap. No hooks or document mutations occur on import.
// All music configuration uses module-owned flags; no actor/system schema access.
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
previousController, onError = () => {} }) {
isEnabled = () => true, authority = () => game.ready && activeMusicGM(game.users)?.id === game.user.id,
previousController, onError = () => {}, onModeChange = () => {} }) {
const flag = d => d?.getFlag('adaptive-music', 'music');
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
@@ -16,26 +15,69 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
if (previousController) {
controller.generation = previousController.generation;
controller.tail = previousController.tail;
const previous=previousController.current;
// The MA session is disposable. Native playback lives in Foundry and
// remains the outgoing source when the browser connects to MA.
if(previous?.playlist?.provider==='native'&&provider.owned.has(previous.playlist.id))controller.current=previous;
if(previousController.dirty.has(previousController.providers.native))controller.dirty.add(provider);
}
let overrides = [];
const refresh = () => {
if (!isEnabled() || !authority()) return Promise.resolve();
const scene = [...game.scenes].find(s => s.active);
let overrides = [],deferredState;
const sceneDocument = scene => ({id:scene.id,music:flag(scene),nativePlaylist:scene.playlist});
const getState = () => {
const scene = game.scenes.active ?? [...game.scenes].find(s => s.active);
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
const state=buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)},
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose,
combats:[...game.combats].map(c=>({id:c.id,sceneId:c.scene?.id??c.scene,active:c.active,started:c.started,playlist:flag(c)?.playlist,
bosses:[...c.combatants].map(b=>{const f=flag(b)??flag(b.token)??{};return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};})}))});
return controller.update(state);
const choose=(ref,fallback,scene)=>{
if(scene?.nativePlaylist)return null;
return ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
};
const combats = [...game.combats].map(combat=>{
const settings = flag(combat) ?? {};
const combatants = [...combat.combatants];
return {
id:combat.id, sceneId:combat.scene?.id ?? combat.scene, active:combat.active, started:combat.started,
// Foundry v14 creates unlinked encounters by default. Token combatants
// retain their own scene association even when the encounter has none.
sceneIds:[...new Set(combatants.map(b=>b.sceneId?.id ?? b.sceneId ?? b.token?.parent?.id).filter(Boolean))],
playlist:settings.playlist, boss:settings.boss === true,
bosses:combatants.map(b=>{
const f = flag(b) ?? flag(b.token) ?? {};
return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};
})
};
});
const retainedScenes = [...game.scenes].filter(s=>s.id!==scene?.id&&
combats.some(combat=>combatAppliesToScene(combat,s.id))).map(sceneDocument);
return buildMusicState({scene:scene&&sceneDocument(scene),retainedScenes,combats,
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose});
};
const refresh = () => {
if (!isEnabled() || !authority() || controller.campaignPaused) return Promise.resolve();
const state=getState();
const intent=candidates(state)[0].key;
if(deferredState===intent)return Promise.resolve();
deferredState=undefined;
return controller.update(state).finally(onModeChange);
};
if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null });
const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'updateUser', 'deletePlaylist', 'deletePlaylistSound'];
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
return { controller, refresh,
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
// Combat start/turn hooks precede the document update on the initiating
// client. Reconcile the committed state on document hooks instead.
const events = ['updateScene', 'canvasReady', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'deletePlaylist', 'deletePlaylistSound'];
const subscriptions = events.map(event => [event, Hooks.on(event, (document,changes) => {
if(event==='updateSetting'&&!['adaptive-music.musicDefaults','adaptive-music.defaultPlaylist'].includes(document?.key))return;
if(event==='updateScene'&&changes&&!Object.hasOwn(changes,'active')&&!Object.hasOwn(changes,'flags')&&!Object.hasOwn(changes,'playlist'))return;
refresh().catch(error=>{if(error.code!=='stale')onError(error);});
})]);
return { controller, refresh,get overrideActive(){return overrides.length>0;},get awaitingSceneChange(){return deferredState!==undefined;},
get musicMode(){return overrides.length>0?'manual':controller.current?.mode;},
pauseCampaign: options => controller.pauseCampaign(options).finally(onModeChange),
resumeCampaign: () => controller.resumeCampaign(() => {
if (!isEnabled()) return undefined;
const state = getState();
return deferredState === candidates(state)[0].key ? undefined : state;
}).then(refresh).finally(onModeChange),
deferUntilMusicChanges:()=>{deferredState=candidates(getState())[0].key;},
setOverrides: value => { deferredState=undefined;overrides = structuredClone(value);onModeChange();return refresh(); },
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
};
}
+69 -11
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;
@@ -53,6 +54,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
make('h2','Assign scene music',scenePanel);
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel);
scenes.setAttribute('aria-label','Scene');
for(const scene of game.scenes)addOption(scenes,scene.id,scene.name);
const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
if(selected)scenes.value=selected.id;
@@ -81,7 +83,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
},ownershipStatus);
let choices=[];
let choices=[],lastCatalog=connection?.status.catalog;
const showScene=()=>{
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
@@ -92,6 +94,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
};
const refreshAssignments=async()=>{
lastCatalog=connection?.status.catalog;
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
};
@@ -116,7 +119,10 @@ 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();
}
if(this.#tab==='playback')void refreshPlayback();
},1500);
}
@@ -127,22 +133,74 @@ export function createSetupClass({game,gateway,audio,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 createPlaybackClass({game,connection,getChoices,start,stop,setOverrides,onError,openSetup,Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicControls extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-controls',window:{title:'Adaptive Music playback',resizable:true},position:{width:500,height:525}};
#timer;
async _renderHTML(){
const root=document.createElement('div');
root.className='adaptive-music-setup';
let choices=await getChoices();
const refresh=mountPlaybackPanel({game,container:root,connection,getChoices:()=>choices,start,stop,setOverrides,onError,openSetup});
clearInterval(this.#timer);
this.#timer=setInterval(async()=>{if(root.isConnected){choices=await getChoices();await refresh();}},1500);
void refresh();
return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
};
}
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);}
};
}
+1 -1
View File
@@ -166,7 +166,7 @@ export class MAReadClient {
}
// Server-only fixed command surface, never a browser route. Target is not an argument.
async mutate(action, args, ctx) {
const fields = {stop:[],pause:[],resume:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'],
const fields = {stop:[],pause:[],resume:[],next:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'],
play_index:['index','seek_position'],play_media:['media','option','shuffle']};
if (!Object.hasOwn(fields,action) || !args || Object.keys(args).some(k => !fields[action].includes(k)) ||
!this.#expectedName || !this.#expectedProvider || !ctx?.check) throw new MusicError('denied');
+29 -8
View File
@@ -8,20 +8,41 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
for(const path of ['/ws','/sendspin']){
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
results.push(await new Promise(resolve=>{
const started=performance.now();
const code=await new Promise(resolve=>{
let socket,timer,done=false,csp=false;
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code});};
const policy=event=>{if(event.disposition==='enforce'&&['connect-src','default-src'].includes(event.effectiveDirective)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}};
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve(code);};
const policy=event=>{
if(event.disposition!=='enforce'||!['connect-src','default-src'].includes(event.effectiveDirective))return;
if(event.blockedURI===url.href||event.blockedURI===url.origin||event.blockedURI===url.origin+'/'){
csp=true;finish('csp-blocked');
}
};
events?.addEventListener('securitypolicyviolation',policy);
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
}));
});
const elapsedMs=Math.round(performance.now()-started);
// A prompt can change the site's permission during this probe. These values
// are advisory and browser support and permission names vary.
const permissions={};
for(const name of ['local-network','local-network-access','local-network-devices','loopback-network']){
try{
const state=(await globalThis.navigator?.permissions?.query({name}))?.state;
if(['granted','prompt','denied'].includes(state))permissions[name]=state;
}catch{}
}
results.push({path,code,elapsedMs,...(Object.keys(permissions).length&&{permissions})});
}
return results;
}
export const diagnosticMessage=result=>({
export const diagnosticMessage=result=>{
const hint=result.code!=='upgrade-ok'&&Object.entries(result.permissions??{}).some(([permission,state])=>permission!=='loopback-network'&&state==='denied')
? ' This Foundry site also reports denied local network access. If the proxy is on your private network, review Foundry’s site permission in the browser.' : '';
return ({
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
}[result.code]??'Diagnostic unavailable.');
'upgrade-timeout':'The WebSocket upgrade timed out. Check for a browser permission prompt and try opening the normal MA HTTPS page in this profile.',
'upgrade-failed':'The browser did not expose a successful upgrade. Try opening the normal MA HTTPS page in this profile and check this Foundry site’s permissions. Browser code cannot read the failed handshake’s HTTP status or TLS error.'
}[result.code]??'Diagnostic unavailable.')+hint;
};
+12 -6
View File
@@ -21,6 +21,7 @@ export class MAPlaybackProvider {
title: typeof item?.name === 'string' ? item.name.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 180) : '',
duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
position,
repeat: queue.repeat_mode,
};
}
#check(ctx) {
@@ -41,7 +42,7 @@ export class MAPlaybackProvider {
async #capture(ctx) {
this.#check(ctx);await this.#client.verifyTarget();
const before=await this.#client.queueState();
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1 || before.ended) throw new MusicError('unsupported');
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1) throw new MusicError('unsupported');
const items=[];
for(let offset=0;offset<5000;offset+=100){this.#check(ctx);const page=await this.#client.queueItems(offset);items.push(...page);if(page.length<100)break;if(offset===4900)throw new MusicError('unsupported');}
const after=await this.#client.queueState();
@@ -50,12 +51,12 @@ export class MAPlaybackProvider {
if (before.items!==items.length || stable(before)!==stable(after) || identity(items)!==identity(again)) throw new MusicError('stale');
if (!['idle','playing','paused'].includes(after.state) || !['off','one','all'].includes(after.repeat_mode) ||
(items.length && (!Number.isSafeInteger(after.current_index) || after.current_index<0 || after.current_index>=items.length))) throw new MusicError('unsupported');
const elapsed=after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
const elapsed=after.ended ? 0 : after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
const position=Math.floor(elapsed ?? 0);
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
this.#check(ctx);
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000,
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
state:after.ended?'idle':after.state,ended:after.ended===true,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
if(this.#paused){if(value.state!=='idle'||JSON.stringify(value.items)!==JSON.stringify(this.#paused.items))throw new MusicError('stale');return {...value,state:'paused',index:this.#paused.index,position:this.#paused.position};}
return value;
@@ -72,16 +73,18 @@ export class MAPlaybackProvider {
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>{this.#paused=undefined;return this.#client.mutate('stop',{},this.#context(ctx));}); }
async control(action,value,ctx) {
this.#check(ctx);
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
const args={pause:{},resume:{},stop:{},next:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
if(!Object.hasOwn(args,action))throw new MusicError('denied');
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{
if(action==='pause'&&this.#client.supportsNativePause?.()===false){
const captured=await this.#capture(ctx);if(!captured.items.length)return;
const captured=await this.#capture(ctx);if(!captured.items.length||captured.ended)return;
await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
}else if(action==='resume'&&this.#paused){
const captured=await this.#capture(ctx);await this.#client.mutate('play_index',{index:captured.index,seek_position:captured.position},this.#context(ctx));this.#paused=undefined;
}else if(action==='seek'&&this.#paused){
const captured=await this.#capture(ctx);if(!Number.isSafeInteger(value)||value<0||!(captured.items[captured.index]?.duration>value))throw new MusicError('unsupported');this.#paused={...captured,position:value};
}else if(action==='next'&&this.#paused){
throw new MusicError('unsupported');
}else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
this.#epoch++;
});
@@ -103,9 +106,12 @@ export class MAPlaybackProvider {
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
if(value.state==='paused'&&this.#client.supportsNativePause?.()===false)this.#paused=structuredClone(value);
else{await write('play_index',{index:value.index,seek_position:value.position});if(value.state==='paused')await write('pause',{});}
else if(!value.ended){
await write('play_index',{index:value.index,seek_position:value.position});
if(value.state==='paused')await write('pause',{});
if(value.state==='idle')await write('stop',{});
}
}
});
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
const commands=new Set(['sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','next','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;#authenticated=false;#onDisconnect;
+2 -1
View File
@@ -24,7 +24,7 @@ export class NativeProvider {
return { id: p.id, soundId: sound.id };
}
async snapshot(ctx) {
const playlists = [...this.owned].map(id => {
const playlists = [...this.owned].filter(id=>!this.sceneConflict(id)).map(id => {
const p = this.playlist(id, ctx);
return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({
id: s.id, playing: s.playing, pausedTime: s.playing ? (s.sound?.currentTime ?? 0) : s.pausedTime,
@@ -35,6 +35,7 @@ export class NativeProvider {
}
async stopOwned(ctx) {
for (const id of this.owned) {
if(this.sceneConflict(id))continue;
const p = this.playlist(id, ctx);
const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null }));
if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
+33
View File
@@ -43,3 +43,36 @@
#adaptive-music-setup .adaptive-checklist input {min-height:0;}
#adaptive-music-setup details[open] > :not(summary) {margin-block-start:0.5rem;}
#adaptive-music-setup [role="alert"] {padding:0.55rem;border-inline-start:3px solid var(--color-level-error,#aa3b30);overflow-wrap:anywhere;}
.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;}
+32 -5
View File
@@ -4,14 +4,41 @@
<section id="adaptive-music-setup"><main id="app" class="window-content"></main></section>
<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',active:true,getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;window.saved=flag}};
const scene={id:'scene',name:'Moonlit forest',documentName:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;window.saved=flag}};
const game={user:{isGM:true},settings:{get:(ns,k)=>settings[k],set:async(ns,k,v)=>{settings[k]=v}},playlists:collection([{id:'native',name:'Foundry fallback'}]),scenes:collection([scene]),combats:[]};
let trackState='playing',position=12;window.controlActions=[];
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90}),
control:async(action,value)=>{window.controlActions.push(action);if(action==='seek')position=value;else trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}};
let trackState='playing',position=12,repeat='off';window.controlActions=[];
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'ws-upgrade-failed',stage:'API authentication',detail:p.token};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90,repeat}),
control:async(action,value)=>{window.controlActions.push(action);if(action==='seek')position=value;else if(action==='repeat')repeat=value;else trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}};
const Setup=createSetupClass({game,connection,getChoices:async()=>[{provider:'native',id:'native',name:'Foundry fallback'},...catalog],start(){},stop(){},setOverrides(){},onError(){},Base:class{}});
document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
window.nativeConfiguration=async()=>{
const callbacks=new Map();
const Hooks={on:(event,callback)=>callbacks.set(event,callback),off:event=>callbacks.delete(event)};
const directory=document.createElement('aside'),sheet=document.createElement('section');
directory.id='fixture-playlists';sheet.id='fixture-scene';document.body.append(directory,sheet);
const interfaces=startConfigurationInterfaces({game,Hooks,getChoices:()=>catalog,onError(error){throw error;}});
await callbacks.get('renderPlaylistDirectory')({},directory);
window.refreshNativeConfiguration=async()=>{
await interfaces.refreshDirectory({element:directory});
await callbacks.get('renderSceneConfig')({document:scene},sheet);
};
window.closeNativeConfiguration=()=>{interfaces.dispose();directory.remove();sheet.remove();};
};
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();}
}
});
+1 -1
View File
@@ -39,5 +39,5 @@ test('editor uses text for catalog labels and rechecks GM on actual save event',
test('configuration hook disposal prevents pending asynchronous render from mounting',async()=>{
const f=fixture(),callbacks=new Map();let resolve;const off=[];
const ui=startConfigurationInterfaces({...f,Hooks:{on(e,fn){callbacks.set(e,fn);return e;},off(...args){off.push(args);}},getChoices:()=>new Promise(r=>{resolve=r;})});
const root=container();const pending=callbacks.get('renderSceneConfig')({document:f.document},root);ui.dispose();resolve(choices);await pending;assert.equal(root.children.length,0);assert.equal(off.length,2);
const root=container();const pending=callbacks.get('renderSceneConfig')({document:f.document},root);ui.dispose();resolve(choices);await pending;assert.equal(root.children.length,0);assert.equal(off.length,3);
});
+26
View File
@@ -38,3 +38,29 @@ test('synchronous browser CSP rejection waits for the asynchronous enforcement e
}});
assert.deepEqual(results.map(r=>r.code),['csp-blocked','csp-blocked']);
});
test('probe samples the site permission after each route and records its elapsed time',async t=>{
const permissions=Object.getOwnPropertyDescriptor(globalThis.navigator,'permissions');
let state='prompt';
Object.defineProperty(globalThis.navigator,'permissions',{configurable:true,value:{query:async({name})=>{
if(name!=='local-network')throw new TypeError('Unknown permission');
return {state};
}}});
t.after(()=>{
if(permissions)Object.defineProperty(globalThis.navigator,'permissions',permissions);
else delete globalThis.navigator.permissions;
});
const results=await probeWebSockets('https://ma.example.test',{createSocket:url=>{
const socket={close(){}};
queueMicrotask(()=>{
const opened=url.endsWith('/ws');
state=opened?'granted':'denied';
if(opened)socket.onopen();
else socket.onerror();
});
return socket;
}});
assert.deepEqual(results.map(result=>result.permissions),[{'local-network':'granted'},{'local-network':'denied'}]);
assert.ok(results.every(result=>Number.isSafeInteger(result.elapsedMs)&&result.elapsedMs>=0));
assert.match(diagnosticMessage(results[1]),/reports denied local network access/);
});
+121
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');
@@ -67,6 +133,35 @@ test('scene change during manual never resurrects previous scene', async () => {
await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')});
assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0);
});
test('a scene excursion during a live encounter keeps only its interrupted ambient snapshot',async()=>{
const f=fixture();
const a=scene(), b=scene('B'), fight=combat();
const original={scene:a,combats:[fight]};
await f.controller.update({scene:a});
f.playback={...f.playback,offset:36};
await f.controller.update(original);
await f.controller.update({scene:b,combats:[fight],retainedAmbient:[a]});
assert.equal(f.playback.items[0],'B');
await f.controller.update(original);
assert.equal(f.controller.current.mode,'combat');
await f.controller.update({scene:a});
assert.equal(f.controller.current.mode,'ambient');
assert.equal(f.playback.offset,36);
await f.controller.update(original);
await f.controller.update({scene:b,combats:[fight],retainedAmbient:[a]});
await f.controller.update({scene:b});
assert.equal(f.controller.frames.length,0);
assert.equal((await f.controller.update({scene:a})).restored,false);
});
test('same playlist may change combat mode to boss without restarting the queue',async()=>{
const f=fixture(), fight=combat(), state={scene:scene(),combats:[fight]};
await f.controller.update(state);
const before=f.log.length;
await f.controller.update({...state,combats:[{...fight,bossPlaylist:fight.playlist}]});
assert.equal(f.controller.current.mode,'boss');
assert.equal(f.log.length,before);
});
test('boss removed during manual and deleted combat cannot return', async () => {
const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]};
await f.controller.update(base); await f.controller.update(big);
@@ -152,3 +247,29 @@ test('superseded cross-provider apply is reconciled by stopping partially touche
const newest=f.controller.update({scene:scene()});resume();await assert.rejects(stale,{code:'stale'});await newest;
assert.equal(cleanups,1);assert.equal(f.playback.items[0],'A');
});
test('duplicate hooks during a transition share its fence and a shared playlist does not restart',async()=>{
const {controller,log}=fixture();
const state={scene:{id:'A',playlist:ref('same')}};
const first=controller.update(state),duplicate=controller.update(structuredClone(state));
assert.equal(duplicate,first);
await first;
assert.equal((await controller.update({scene:{id:'B',playlist:ref('same')}})).unchanged,true);
assert.deepEqual(log,[['resolve','same'],['apply','same']]);
});
test('shared ambient and combat cue retains its position when combat ends under an override',async()=>{
const f=fixture();
const ambient={scene:scene()};
const fighting={...ambient,combats:[{...combat(),playlist:ambient.scene.playlist}]};
const overrides=[{id:'manual',playlist:ref('different')}];
await f.controller.update(ambient);
await f.controller.update(fighting);
const saved={...f.playback,offset:73};
f.playback=saved;
await f.controller.update({...fighting,overrides});
await f.controller.update({...ambient,overrides});
assert.equal((await f.controller.update(ambient)).restored,true);
assert.equal(f.playback.offset,saved.offset);
assert.deepEqual(f.playback.items,saved.items);
});
+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;
+11
View File
@@ -113,3 +113,14 @@ test('Sendspin pause emulation retains position and restores paused queues witho
assert.deepEqual(f.writes.slice(before).map(w=>w.action),['stop','clear','repeat','play_media']);
const again=await f.provider.snapshot({...f.ctx,generation:7});assert.equal(again.value.state,'paused');assert.equal(again.value.index,1);assert.equal(again.value.position,17);
});
test('an exhausted ambient queue can be interrupted and restored without starting audio',async()=>{
const f=fixture();
Object.assign(f.state,{state:'idle',ended:true,current_index:2,elapsed_time:0,repeat_mode:'off'});
const finished=await f.provider.snapshot(f.ctx);
assert.equal(finished.value.ended,true);
f.state.ended=false;
await f.provider.restore(finished,{...f.ctx,generation:2});
assert.deepEqual(f.writes.map(write=>write.action),['stop','clear','repeat','play_media']);
assert.equal(f.state.state,'idle');
});
+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,2);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;}
});
+46 -5
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,15 +51,55 @@ test('scene-linked playlist conflict and lost authority fail before mutation',as
provider.sceneConflict=()=>false;
await assert.rejects(provider.stopOwned({...ctx,check(){throw new Error('lost');}}));assert.equal(calls.length,0);
});
test('GM election deterministic and no GM means none',()=>{
assert.equal(primaryGM([{id:'z',active:true,isGM:true},{id:'a',active:true,isGM:true},{id:'0',active:false,isGM:true}]),'a');
assert.equal(primaryGM([]),undefined);
test('only one active full GM has authority and assistants are listeners',()=>{
const gm={id:'a',active:true,role:4,isGM:true};
const assistant={id:'b',active:true,role:3,isGM:true};
assert.equal(activeMusicGM([assistant,gm,{active:false,role:4}]),gm);
assert.equal(activeMusicGM([assistant]),undefined);
assert.equal(activeMusicGM([gm,{id:'z',active:true,role:4}]),undefined);
assert.equal(activeMusicGM([{...gm,isBanned:true}]),undefined);
assert.equal(isMusicListener(assistant),true);
});
test('Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access',async()=>{
const callbacks=new Map();let index=0,registered=0;
const Hooks={on(e,cb){callbacks.set(++index,cb);return index;},off(e,id){callbacks.delete(id);}};
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[],combats:[],
const game={ready:true,user:{id:'gm'},users:[{id:'gm',role:4,active:true}],playlists:collection([]),scenes:[],combats:[],
settings:{register(){registered++;},get(){return null;}}};
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[]});
await runtime.refresh();assert.equal(registered,1);assert.ok(callbacks.size>0);runtime.dispose();assert.equal(callbacks.size,0);
});
test('Foundry runtime uses committed unlinked combatant scenes and coalesces initiative changes',async()=>{
const callbacks=new Map(), calls=[];
const Hooks={on(event,callback){callbacks.set(event,callback);return event;},off(event){callbacks.delete(event);}};
const ref=id=>({provider:'ma',id});
const scene={id:'A',active:true,getFlag:()=>({ambient:ref('ambient'),combat:ref('battle'),boss:ref('boss')})};
const encounter={id:'fight',scene:null,active:true,started:false,
combatants:[{id:'token',sceneId:'A',getFlag:()=>undefined}],getFlag:()=>({boss:true})};
const combats=collection([encounter]);
const game={ready:true,user:{id:'gm'},users:[{id:'gm',role:4,active:true}],playlists:collection([]),scenes:[scene],combats,
settings:{register(){},get(){return null;}}};
const maProvider={supports:()=>true,resolve:async ref=>ref,apply:async ref=>calls.push(ref.id),stopOwned:async()=>{},snapshot:async()=>({}),
restore:async()=>calls.push('restored')};
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[],maProvider});
await runtime.refresh();
assert.equal(runtime.musicMode,'ambient');
assert.equal(callbacks.has('combatStart'),false);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient']);
combats.set(encounter.id,encounter);
encounter.started=true;
callbacks.get('updateCombat')(encounter,{round:1,turn:0});
await runtime.controller.tail;
assert.equal(runtime.musicMode,'boss');
callbacks.get('updateCombat')(encounter,{turn:1});
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss']);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss','restored']);
assert.equal(runtime.musicMode,'ambient');
runtime.dispose();
});
+61
View File
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict';
import {test} from 'node:test';
import {PcmTimeline} from '../../src/audio/pcm-timeline.mjs';
const sampleRate=48000;
const packet=serverTimeUs=>({samples:[new Float32Array(960)],sampleRate,serverTimeUs});
function fixture(){
const sources=[];
const context={currentTime:1,state:'running',
createBuffer:(_channels,frames)=>({data:new Float32Array(frames),getChannelData(){return this.data;}}),
createBufferSource(){
const source={playbackRate:{value:1},connect(){},disconnect(){},start(time){this.time=time;},stop(time){this.stopTime=time;}};
sources.push(source);
return source;
},
};
return {context,sources,timeline:new PcmTimeline(context,{})};
}
test('consecutive PCM stays contiguous under a jittering browser clock',()=>{
const {context,sources,timeline}=fixture();
for(let i=0;i<8;i++){
context.currentTime=1+i*0.02+i%2*0.0025;
timeline.push(packet(2000000+i*20000),1900000+i*20000);
}
for(let i=1;i<sources.length;i++){
const previous=sources[i-1],current=sources[i];
assert.ok(Math.abs(current.time-previous.time-0.02/previous.playbackRate.value)<1e-9);
}
assert.equal(timeline.diagnostics.sourceGaps,0);
assert.equal(timeline.diagnostics.underruns,0);
});
test('partial clear preserves only the valid span and allows replacement at its boundary',()=>{
const {sources,timeline}=fixture();
const start=timeline.push(packet(2000000),1900000);
timeline.push(packet(2020000),1900000);
timeline.push(packet(2040000),1900000);
timeline.clear(2030000);
assert.ok(Math.abs(sources[1].stopTime-start-0.03)<1e-9);
assert.equal(sources[2].stopTime,undefined);
assert.equal(timeline.push(packet(2030000),1900000),sources[1].stopTime);
assert.equal(timeline.diagnostics.sourceOverlaps,0);
});
test('source gaps and late packets are observable separately from suspension',()=>{
const {context,timeline}=fixture();
timeline.push(packet(2000000),1900000);
timeline.push(packet(2030000),1900000);
assert.equal(timeline.diagnostics.sourceGaps,1);
assert.equal(timeline.diagnostics.gapMs,10);
assert.equal(timeline.push(packet(1000000),1900000),false);
assert.equal(timeline.diagnostics.droppedLate,1);
context.state='suspended';
assert.equal(timeline.push(packet(2080000),1900000),false);
assert.equal(timeline.diagnostics.bufferedMs,0);
context.state='running';
assert.ok(timeline.push(packet(2080000),1900000)>0);
assert.equal(timeline.diagnostics.sourceGaps,1);
});
+13
View File
@@ -19,6 +19,19 @@ test('native fallback is explicit, manual silence wins and legacy ambient does n
assert.equal(candidates(state)[0].playlist,null);assert.equal(state.scene.playlist.id,'fallback');assert.equal(state.combats[0].playlist.id,'fallback');
assert.equal(buildMusicState({scene:{id:'s',music:{ambient:null,playlist:native('old')}}}).scene.playlist,null);
});
test('unlinked encounters follow their token scenes and a designated boss uses the scene default',()=>{
const encounter={id:'fight',active:true,started:true,sceneId:null,sceneIds:['A'],boss:true};
const cue=(id,combat=encounter,music={ambient:ma('ambient'),combat:ma('fight'),boss:ma('climax')})=>
candidates(buildMusicState({scene:{id,music},combats:[combat]}))[0];
assert.equal(cue('A').mode,'boss');
assert.equal(cue('A').playlist.id,'climax');
assert.equal(cue('A',{...encounter,boss:false}).mode,'combat');
assert.equal(cue('A',{...encounter,started:false}).mode,'ambient');
assert.equal(cue('B').mode,'ambient');
assert.equal(cue('B',{...encounter,sceneId:'B'}).mode,'boss');
assert.equal(cue('A',encounter,{combat:ma('fight')}).mode,'combat');
assert.equal(cue('A',{...encounter,bosses:[{id:'leader',active:true,playlist:ma('custom')}]}).playlist.id,'custom');
});
test('unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny',async()=>{
let flag={ambient:ma('old')};const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}};const game={user:{isGM:true}};
await saveMusicAssignments({document,game,choices:[],values:{ambient:referenceKey(ma('old'))}});assert.equal(flag.ambient.id,'old');
+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()=>{
+36 -1
View File
@@ -2,6 +2,7 @@ import hashlib
import importlib.util
import json
from pathlib import Path
import stat
import tempfile
import unittest
from unittest.mock import patch
@@ -24,7 +25,7 @@ class ReleaseTests(unittest.TestCase):
root=Path(folder);bundle=release.build_release(output=root);first=bundle.read_bytes();release.build_release(output=root)
self.assertEqual(first,bundle.read_bytes())
with zipfile.ZipFile(bundle) as outer:
self.assertTrue({'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','LICENSE','THIRD-PARTY-NOTICES','SHA256SUMS'}.issubset(outer.namelist()))
self.assertTrue({'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','HANDOFF.md','USER-ACCEPTANCE.md','LICENSE','THIRD-PARTY-NOTICES','SHA256SUMS'}.issubset(outer.namelist()))
standalone=json.loads(outer.read('module.json'))
for row in outer.read('SHA256SUMS').decode().splitlines():
digest,name=row.split(' ',1);self.assertEqual(hashlib.sha256(outer.read(name)).hexdigest(),digest)
@@ -39,6 +40,8 @@ class ReleaseTests(unittest.TestCase):
if (ROOT/evidence).is_file():
self.assertEqual(outer.read(evidence),source.read(f'adaptive-music-source/{evidence}'))
release.validate_package(root/'adaptive-music.zip',standalone)
self.assertEqual(json.loads((root/'release.json').read_bytes())['runtimeAssetsSHA256'],
release.runtime_assets_sha256(root/'adaptive-music.zip'))
(root/'licenses').mkdir(exist_ok=True)
(root/'licenses/unmanaged.txt').write_text('must not be swept into the release')
with self.assertRaises(ValueError):release.build_release(output=root)
@@ -58,4 +61,36 @@ class ReleaseTests(unittest.TestCase):
with patch.object(release.subprocess,'check_output',side_effect=FileNotFoundError):
entries=release.source_entries(manifest)
self.assertIn('adaptive-music-source/src/audio/gm-host.mjs',entries)
self.assertIn('adaptive-music-source/HANDOFF.md',entries)
self.assertIn('adaptive-music-source/USER-ACCEPTANCE.md',entries)
self.assertIn('adaptive-music-source/SOURCE_REVISION.txt',entries)
def test_source_revision_status_distinguishes_checkout_and_generated_manifest(self):
manifest=release.release_manifest()
with patch.object(release.subprocess,'check_output',return_value=''):
self.assertEqual(release.source_revision_status(manifest),'clean Git checkout')
generated=release.release_manifest('https://github.com/example/adaptive-music')
self.assertIn('generated release manifest',release.source_revision_status(generated))
with patch.object(release.subprocess,'check_output',return_value=' M src/file\n'):
self.assertIn('base revision',release.source_revision_status(manifest))
with patch.object(release.subprocess,'check_output',side_effect=FileNotFoundError):
self.assertIn('without Git metadata',release.source_revision_status(manifest))
def test_package_rejects_unexpected_files_or_replaced_provenance(self):
manifest=release.release_manifest()
with tempfile.TemporaryDirectory() as folder:
path=Path(folder)/'bad.zip'
entries=release.module_entries(manifest)
release.write_zip(path,{**entries,'adaptive-music/extra.json':b'{}'})
with self.assertRaisesRegex(ValueError,'inventory'):release.validate_package(path)
entries['adaptive-music/vendor/provenance.json']=b'{}'
release.write_zip(path,entries)
with self.assertRaisesRegex(ValueError,'provenance'):release.validate_package(path)
entries=release.module_entries(manifest)
with zipfile.ZipFile(path,'w') as archive:
for name,data in entries.items():
info=zipfile.ZipInfo(name)
if name.endswith('/LICENSE'):
info.external_attr=(stat.S_IFLNK|0o777)<<16
archive.writestr(info,data)
with self.assertRaisesRegex(ValueError,'inventory'):release.validate_package(path)