4 Commits
Author SHA1 Message Date
Jason 357c904d1b Adaptive Music v0.8.1 combat automation fixes
Validate and generate manual release / package (push) Waiting to run
2026-12-05 13:37:05 -05:00
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
Jason 8c07a468a4 Synchronize Gitea manifest upload 2026-12-04 11:15:28 -05:00
CheddahBoxMB 4f3fac5f1c Upload files to "/" 2026-12-04 11:13:48 -05:00
53 changed files with 4914 additions and 347 deletions

No files matched your search

+62 -34
View File
@@ -1,4 +1,4 @@
# Adaptive Music architecture — 0.7.2 # Adaptive Music architecture — 0.8.1
Adaptive Music is an independent project by CheddahBoxMB for Foundry v14.371 and 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 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 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 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 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 trusted-origin scripts or theft of the complete browser profile. A GM can opt in
persisted. Failed attempts retain private inputs in tab memory; changing the MA to a separate encrypted device record with the MA token, address, receiver name
origin never reuses its token or identity. 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 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. 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 `/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 this new web receiver with already-authenticated API sessions for the token. The
same API session must therefore survive pairing, catalog reads and playback. 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 `sendspin/pair_web_player` pairs only this identity to the calling account. Noise
activation and clock synchronization precede exact ID/name/provider/topology checks. activation and clock synchronization precede exact ID/name/provider/topology checks.
During startup, a successful null queue lookup is retried briefly on the same 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 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 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. 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 Saving that scene again writes the new reference. Scene and world flags hold opaque references. The active GM browser and its audio
references. Live connections still depend on the active GM browser and its audio context host the live connection. Disconnect ends that session and pauses automatic
context. Disconnect stops the session and clears the in-memory token. reconnection.
## Audio and listeners ## Audio and listeners
The pinned official SDK negotiates PCM, performs Noise and time synchronization, The pinned official SDK negotiates PCM, performs Noise and time synchronization,
and decodes audio. A bounded Web Audio scheduler accepts the normal approximately and decodes audio. A bounded Web Audio timeline anchors a packet run to the local
four-second stream-ahead window (six-second ceiling, 512 nodes and 2 MiB of decoded audio clock and advances it by each rendered chunk’s length. The browser converts
buffers). Timestamped partial clears trim only affected audio. Full clears and ends sample rates from each AudioBuffer’s input rate. A 120 ms startup cushion and
stop the stream. A software gain and output meter feed the GM speakers and a single bounded 0.1% rate correction absorb jitter and drift. The queue allows eight
MediaStreamDestination track for listener distribution. 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. User document public keys authenticate ephemeral ECDH/AES-GCM invitation delivery.
Private keys stay in memory. Invitations are bound to world, sender, recipient, Private keys stay in memory. Invitations are bound to world, sender, recipient,
@@ -66,18 +76,22 @@ never PCM over that socket. Firefox’s session-level SDP direction default is
correctly overridden by the sole audio media direction. Offers remain recvonly; correctly overridden by the sole audio media direction. Offers remain recvonly;
answers remain sendonly. Video, data and injected sender media are rejected. answers remain sendonly. Video, data and injected sender media are rejected.
Up to eight listeners negotiate automatically. Invitations renew after 20 minutes Up to eight listeners negotiate automatically. A signaling invitation expires
and expire after 30. Failed negotiation times out after 20 seconds; disconnected after 30 minutes. Established DTLS-SRTP media continues while its listener and GM
peers are revoked after 10 seconds and the 15-second reconciliation loop can issue remain authorized. Failed negotiation times out after 20 seconds and a disconnected
fresh invitations. One user gesture unlocks browser audio when required. A stable peer is dropped after 10 seconds. The reconciliation loop can invite the listener
HTMLAudioElement pumps the incoming remote track; Web Audio provides an optional again. One user gesture unlocks browser audio when required. A stable
activated playback path. Default ICE has no public STUN/TURN service. WAN delivery HTMLAudioElement plays the incoming track, with an optional activated Web Audio
requires a viable existing ICE route and is not inferred from local tests. path. Default ICE uses no public STUN/TURN service.
## Transitions and recovery ## Transitions and recovery
Manual override/silence > explicit boss > started combat in the active scene > Manual override/silence > combatant boss override > designated encounter boss cue
ambient > world default > silence. No system actor schemas are used. The existing > 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. 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 A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
server-side distributed fence or seamless handover protocol. server-side distributed fence or seamless handover protocol.
@@ -85,23 +99,37 @@ server-side distributed fence or seamless handover protocol.
Every queue mutation verifies the exact dedicated target, standalone topology and Every queue mutation verifies the exact dedicated target, standalone topology and
its own active queue. Signed snapshots retain ordered duplicates, index, repeat, its own active queue. Signed snapshots retain ordered duplicates, index, repeat,
whole-second position and state, scoped to campaign/session/fence/generation for up 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 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 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 Reconnecting to a remembered receiver can preserve its existing queue. When the
without replacing it. Automation remains paused for explicit resumption when that trusted device auto-reconnects with a populated queue, the next music intent
queue is nonempty. Crash/reload cannot guarantee restoration of an interrupted or explicit return to scene music takes control. Crash or reload can lose the
ambient stack or logical pause position. No crossfade or independent simultaneous ambient interruption stack and logical pause. Adaptive Music provides sequential
layers is implemented with the single upstream queue. Native playback uses only fade-out and fade-in using its one MA queue. True overlap between arbitrary
explicitly owned playlists; effects and AmbientSound remain untouched. 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 ## Verification boundary
The installed v0.7.0 module was tested in a logged-in Foundry v14.371 development 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 world through the private Nginx route. The v0.8.0 browser preview used validated
received audio using Foundry’s module socket for signaling. The test also exercised ZIP assets with the real development world, MA and two listeners. It exercised
real combat hooks, ordered ambient restoration, and User document permissions. Foundry module-socket signaling, scene and combat hooks, ordered ambient
Earlier browser tests used a Playwright source overlay. The original Mac path, restoration, real playback controls and User document permissions. The operator
physical-device audibility, invitation renewal and WAN behavior remain unverified. 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).
+44
View File
@@ -1,5 +1,49 @@
# Changelog # Changelog
## 0.8.1 — Combat Tracker cues and Firefox diagnostics
- Follow the combatants' token scenes when Foundry creates an unlinked
encounter through its native token HUD. Switch after combat starts, keep
the cue across initiative changes, and restore ambient when combat ends.
- Add **Boss encounter** to the GM's native Combat Tracker. Beginning a
designated encounter uses the scene's default boss cue. The tracker and
Playback panel show the current music mode and expose a way back to
automation while a manual override is active.
- Retain an interrupted ambient position across a scene excursion while
the original encounter remains active.
- Record the last failed Connect action's timestamp, error code and known setup
stage in the copyable connection report.
- Record each unauthenticated WebSocket probe's duration and the site permission
state observed after that route completes. Keep opaque upgrade failures
distinct from a confirmed CSP block.
- Record installed v0.8.0 macOS operator acceptance and the Firefox connectivity
failure. The macOS Firefox fix is still awaiting diagnosis.
## 0.8.0 — playback stability and native Foundry controls
- Keep Sendspin PCM packet boundaries contiguous in Web Audio. Track source gaps,
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 ## 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. - 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.
+274
View File
@@ -0,0 +1,274 @@
# Adaptive Music v0.8.1 handoff
## Repository state
The original workspace's Git metadata is read-only. Before v0.8.1 changes,
its 157 tracked and untracked source files matched the clean local release
commit `1ed6b4c` byte for byte. The original HEAD `987122f` is that commit's
parent. Develop on `v0.8.1-firefox` in the remote-free
`.local/v080-release-checkout`. Its `main` branch retains `1ed6b4c`.
The operator reported Gitea published v0.8.0 from `95b0427`. That object
is absent in both local Git databases. The published commit's ancestry
can be checked if its Git object is supplied offline.
A read-only check of the authorized private Foundry route confirmed the
installed manifest is v0.8.0 and all 28 runtime files match `1ed6b4c`.
The v0.8.1 archive is built from a clean checkout and its source is compared
against its local commit. Read its exact commit in
`dist/releases/v0.8.1/release.json`. Gitea access and production deployment
are outside this work.
## Installed v0.8.0 macOS acceptance
- **Operator pass:** Chrome connectivity, credentials after quitting and
reopening Chrome, automatic scene playlist activation, background-tab audio,
remote player audio over WAN, and smooth transitions. The operator heard no
stuttering or crackling during their session.
- **Operator fail:** macOS Firefox connectivity.
- **Combat follow-up:** assigned battle music worked when used as ambient,
while normal combat left ambient playing. The operator could not find
the boss designation. Combat, restoration, boss and manual controls need
hands-on acceptance with the corrected candidate.
## v0.8.1 native combat correction
The native token HUD created an unlinked encounter on Foundry 14.371 and D&D 5e
6.1.2. Installed v0.8.0 ignored it even after the native tracker started round 1.
Use the Combatant token scene when the encounter has no explicit scene. The
tracker now has a GM-only **Boss encounter** option and shows the playback mode
and **Return to automation** for a manual override. The same combat and boss
assignment can change mode without restarting the queue. Use distinct playlists
to verify the audible changes.
The authorized GUI run and its hook trace live under ignored
`.local/v081-combat-gui-*`. See [TESTING.md](TESTING.md) and
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the reproduced lifecycle and steps.
The Chromium browser preview used three distinct cues and restored ambient at
30, 33 and 46 seconds across normal, boss and manual-override encounters.
It verified turn and round continuity, End Combat cancellation, scene changes,
and returning from the manual hold. The server still reported v0.8.0 during
the previews. Headed Firefox repeated the normal combat lifecycle against the
same runtime and restored ambient at 9 seconds.
## v0.8.1 Firefox investigation
- The two WSS routes opened with HTTP 101 in Mozilla Firefox 161.0.1 on Ubuntu
from the anonymous Foundry origin and the MA origin using the native
WebSocket. Trusted TLS and the authorized private route were retained.
- The isolated stock-Firefox policy test reproduced enforced CSP, report-only
CSP, a server-side Origin rejection and a mismatched TLS certificate. Browser
script saw Origin rejection and TLS rejection as opaque upgrade failures.
- The candidate improves the token-free report with manual Connect failure
stage and time, per-route duration and post-probe permission states.
Audio, credential storage and the authenticated transport are outside the
change. The original macOS failure needs the browser-side capture described
in [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md#capture-the-firefox-failure).
- The private stock browser, scripts and raw reports under `.local/v081-*`
are test-only. See [sanitized v0.8.1 evidence](evidence/v0.8.1-live.json).
## Historical v0.8.0 audit checkpoint
- The development world keeps **Christmas — Adaptive Music demo** active with
Christmas music assigned. **Dûr-Khazrak — Adaptive Music demo** has distinct
ambient, combat and boss cues and a prepared, unstarted encounter with the
Dûr-Khazrak Champion. Its ambient uses a development playlist as a stand-in.
The authorized catalog contained no identifiable dwarven soundtrack.
- The 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.1"
python3 scripts/release.py --validate dist/releases/v0.8.1/adaptive-music.zip
(cd dist/releases/v0.8.1 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.1.zip.sha256)
```
The headed browser tests use the authorized private Nginx HTTPS route and retain
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.
+96 -27
View File
@@ -1,4 +1,4 @@
# Install and connect — 0.7.2 # Install and connect — 0.8.1 candidate
## Normal setup ## Normal setup
@@ -8,33 +8,53 @@
The ZIP contains one `adaptive-music/` directory. Do not install the outer release The ZIP contains one `adaptive-music/` directory. Do not install the outer release
bundle or source archive as the module. bundle or source archive as the module.
2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**, 2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**,
enter the private **HTTPS Music Assistant server address** and the dedicated enter the private **HTTPS Music Assistant server address** and a dedicated
account’s access token. Use the server origin and select **Connect** to create or long-lived token from MA → Settings → Profile. On a trusted browser, check
reconnect the campaign receiver, pair it, and load playlists. **Remember credentials and reconnect on this trusted device**. Select
3. Select **Choose scene music**. In **Scene Music**, choose the scene and save its **Connect** to authenticate, provision the receiver and load the catalog.
ambient, combat, boss and native fallback assignments. You can also set world 3. Open a scene’s native **Configure Scene** window. Assign music under
defaults and individual boss overrides. **Adaptive Music** and select **Save assignments**. The Playlists sidebar
4. Open **Playback** to enable automation, see the current track and listeners, or also lists draggable MA catalog entries for the scene’s playlist fields.
adjust campaign volume and control the dedicated MA queue. 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 connect automatically. If a browser requires activation, open Campaign 5. Players connect automatically. If a browser requires activation, open Campaign
audio and select **Enable Audio** once. Keep one audio tab per account. audio and select **Enable Audio** once. The GM can use **Enable GM audio** in the
playback controls after an automatic connection.
After a successful connection, the GM’s Foundry account remembers the encrypted The opted-in browser can reconnect on world entry. **Disconnect** ends its live
server address and receiver name. On another computer or after reload, enter the session and pauses automatic reconnection until you connect again.
same MA token and select **Connect** to unlock the saved address. Reload and **Forget Credentials** also removes the stored token. Reload without retention
**Disconnect** clear the in-memory token. If the token changes, enter the server requires the token again. The Foundry account remembers an encrypted address and
address with the replacement token. **Advanced → Forget saved connection** clears receiver name. On a different browser, use the same token to unlock the account
the account record. The receiver identity remains encrypted in its browser vault. 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 MA 2.10.6 assigns a restricted token’s API sessions to its most recently connected
origin. To update a legacy assignment, connect from the browser that originally web receiver. Use a different token for a simultaneously running native MA web
saved it and save the scene again. From a different browser, reselect its playlists. player. New MA playlist assignments are portable across browsers with the same
Keep the active GM browser open for live MA playback and listener forwarding. 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 Keep the GM tab open while serving audio. The setup window is independent of
when ready to resume scene control. Unknown mutation outcomes stop automation and playback. Automatic reattachment preserves a populated queue until the next
require review. Pause preserves a stopped queue’s index and position for the active scene or combat music cue. You can also select **Return to scene music** to take
GM session. 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 ## Connection diagnostics
@@ -54,6 +74,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. | | 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. | | 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. | | 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. | | 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`. Use trusted HTTPS for Foundry and private HTTPS/WSS for both MA `/ws` and `/sendspin`.
@@ -62,19 +83,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 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; address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
remote players still need a viable existing WebRTC path. 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 separately verified installed baseline is v0.8.0.
Unzip the complete release bundle on the development host and run these
commands as the Foundry data owner. Set the first two variables to the existing
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.1'
cd "$AM_RELEASE_DIR"
grep ' adaptive-music.zip$' SHA256SUMS | sha256sum -c -
test -d "$FOUNDRY_DEV_DATA/modules"
AM_STAGE=$(mktemp -d "$FOUNDRY_DEV_DATA/adaptive-music-v081.XXXXXX")
unzip -q adaptive-music.zip -d "$AM_STAGE"
test -f "$AM_STAGE/adaptive-music/module.json"
if [ -d "$FOUNDRY_DEV_DATA/modules/adaptive-music" ]; then
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.1**. Enable the module if needed, then sign in as
**CodexDEV** and follow the acceptance checklist. For rollback, shut down the
development instance, move the candidate module out of `Data/modules` and move
`previous-adaptive-music` from the printed rollback directory back to
`Data/modules/adaptive-music`.
## Manual Gitea publication ## Manual Gitea publication
The existing stable manifest and versioned download mechanism is preserved: The existing stable manifest and versioned download mechanism is preserved:
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json` - 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.1 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.1/adaptive-music.zip`
These are the established repository’s URLs; this work never contacted Gitea or These are the established repository’s URLs; this work never contacted Gitea or
verified public asset availability. After acceptance, manually publish the included 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.1`, attach
`adaptive-music.zip` and the included manifest/checksums, and update the branch `adaptive-music.zip` and the included manifest/checksums, and update the branch
manifest only after its versioned asset exists. The outer bundle includes full manifest only after its versioned asset exists. The outer bundle includes full
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
+119 -14
View File
@@ -1,10 +1,109 @@
# Adaptive Music progress — 0.7.2 staged acceptance # Adaptive Music progress — 0.8.1 combat and Firefox
Standalone module work now includes automatic campaign receiver provisioning and ## Installed v0.8.0 manual acceptance
account-bound pairing, remembered encrypted browser-local identity, memory-only token
retention/retry, scene assignments, listener bootstrap, guarded transitions and queue The operator confirmed on macOS that Chrome connected and retained credentials
restoration. Existing Gitea URLs/manual release mechanism are preserved. No Git host after a full quit and reopen. Automatic scene playlist activation, background-tab
was accessed and no production infrastructure/core versions were changed. audio, WAN player audio and smooth transitions passed. The operator reported
that stuttering and crackling were resolved in their testing. Firefox
connectivity failed. A follow-up confirmed the battle playlist played when
assigned to ambient, while tracked combat left ambient unchanged. The operator
could not find boss designation. The corrected combat workflow still awaits
operator acceptance.
## v0.8.1 combat correction
The installed v0.8.0 reproduction used the native token HUD and Combat Tracker
on Foundry 14.371 and D&D 5e 6.1.2. Start Combat committed round 1 and turn 0
for an unlinked encounter with a token in the active scene. The module required
an explicit encounter scene and kept its ambient queue. The correction considers
the unlinked encounter's combatant scenes and reconciles from the committed
lifecycle. The Combat Tracker now lets the GM mark a boss encounter and return
to automation. Both the tracker and Playback panel identify the current cue.
The Chromium candidate preview verified the native tracker workflow with three
distinct playlists. Turn and round changes kept the combat cue, canceled End
Combat kept the encounter running, and confirmed end restored ambient after
normal, boss, and manual-override encounters. The scene excursion preserved the
interrupted ambient position. The manual override was visible in the tracker and
released to Combat through **Return to automation**.
The headed Firefox preview repeated the normal tracker lifecycle and restored
ambient at 9 seconds. The installed macOS candidate awaits operator retesting.
## v0.8.1 status
The clean local v0.8.0 release commit was reconciled against the original
workspace and the installed runtime. The original Git metadata is read-only
and the operator's published commit `95b0427` is absent locally. Both local
trees had identical source before v0.8.1 work. The installed v0.8.0 manifest
and all 28 runtime files matched the local release baseline.
Stock Firefox 161.0.1 on Ubuntu opened both private WSS routes from the
anonymous Foundry page and the MA origin. The isolated policy fixture
distinguished enforced CSP and kept Origin and certificate failures opaque.
The v0.8.1 diagnostic candidate records route timing, permissions after
the probe and the failed Connect stage without copying arbitrary error text.
The source change is confined to the connection diagnostics and their UI.
The macOS failure remains open pending the
[Firefox capture](USER-ACCEPTANCE.md#capture-the-firefox-failure).
The v0.8.1 regressions passed 115 JavaScript and 17 Python tests, plus the
Chromium, Firefox and Linux WebKit setup fixtures. Repository and upstream
verification passed. npm audit reported zero vulnerabilities. The complete
diagnostic candidate bundle is staged locally under `dist/releases/v0.8.1/`.
## Historical v0.8.0 automated audit
The operator confirmed that installed v0.7.2 plays MA audio in Chrome on a Mac.
The v0.8.0 work uses that baseline and retains the dedicated receiver architecture.
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 ## Defects
@@ -12,11 +111,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-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-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-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-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 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 | | 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 |
| 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-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 | | 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 ## Technical findings
@@ -50,7 +152,10 @@ startup failed with MA `MediaNotFoundError` in both engines. The cause of those
failures remains unconfirmed. The controller preserves the failed command and skips 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`. 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 The earlier server-installed evidence is in `evidence/v0.7.0-foundry-private.json`.
remains pending Mac, physical-device, WAN and invitation-renewal checks in TESTING.md. The installed v0.8.0 manual results and remaining checklist are in
Crossfade, durable crash restoration, seamless handover and WAN synchronization [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md). See [TESTING.md](TESTING.md)
remain unsupported. 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.
+23 -23
View File
@@ -1,29 +1,29 @@
# Adaptive Music — 0.7.2 # Adaptive Music — 0.8.1 candidate
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
Foundry v14.371 and Music Assistant 2.10.6. System-independent; one Foundry module Foundry v14.371 and Music Assistant 2.10.6. The module runs independently of the game
ZIP, no other required module, container, VM/LXC or companion service. system and uses a single installable Foundry ZIP.
Enter your private HTTPS MA address and token in **Connection**, then select In **Connection**, enter your private HTTPS Music Assistant address and a revocable
**Connect**. Assign playlists in **Scene Music** and enable automation in Music Assistant token. On a trusted GM device, opt in to **Remember credentials and
**Playback**. Players receive WebRTC audio reconnect on this trusted device**. Assign ambient, combat and boss playlists in
automatically, with one Enable Audio click if their browser requires it. No receiver native **Scene Configuration**. Enable automation once. Open **Adaptive Music
identity export or JSON import is part of setup. 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 The active scene starts its assigned music. Starting an encounter in the Combat
MA token and select **Connect** to unlock it in a new browser session. MA tokens Tracker interrupts ambient and ending it restores the saved track and position.
stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity Check **Boss encounter** before starting to use the scene's default boss cue.
is encrypted in that browser’s IndexedDB so reconnecting does not create another The tracker and playback controls show Ambient, Combat, Boss or Manual Override.
receiver. Players receive individually encrypted invitations, not MA credentials. GMs can pause, resume,
Only that dedicated receiver and explicitly owned Foundry music playlists are skip, stop, set repeat, adjust volume, apply a manual playlist and return to scene music.
controlled. Household speakers, grouping, queue transfers, sound effects and Player audio connects automatically, with an **Enable Audio** click when required
AmbientSound documents are outside the control surface. by the browser.
The v0.7.1 browser preview passed the new graphical setup and playback workflow The GM browser hosts Music Assistant playback and player WebRTC connections. Keep
in a real Foundry v14.371 development world with two listeners. See TESTING.md that tab open. The encrypted device credential stays in the browser profile where
for the test scope and remaining installed-build checks. 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 for setup/manual publication, TESTING.md for the consolidated Mac See [INSTALL.md](INSTALL.md) for setup, [SECURITY.md](SECURITY.md) for credential
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status. scope, and [TESTING.md](TESTING.md) for measured behavior and remaining acceptance.
Crossfade, seamless GM handover, durable crash restore and WAN synchronization
claims are not implemented. Attribution and licenses remain in THIRD-PARTY-NOTICES.
+30 -23
View File
@@ -1,32 +1,35 @@
# Adaptive Music security — 0.7.2 # Adaptive Music security — 0.8.1
## Credentials and browser trust ## Credentials and browser trust
The MA access token remains in the trusted GM tab’s closure memory. It is excluded By default the MA access token remains in the GM tab’s memory. A GM can opt in
from Foundry settings, flags, sockets, URLs, console logging, IndexedDB serialization to an encrypted IndexedDB record for this trusted browser profile. A separate,
and release archives. Setup failures retain it in this tab; disconnect or reload non-extractable AES-GCM key and random nonce protect the record, which is bound to
forgets it. Tokens are never reused after an origin change. Use a restricted MA the Foundry origin, world and user. Use a dedicated, high-entropy, revocable token
account with only the intended music providers and dedicated receiver permissions. 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 Local encryption protects against casual inspection of plaintext storage. Same-origin
address and receiver name. The encryption key is derived from the user-entered MA scripts, enabled modules and the browser profile owner can use the retained key.
token for this account and world. Use a generated, high-entropy MA token. The The device credential does not travel to another browser with a Foundry login.
envelope cannot be unlocked after rotating that token. Connect with the explicit Use a separate browser profile for accounts that should never share local trust.
address and new token to replace it. Forget saved connection removes the envelope. 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 Foundry’s user-scoped address record still holds only a version, nonce and
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and ciphertext. It can be unlocked on another device with the same token. Rotating the
a non-extractable key stored in the same browser. It avoids plaintext receiver token requires entering the MA address again. MA catalog references created with
storage; it cannot protect against same-origin scripts, a compromised enabled the former token can need reassignment. Receiver private material has its own
module, the local profile owner or theft of a complete browser profile. Use separate encrypted browser record, paired to the dedicated target.
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.
Private development endpoints, tokens, identities, account/catalog results and Private development endpoints, tokens, identities, account/catalog results and
snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket snapshots remain under ignored .local/ (0700; secret files 0600). MA raw WebSocket
frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled; frames can include credentials at VERBOSE logging. Keep raw-frame logging disabled;
the module does not change production log settings. Expanded operator authorization the module does not change production log settings. Expanded operator authorization
covers the dedicated live development tests; no production infrastructure was changed. 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 ## 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` Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics 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. 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 Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
those causes. those causes.
@@ -49,17 +54,19 @@ sessions reject them. Browser authority cannot replace a distributed server fenc
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses. Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
Public ephemeral keys on permission-controlled User documents authenticate invitation 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 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 the installed development world. SDP is encrypted, bounded, replay protected and validated for a single audio
replay protected, and validated for one audio direction with media-level SDP direction with media-level inheritance. Expiry ends the signaling capability.
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP. 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 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. 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 ## Recovery and distribution
API/Sendspin loss stops automation and listener forwarding. Retained tab inputs API/Sendspin loss stops automation and listener forwarding. Retained tab inputs
support a deliberate reconnect; the owned queue is not replaced during reattachment. support deliberate reconnect. A trusted device can also reauthenticate after a
No blind mutation retry or automatic crash restoration is promised. Logical pause 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 and interruption snapshots do not survive a reload. Native fallback cannot silently
resolve an uncertain remote queue. resolve an uncertain remote queue.
+1 -1
View File
@@ -1 +1 @@
1ccdd229e40e1e02f0fa76d8fc553877c66c9494 1ed6b4c8ccd35e1187b83003379fe05d3cbeed8a
+175 -6
View File
@@ -1,9 +1,173 @@
# Adaptive Music verification — 0.7.2 # Adaptive Music verification — 0.8.1
## Executed evidence ## Executed evidence
The source archive includes sanitized evidence separately from private .local inputs. The source archive includes sanitized evidence separately from private .local inputs.
### Installed v0.8.0 manual macOS acceptance
The operator confirmed Chrome connectivity, retention after a full Chrome quit
and reopen, automatic scene playlist activation, background-tab audio, WAN
player audio and smooth transitions. Stuttering and crackling were resolved
during testing. Firefox connectivity failed. In the combat follow-up, the
operator reported that a battle playlist played when assigned to ambient,
while native combat use left the ambient cue playing. They could not find
the boss designation. The corrected combat flow and manual playback
controls still need operator acceptance.
### v0.8.1 native Combat Tracker investigation
Tested Foundry **14.371** and D&D 5e **6.1.2** in the authorized development
world. The baseline used installed v0.8.0 and the GM entered a token into
combat through its native HUD. The tracker created an active, unlinked
encounter with one combatant belonging to the active scene. On **Start Combat**,
`combatStart` arrived at round 0 with `started=false`. The subsequent
`updateCombat` and `combatTurnChange` reported round 1, turn 0 and
`started=true`. The baseline made no dedicated queue transition, reproducing
the failure without calling a module API or injecting encounter state.
Foundry v14's `Combat.scene` is optional in practice and its unlinked encounters
are visible across scenes. `Combatant.sceneId` identifies the token's scene.
D&D 5e's `Combat5e` at `75750bf1b8bd79f8448af40495c8bb5c99f49551`
delegates start, end and update/delete processing to Foundry core and adds
system-specific resource and token behavior. Adaptive Music uses
the committed document hooks and accepts explicit scene links or the token
scenes in an unlinked encounter. A turn or round change leaves the cue intact.
The Chromium package preview used three distinct playlists. A native token HUD
and native tracker controls verified adding combatants, rolling initiative,
starting an encounter, advancing turns and rounds, and canceling or confirming
End Combat. Neither preparation nor canceled End Combat changed the cue.
Confirmed End Combat restored the ordered ambient queue at track index 0 and
30 seconds. The **Boss encounter** checkbox selected the scene's default boss
cue on the next encounter. A scene excursion using Foundry's scene activation
operation played the other scene's ambient, then selected Boss on return.
Ending the boss restored the original ambient at 33 seconds. A manual silence
override displayed an explicit warning during the next encounter. **Return to
automation** selected Combat, and End Combat restored ambient at 46 seconds.
The test measured GM output and restored the development world afterward.
Headed Ubuntu Firefox 159 repeated the native token HUD, initiative, start,
turn and round, canceled end, and confirmed end checks against the same
candidate runtime. It measured GM output and restored ambient at index 0
and 9 seconds. Both candidate previews ran on Foundry 14.371 and D&D 5e 6.1.2
with server-installed metadata reporting v0.8.0.
[Foundry Combat Tracker guide](https://foundryvtt.com/article/combat/),
[combatStart hook](https://foundryvtt.com/api/v14/functions/hookEvents.combatStart.html),
[Combatant API](https://foundryvtt.com/api/v14/classes/foundry.documents.Combatant.html),
and [D&D 5e 6.1.2 Combat implementation](https://raw.githubusercontent.com/foundryvtt/dnd5e/75750bf1b8bd79f8448af40495c8bb5c99f49551/module/documents/combat.mjs).
### v0.8.1 Firefox transport investigation
The downloaded Mozilla Firefox 161.0.1 Linux archive matched Mozilla's SHA-512
listing. Real stock Firefox over the authorized private route opened native
`/ws` and `/sendspin` WebSockets with HTTP 101 from the anonymous Foundry
page and the MA origin. The test used a process-local mapping to the authorized
private proxy and normal certificate verification. No credentials were entered.
The MA page replaces its WebSocket constructor, so its control used the
native constructor retained before page script execution.
Separate live runs with stock Firefox 161.0.1 on Ubuntu also signed into the
development world, authenticated to MA and measured scene audio at the GM and
a second Foundry login. Those runs covered installed v0.8.0 and the earlier
diagnostics-only v0.8.1 browser preview.
Seven isolated stock-Firefox policy cases covered trusted cross-origin and
same-origin upgrades, enforced and report-only CSP, server-side Origin
rejection and a mismatched WSS certificate. Origin and TLS failures remained
opaque to page script. The permission API reported `prompt` even on a private
route that worked, so that reported state does not determine the cause.
Firefox's site-level local network permission and the macOS app-level permission
are separate. Record whether MA's normal HTTPS page works in the failing Firefox
profile. If it fails, verify the displayed error and compare the profile's
existing DNS and proxy settings. If MA loads, compare the two Foundry WSS routes
and look for local-network or CSP console messages. A reverse proxy's
timestamped path and response status can distinguish a received handshake
from a failure before it reached the proxy. The pinned MA 2.10.6 handlers
authenticate after upgrade. Ordinary HTTP CORS settings do not establish
authorization for a WebSocket Origin. Keep browser, TLS and proxy policy in place.
See [the Firefox capture instructions](USER-ACCEPTANCE.md#capture-the-firefox-failure),
[Mozilla local-network permissions](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [MDN's CSP connect-src reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/connect-src).
### v0.8.0 handoff checkpoint
The v0.8.0 browser preview reached the actual Foundry development world through
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 ### Account persistence and v0.7.0 GUI review
The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive
@@ -92,6 +256,10 @@ runs used dedicated MA development receivers exclusively.
## One consolidated Mac / logged-in-world acceptance ## 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 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. private HTTPS MA endpoint. It needs no developer console or diagnostic shell commands.
@@ -116,15 +284,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. 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 Reconnect the same owned receiver and confirm its queue is not replaced. Apply the
automation setting explicitly if a nonempty queue was retained. 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 brief network interruption, reconnect, and one background/suspend cycle. Report
failures with Copy connection diagnostics. Repeat on the actual WAN player route; failures with Copy connection diagnostics. Repeat on the actual WAN player route;
loopback/LAN signal does not establish NAT/TURN reachability or synchronization. loopback/LAN signal does not establish NAT/TURN reachability or synchronization.
The installed-world run covered real Foundry hooks, socket delivery and User The development-world runs covered real Foundry hooks, socket delivery and User
permissions. Public release acceptance still requires audibility on the actual permissions. The v0.8.0 preview verified continued playback through the
Mac/player devices, the original Mac connection, invitation renewal and WAN checks. signaling lifetime and listener reconnection. For v0.8.1, verify the exact
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp 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 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. and temporary VM-to-proxy access rollback are in ignored .local/PRIVATE-ROUTE-REQUEST.md.
+72
View File
@@ -0,0 +1,72 @@
# Adaptive Music Mac acceptance
## Installed v0.8.0 operator results
These results are user-confirmed manual testing on macOS. See
[TESTING.md](TESTING.md) for automated browser and development-world evidence.
| Result | Scope |
| --- | --- |
| Pass | Chrome connectivity, Chrome credentials after a full quit and reopen, automatic scene playlist activation, background-tab audio, remote player audio over WAN, and smooth transitions. The operator heard no stuttering or crackling during testing. |
| Fail | Firefox connectivity on macOS. The operator also reported that the assigned battle playlist played when used as ambient, while normal Combat Tracker use left the ambient cue playing. |
| Usability finding | The operator could not find a way to designate a boss. Their normal combat and default boss assignments used the same playlist. |
| Awaiting candidate retest | Combat start and end, ambient restoration, boss designation, and manual playback controls. |
## Capture the Firefox failure
1. Note the Firefox and macOS versions. In the same Firefox profile and network,
open the normal MA HTTPS page and record whether it loads or shows a
certificate or connection error.
2. Return to the Foundry world. Open **Adaptive Music setup → Connection** and
reproduce **Connect** once. Note the exact error and the time with timezone.
Run **Check browser connection**, then select **Copy connection diagnostics**.
3. If either route fails, record the Foundry site's local network permission
from Firefox's site permissions or **Settings → Privacy & Security →
Permissions → Local network devices**. Also record the Firefox entry under
**System Settings → Privacy & Security → Local Network** on macOS. Leave
these settings as they are for the initial capture.
4. If available, copy the relevant Web Console line for `/ws` or `/sendspin`
using **⌘⌥K**, especially a Local Network Access, CSP or certificate error.
Share the result privately with the copied module diagnostics. Omit tokens,
cookies, raw WebSocket frames and full network exports.
See [Mozilla’s Firefox local-network permission guide](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [Apple’s macOS Local Network settings guide](https://support.apple.com/guide/mac-help/mchla4f49138/mac).
## Candidate checklist
Run the relevant checks against the exact candidate being accepted. Use the
private development world and sign in as **CodexDEV**, with one GM browser
connected at a time. Use the same approved development MA token in both
browsers so the existing scene assignments resolve. Put on headphones and
record your browser and macOS versions.
Before starting a v0.8.1 run, confirm **Manage Modules** shows Adaptive Music
**0.8.1**. Use the [local ZIP install procedure](INSTALL.md#install-the-candidate-on-an-isolated-development-instance).
Only use the dedicated development receiver.
| Check | Action | Expected result |
| --- | --- | --- |
| ☐ 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. |
| ☐ Player audio | Join as an ordinary development player in a separate profile. Open **Campaign audio** and select **Enable Audio** if prompted. Try **Stop Audio**, **Enable Audio** and one player reload. | The listener hears the GM's cue and audio returns after re-enabling and reloading. |
| ☐ Continuity | Listen on GM and player output through steady playback, cue changes and at least one track boundary. Cover each Foundry tab with another tab for at least one minute. Include one 30-minute play session and a Mac sleep/wake test across the two browsers. | Steady audio has no audible pops, crackle or unexpected gaps. Cue changes use a short sequential fade. Track/position continue while the tab is hidden. Record what happens during and after sleep. |
| ☐ Restart and reconnect | Quit the browser fully, reopen the same profile and return to the development world. With a working session, briefly drop and restore the test device's network. | The remembered receiver reconnects without token entry. A populated queue is preserved on attachment. Select **Return to scene music** to resume scene cues immediately if needed. |
| ☐ Disconnect and forget | Click **Disconnect**, restart the browser and verify it stays disconnected. Reconnect intentionally, click **Forget Credentials**, then restart again. | Disconnect pauses automatic reconnect. Forgetting removes the stored device token. The next connection requires token entry. |
| ☐ MA revocation | If testing revocation, use a disposable development token. At the end of that test, revoke only that token in MA Profile and retry from the same browser. | The revoked token cannot authenticate and the setup reports auth denial. Re-enter the approved token and private address before using the prepared scenes again. |
If a check fails, record local time with timezone, the browser and OS version,
the scene and cue, and whether the GM, a player or both were affected. For an
audio artifact, note the track position, duration and whether the tab was
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
+688
View File
@@ -0,0 +1,688 @@
{
"version": "0.8.1",
"scope": "Firefox diagnostics and native Combat Tracker candidate. Private development-world package previews, transport checks and browser fixtures.",
"publicationReady": false,
"serverInstalledExactVersion": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"macFirefoxRootCauseConfirmed": false,
"operatorAcceptanceV080": {
"source": "Operator-reported manual acceptance on installed Adaptive Music v0.8.0 on macOS",
"installedVersion": "0.8.0",
"passed": [
"Chrome connectivity",
"No stuttering or crackling during testing",
"Chrome credential retention after full quit and reopen",
"Automatic scene playlist activation",
"Background-tab audio continuity",
"Remote player audio over WAN",
"Smooth music transitions"
],
"failed": [
"Firefox connectivity on macOS"
],
"notTested": [
"Automatic combat music",
"Ambient restoration",
"Boss music",
"Manual playback controls"
],
"combatFollowUp": {
"scope": "Operator follow-up from their actual Foundry scene",
"ambientPlayback": "pass",
"battlePlaylistPlayableWhenAssignedToAmbient": true,
"combatCueSwitch": "fail: ambient continued",
"bossDesignationDiscoverability": "fail",
"combatAndBossUsedSamePlaylist": true,
"candidateManualRetest": "pending"
}
},
"localHistory": {
"originalHead": "987122ffee17ddbdb6266a12d4d8beb29903b838",
"localV080Release": "1ed6b4c8ccd35e1187b83003379fe05d3cbeed8a",
"v080SourceFilesIdentical": 157,
"reportedPublishedCommit": "95b0427",
"publishedObjectAvailableLocally": false,
"v081Branch": "v0.8.1-firefox"
},
"installedBaselineComparison": {
"scope": "anonymous exact-path read of installed Foundry module files over trusted private HTTPS",
"manifestStatus": 200,
"installedVersion": "0.8.0",
"runtimeFilesCompared": 28,
"runtimeFilesIdentical": 28,
"runtimeMismatches": []
},
"stockFirefox": {
"version": "161.0.1",
"platform": "Linux x86-64",
"archiveSha512": "9ef6ccc1b0e4376980ab88a49408924e75d3cafca248becfb8893424c6f025a58d715bf05f1f5397a4a997059de4c054a3e6490a140bdf4dc8795ec78b26e02a",
"download": "https://archive.mozilla.org/pub/firefox/releases/161.0.1/linux-x86_64/en-US/firefox-161.0.1.tar.xz",
"archiveVerifiedAgainstMozillaSha512Listing": true,
"privateRoute": {
"scope": "official Mozilla Firefox on Ubuntu, anonymous private Foundry and MA HTTPS pages, fixed unauthenticated WSS routes",
"browser": "161.0.1",
"tlsValidation": true,
"checks": {
"foundryOrigin": {
"status": 200,
"cspHeaderPresent": false,
"reportOnlyHeaderPresent": false,
"secureContext": true,
"cspMetaPresent": false,
"replaced": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 9,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
},
"maOrigin": {
"secureContext": true,
"cspMetaPresent": false,
"replaced": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 195,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
}
},
"completed": true
},
"isolatedPolicyChecks": {
"scope": "isolated real Firefox HTTPS/WSS policy tests; local transport server, no MA, no Foundry, no credentials or audio",
"browser": "161.0.1",
"mozillaStockBuild": true,
"tls": "local CA trusted in disposable Firefox profile; no certificate bypass",
"checks": [
{
"name": "Trusted HTTPS cross-origin WSS allowed",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 11,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Enforced CSP blocks cross-origin before upgrade",
"results": [
{
"path": "/ws",
"code": "csp-blocked",
"elapsedMs": 1,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "csp-blocked",
"elapsedMs": 0,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same MA origin control",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Report-only CSP does not block",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Server Origin rejection stays opaque",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 31,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same origin still succeeds under Origin restriction",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 2,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Mismatched WSS certificate stays opaque and connection closed",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 28,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
}
],
"passed": true
}
},
"offlineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
],
"regression": {
"javascriptPassed": 115,
"javascriptFailed": 0,
"pythonPassed": 17,
"pythonFailed": 0,
"repositoryPrivacyAndAttribution": "pass",
"upstreamProvenance": "pass",
"npmAuditReportedVulnerabilities": 0
},
"remainingAcceptance": [
"Capture the failure on the operator Mac and identify its WebSocket or subsequent setup stage",
"Verify the exact server-installed v0.8.1 candidate in the affected Firefox profile and the working Chrome profile",
"Retest the corrected combat, ambient restoration, boss designation and manual playback controls on the operator Mac"
],
"combatTrackerAcceptance": {
"scope": "Authorized private development world; the candidate ZIP supplied runtime assets to the browser",
"dnd5eReviewedCommit": "75750bf1b8bd79f8448af40495c8bb5c99f49551",
"installedV080Reproduction": {
"at": "2026-12-05T18:15:47.932Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"cleanup": true,
"nativeHudAndStartCombat": true,
"encounter": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1
},
"ambientQueueChanged": false,
"lifecycle": [
{
"event": "createCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 0,
"participantsInActiveScene": 0,
"updateKeys": []
},
{
"event": "createCombatant",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1
},
{
"event": "combatStart",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "updateCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "combatTurnChange",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
}
]
},
"candidateNormalEncounter": {
"at": "2026-12-05T18:20:56.093Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.04104
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 30
},
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.0348
}
},
"harnessResult": "Normal encounter checks passed. The first scene-navigation locator timed out and the focused follow-up exercised the scene edge cases.",
"postCommitEvents": [
"combatRound",
"combatStart",
"combatTurn",
"combatTurnChange",
"createCombat",
"createCombatant",
"deleteCombat",
"updateCombat",
"updateCombatant"
]
},
"candidateBossSceneAndOverride": {
"at": "2026-12-05T18:29:02.740Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.11936
},
"sceneExcursionDuringCombat": {
"passed": true,
"outwardMethod": "native-scene-activation",
"returnMethod": "native-scene-activation"
},
"bossRestoration": {
"index": 0,
"seconds": 33
},
"manualOverrideAndTrackerReturn": true,
"repeatedRestoration": {
"index": 0,
"seconds": 46
}
},
"onlyDedicatedQueueWritten": true
},
"candidateFirefox": {
"completed": true,
"at": "2026-12-05T18:32:54.490Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.03617
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 9
}
}
}
},
"combatCandidateOfflineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
]
}
+2 -2
View File
@@ -2,7 +2,7 @@
"id": "adaptive-music", "id": "adaptive-music",
"title": "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.", "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.0",
"authors": [ "authors": [
{ {
"name": "CheddahBoxMB" "name": "CheddahBoxMB"
@@ -24,5 +24,5 @@
"socket": true, "socket": true,
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music", "url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json", "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.0/adaptive-music.zip"
} }
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "adaptive-music", "name": "adaptive-music",
"version": "0.5.0", "version": "0.8.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "adaptive-music", "name": "adaptive-music",
"version": "0.5.0", "version": "0.8.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@sendspin/sendspin-js": "5.0.0" "@sendspin/sendspin-js": "5.0.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "adaptive-music", "name": "adaptive-music",
"version": "0.5.0", "version": "0.8.0",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "MIT", "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. // Browser interoperability checks for encrypted signaling and audio-only SDP.
import {createServer} from 'node:http'; 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'; 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 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();}}); 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=[]; await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const reports=[];
try{ try{
for(const [name,type]of [['firefox',firefox],['chromium',chromium]]){ for(const name of engines){
const browser=await type.launch({headless:true,...(name==='chromium'?{args:['--no-sandbox']}: {})}); const browser=await playwright[name].launch({headless:!process.argv.includes('--headed'),...(name==='chromium'?{args:['--no-sandbox']}: {})});
let pages=[],stage='browser-setup';
try{ 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); 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;}); 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); 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)};}); 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++){ 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].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); },i===0);
await pages[0].waitForFunction(()=>window.peer.diagnostics().peers[0]?.connection==='connected',{},{timeout:8000}).catch(()=>{}); 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 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()))); 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();} }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));} }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. // 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 {lookup} from 'node:dns/promises';
import {isIP} from 'node:net'; import {isIP} from 'node:net';
import {resolve} from 'node:path'; 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 report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
const playback = process.argv.includes('--playback'); 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 loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium'; const engine = process.argv.includes('--firefox')?'firefox':process.argv.includes('--webkit')?'webkit':'chromium';
const previewModule = process.argv.includes('--preview-module'); 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); }; const expect = (ok, code) => { if (!ok) throw new Error(code); };
async function privateJSON(name) { 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) { 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'); 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) { if (previewModule) {
const prefix='/modules/adaptive-music/'; 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=>{ await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
const file=new URL(route.request().url()).pathname.slice(prefix.length); 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'}); await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
}); });
} }
page.setDefaultTimeout(20000); 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); await retainBrowserWebSocket(page);
if (playback) await page.addInitScript(() => { 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 peers = [];
const contexts = []; const contexts = [];
const analysers = []; const analysers = [];
@@ -140,9 +172,26 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
return destination; return destination;
}; };
const createAnalyser = AudioContext.prototype.createAnalyser; 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 () { AudioContext.prototype.createAnalyser = function () {
const analyser = createAnalyser.call(this); const analyser = createAnalyser.call(this);
analysers.push(analyser); 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; return analyser;
}; };
const createSource = AudioContext.prototype.createMediaStreamSource; 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 source = createSource.call(this, stream);
const analyser = createAnalyser.call(this); const analyser = createAnalyser.call(this);
source.connect(analyser); source.connect(analyser);
listenerAnalysers.push({context: this, stream, analyser}); const report={context: this, stream, analyser};
listenerAnalysers.push(report);
measure(this,analyser,report);
return source; return source;
}; };
window.__adaptiveMusicTestPeers = peers; 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.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
expect(state.adaptiveMusicActive, 'adaptive-music-inactive'); expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
// Keep the unattended canvases from saturating the shared headless renderer. // 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; const ticker = globalThis.canvas?.app?.ticker;
if (!ticker?.started) return false; if (!ticker?.started) return false;
ticker.stop(); ticker.stop();
@@ -214,24 +265,38 @@ async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password},
let browser, stage = 'configuration'; let browser, stage = 'configuration';
try { 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 config = await privateJSON('live-environment');
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma); const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
const proxyIP = config.proxy_ip; const proxyIP = config.proxy_ip;
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route'); expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright'); const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
stage = 'browser-launch'; stage = 'browser-launch';
if (engine === 'firefox') { if (engine !== 'chromium') {
for (const host of [foundry.hostname, ma.hostname]) { for (const host of [foundry.hostname, ma.hostname]) {
const answers = await lookup(host, {all: true}); const answers = await lookup(host, {all: true});
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required'); 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}`]} : `--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.engine = engine;
report.browser = browser.version(); 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]])) { for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
stage = name; stage = name;
@@ -265,24 +330,28 @@ try {
} }
if(layoutOnly){ if(layoutOnly){
stage='foundry-graphical-layout'; stage='foundry-graphical-layout';
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs'); const {checkFoundryLayout,checkNativeSceneSheet}=await import('./live_foundry_playback.mjs');
report.layout=await checkFoundryLayout(pages[0],ma); if(nativeSheet)await checkNativeSceneSheet(pages[0],report);
else report.layout=await checkFoundryLayout(pages[0],ma);
} }
if (playback) { if (playback) {
stage = 'installed-world-playback'; stage = 'development-world-playback';
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs'); const {checkFoundryPlayback,checkFoundryV080Review} = await import('./live_foundry_playback.mjs');
report.playback = {}; 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; report.completed = true;
} catch (error) { } catch (error) {
if(error.name==='SyntaxError')console.error(error.stack);
report.completed = false; report.completed = false;
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name}; report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
process.exitCode = 1; process.exitCode = 1;
} finally { } finally {
await browser?.close(); 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}); await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
console.log(JSON.stringify(report, null, 2)); 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();}
}
+52 -8
View File
@@ -1,14 +1,27 @@
// Offline Chromium UI fixture. No Foundry, MA, Git host, token or production access. // Offline Chromium UI fixture. No Foundry, MA, Git host, token or production access.
import {createServer} from 'node:http'; 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 {resolve,extname} from 'node:path';
import {chromium} from 'playwright';
import assert from 'node:assert/strict'; 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 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; await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));let browser;
try{ 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); 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); assert.equal(await page.getByText('Connect optional companion',{exact:true}).count(),0);
for(const width of [380,640,1000]){ 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.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'); 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 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(),''); 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(); await page.getByRole('button',{name:'Choose scene music',exact:true}).click();
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})}); 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(); 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,13 @@ try{
await page.getByText('2 connected listeners',{exact:true}).waitFor(); 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.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('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'); await page.getByLabel('Campaign volume').press('ArrowLeft');
assert.equal(await page.getByLabel('Campaign volume').inputValue(),'99'); 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(); 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']); assert.deepEqual(await page.evaluate(()=>window.controlActions),['pause','resume','seek','repeat','stop']);
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-setup.png'),fullPage:true}); if(engine==='chromium'){await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-setup.png'),fullPage:true});}
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]); 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)); console.log(JSON.stringify({status:'pass',engine,browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','three setup tabs','failed connection diagnostics exclude secrets and clear after retry','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','sidebar catalog refresh and pointer drag','track and listeners','pause/resume/seek/repeat/volume/stop','listener activation'],pageErrors:errors},null,2));
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));} }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 {randomUUID} from 'node:crypto';
import {setTimeout as delay} from 'node:timers/promises'; import {setTimeout as delay} from 'node:timers/promises';
import {loadMAToken} from '../gateway/private-config.mjs'; 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 === '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 === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
if (entry.command === 'player_queues/get' && frame.result) { if (entry.command === 'player_queues/get' && frame.result) {
const {state, current_index, elapsed_time} = frame.result; const {state, current_index, elapsed_time, ended, repeat_mode} = frame.result;
entry.queue = {state, index: current_index, position: elapsed_time}; entry.queue = {state, index: current_index, position: elapsed_time, ended, repeat:repeat_mode};
} }
}); });
}); });
@@ -89,6 +89,7 @@ async function gmAudioDiagnostics(page, setup) {
return { return {
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames, stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead, 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, signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value), volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
}; };
@@ -105,7 +106,7 @@ async function openMenu(page, name) {
}, `${moduleId}.${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){ export async function checkFoundryLayout(page,ma){
await openMenu(page,'setup'); 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}; 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 [gm, ...players] = pages;
const run = randomUUID().slice(0, 8); const run = randomUUID().slice(0, 8);
const receiverName = `Adaptive Music integration ${run}`; const receiverName = `Adaptive Music integration ${run}`;
const fixtureName = `Adaptive Music verification ${run}`; const fixtureName = `Adaptive Music verification ${run}`;
const setup = gm.locator('#adaptive-music-setup'); const setup = gm.locator('#adaptive-music-setup');
const wire = observeMA(gm, ma); 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 => { const stage = name => {
report.stage = name; report.stage = name;
console.error(`Installed-world playback stage: ${name}`); console.error(`Development-world playback stage: ${name}`);
}; };
let baseline, sceneId, combatId, receiver; let baseline, sceneId, combatId, receiver;
@@ -193,7 +261,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
game.modules.get(moduleId).api.stopDevelopment(); game.modules.get(moduleId).api.stopDevelopment();
await game.settings.set(moduleId, 'enabled', false); await game.settings.set(moduleId, 'enabled', false);
} }
return {enabled, scene}; return {enabled, scene, connection:game.settings.get(moduleId,'savedConnection')};
} }
if (data.action === 'cleanup') { if (data.action === 'cleanup') {
const api = game.modules.get(moduleId).api; 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.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 (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); 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)) && return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
game.settings.get(moduleId, 'enabled') === data.baseline.enabled; game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
} }
@@ -260,16 +329,19 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
stage('user-document-permissions'); stage('user-document-permissions');
const gmId = await gm.evaluate(() => game.user.id); const gmId = await gm.evaluate(() => game.user.id);
const probeFlag = `integrationProbe${run}`; 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; } try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
catch { return true; } 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}); 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'); stage('create-test-scene');
baseline = await fixture({action: 'baseline'}); baseline = await fixture({action: 'baseline'});
sceneId = await fixture({action: 'scene', fixtureName}); sceneId = await fixture({action: 'scene', fixtureName});
await fixture({action: 'activate-scene', sceneId}); await fixture({action: 'activate-scene', sceneId});
await gm.waitForFunction(id=>game.scenes.active?.id===id,sceneId,{polling:100});
await openMenu(gm, 'setup'); await openMenu(gm, 'setup');
await gm.evaluate(()=>{ await gm.evaluate(()=>{
window.__adaptiveTestNotifications=[]; window.__adaptiveTestNotifications=[];
@@ -297,7 +369,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
await setup.getByText('Advanced',{exact:true}).click(); await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local')); await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByRole('button',{name:'Connect',exact:true}).click(); 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; receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
check(receiver,'receiver-identity-not-verified'); check(receiver,'receiver-identity-not-verified');
report.oneClickConnection=true; report.oneClickConnection=true;
@@ -322,6 +394,7 @@ export async function checkFoundryPlayback({pages, ma, world, report}) {
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed'); check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
stage('scene-assignments'); 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 assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
const ambient = assignments.getByLabel('Ambient playlist'); const ambient = assignments.getByLabel('Ambient playlist');
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",'))); 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 ambient.selectOption(references[0]);
await assignments.getByLabel('Combat playlist').selectOption(references[1]); await assignments.getByLabel('Combat playlist').selectOption(references[1]);
if(tabbed)await assignments.getByLabel('Default boss music').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.getByRole('button', {name: 'Save assignments', exact: true}).click();
await assignments.getByText('Assignments saved.', {exact: true}).waitFor(); await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{ 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'); const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
report.ambient = await audio(); report.ambient = await audio();
await delay(6500); 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'); stage('actual-combat');
combatId = await fixture({action: 'combat', sceneId, fixtureName}); 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'); check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
await delay(4500); await delay(4500);
report.combat = await audio(); 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'); stage('ambient-restoration');
const restore = wire.commands.length; 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); snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
await delay(4500); await delay(4500);
report.restoredAmbient = await audio(); 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); 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'); 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.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
report.sendspinAuthenticated = wire.sendspinAuthenticated(); report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null); 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={ if(report.stage!=='passed')report.playbackFailureDetails={
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]), notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})), 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 diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {}; const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
return { return {
timeline: window.__adaptiveMusicTestTimeline,
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null, decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
signaling: window.__adaptiveMusicTestSignaling, 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 => { analyserRMS: analysers.map(analyser => {
const samples = new Float32Array(analyser.fftSize); const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples); 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); 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 hashlib
import ipaddress import ipaddress
import json import json
from pathlib import Path from pathlib import Path, PurePosixPath
import re import re
import stat
import subprocess import subprocess
import sys import sys
import urllib.parse import urllib.parse
@@ -13,6 +14,8 @@ import zipfile
ROOT=Path(__file__).resolve().parents[1] ROOT=Path(__file__).resolve().parents[1]
DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music' DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music'
ZIP_TIME=(2000,1,1,0,0,0) 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')) if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts'))
def public_url(value): def public_url(value):
@@ -85,14 +88,20 @@ def validate_package(path,manifest=None):
from audit_repository import findings from audit_repository import findings
with zipfile.ZipFile(path) as archive: with zipfile.ZipFile(path) as archive:
names=archive.namelist() 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) actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual)
if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch') if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch')
for name in names: for name in names:
data=archive.read(name);problems=findings(name,data.decode(errors='replace')) data=archive.read(name);problems=findings(name,data.decode(errors='replace'))
if problems:raise ValueError('private content in release: '+name) if problems:raise ValueError('private content in release: '+name)
if name.endswith('.mjs'): 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 import posixpath
for relative in relative_imports: for relative in relative_imports:
resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative)) 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',[]): for asset in actual['esmodules']+actual.get('styles',[]):
if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset') if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset')
provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json')) 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') 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'] 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') if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license')
return actual 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(): def local_revision():
try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip() try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError,FileNotFoundError): except (subprocess.CalledProcessError,FileNotFoundError):
file=ROOT/'SOURCE_REVISION.txt' file=ROOT/'SOURCE_REVISION.txt'
return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)' 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): def source_entries(manifest):
from audit_repository import findings 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') 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): 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'): 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') 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={} entries={}
@@ -135,7 +170,8 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
output=Path(output).resolve() 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/') 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) 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' evidence_name=f'evidence/v{version}-live.json'
if (ROOT/evidence_name).is_file():allowed.add(evidence_name) 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()) 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: if evidence is not None:
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True) (output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
(output/evidence_name).write_bytes(evidence) (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('*'): 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()) 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'], 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 {} 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['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') 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') (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-')} 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()))) (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 return bundle
if __name__=='__main__': 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') 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)) else:print(build_release(args.repository,args.version,args.output))
+1 -1
View File
@@ -42,7 +42,7 @@ export class AutoListeners {
try{ try{
const {iv,cipher,...header}=packet; 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)); 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||!gm.active||!gm.isGM||gm.isBanned||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
const invite=JSON.parse(new TextDecoder().decode(plain)); 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'); 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); this.#received.add(packet.id);await this.#onInvite(invite);
+51 -22
View File
@@ -1,3 +1,4 @@
import {PcmTimeline} from './pcm-timeline.mjs';
import {MusicError} from '../core/controller.mjs'; import {MusicError} from '../core/controller.mjs';
import {MAReadClient} from '../providers/ma/client.mjs'; import {MAReadClient} from '../providers/ma/client.mjs';
import {MAPlaybackProvider} from '../providers/ma/provider.mjs'; import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
@@ -11,10 +12,16 @@ export function gmAccessPolicy(baseUrl,pageUrl){
return target; return target;
} }
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[k];}};} 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{ 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; #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=()=>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;} 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',scheduledFrames:this.#scheduled,droppedLate:this.#late,droppedAhead:this.#ahead,lastLeadSeconds:this.#lastLead,audioTime:this.#context?.currentTime,lastError:this.#lastError};} 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 catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;} get session(){return this.#session;}
get stream(){return this.#destination?.stream;} get stream(){return this.#destination?.stream;}
@@ -81,9 +88,9 @@ export class GMAudioHost{
const base=gmAccessPolicy(profile.maUrl,this.pageUrl); 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'); 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');}; 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{ 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); const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch'); if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
if(!globalThis.navigator?.locks)throw new MusicError('unsupported'); if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
@@ -93,8 +100,8 @@ 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')}); 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(); await this.#apiTransport.connect();check();
this.#phase='Sendspin authentication';this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);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.#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.#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.#transitionGain=this.#context.createGain();this.#gain=this.#context.createGain();this.#transitionGain.connect(this.#gain);this.#timeline=new PcmTimeline(this.#context,this.#transitionGain);this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);}
this.#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.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.onAudioData=chunk=>this.#schedule(chunk);
this.#core.onConnectionClose=()=>this.#connectionLost(epoch,'Sendspin connection lost'); this.#core.onConnectionClose=()=>this.#connectionLost(epoch,'Sendspin connection lost');
@@ -142,29 +149,51 @@ 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; 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; 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;} 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; const start=this.#timeline.push(chunk,this.#core.getCurrentServerTimeUs());
this.#lastLead=lead;if(!Number.isFinite(lead)||this.#nodes.size>=512||this.#bufferedBytes+frames*chunk.samples.length*4>2097152)return; if(start!==false&&this.#fadeNext&&!this.#transitioning){
if(lead>6){this.#ahead++;return;}if(lead+frames/chunk.sampleRate<0){this.#late++;return;} this.#fadeNext=false;
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples)); const gain=this.#transitionGain.gain;
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++; gain.setValueAtTime(0,start);
gain.linearRampToValueAtTime(1,start+0.35);
}
} }
#clear(fromTimestampUs){ #clear(fromTimestampUs){
if(Number.isFinite(fromTimestampUs)){ this.#timeline?.clear(fromTimestampUs);
const when=Math.max(this.#context.currentTime,this.#context.currentTime+(fromTimestampUs-this.#core.getCurrentServerTimeUs())/1000000); if(!Number.isFinite(fromTimestampUs)&&this.#transitioning)this.#fadeNext=true;
for(const node of this.#nodes)if(node.adaptiveServerEnd>fromTimestampUs){try{node.stop(node.adaptiveServerStart>=fromTimestampUs?0:when);}catch{}} }
return; 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;} #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);} resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
snapshot(ctx){return this.#ready().snapshot(ctx);} snapshot(ctx){return this.#observe(()=>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;}} 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));} apply(prepared,ctx){return this.#observe(()=>this.#ready().apply(prepared,ctx));}
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,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));} 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));} 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();} async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;this.#meter=null;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
} }
+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'); 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 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}; 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.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.ondatachannel=event=>event.channel.close();
pc.onconnectionstatechange=()=>{ 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 #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){ async #receive(frame){
const entry=this.#peers.get(frame?.peer);if(!entry||frame.session!==entry.invite.session)return; 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()=>{ 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'); 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(payload.type==='bye'){this.revoke(frame.peer);return;}
if(entry.role==='gm'&&payload.type==='offer'){ if(entry.role==='gm'&&payload.type==='offer'){
// The listener's SDP is recvonly: reject video, data, injected outbound audio. // 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;} 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}); 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); 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}); entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
}else if(entry.role==='listener'&&payload.type==='answer'){ }else if(entry.role==='listener'&&payload.type==='answer'){
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp}); 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);} 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);} 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}))};} 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;}
} }
+56 -19
View File
@@ -2,22 +2,35 @@
export class MusicError extends Error { export class MusicError extends Error {
constructor(code) { super(code); this.code = code; } 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) { export function candidates(state) {
const scene = state.scene; 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) 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)); .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
const make = (key, playlist) => ({ key, playlist: playlist ?? null });
return [ return [
...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)), ...(state.overrides ?? []).slice().reverse().map(o => intent(`manual:${o.id}`, 'manual', o.playlist)),
...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)), ...bosses.map(b => intent(`boss:${scene.id}:${b.id}`, 'boss', b.playlist)),
...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id)) ...combats.filter(c => c.bossPlaylist).map(c => intent(`boss-encounter:${scene.id}:${c.id}`, 'boss', c.bossPlaylist)),
.map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)), ...combats.filter(c => c.playlist).map(c => intent(`combat:${scene.id}:${c.id}`, 'combat', c.playlist)),
...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []), ...(scene?.playlist ? [ambientIntent(scene)] : []),
make('default', state.defaultPlaylist) intent('default', state.defaultPlaylist ? 'ambient' : 'silence', state.defaultPlaylist)
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` })); ];
} }
const samePlaylist = (a, b) => Boolean(a && b && a.provider === b.provider && a.id === b.id);
export class MusicController { export class MusicController {
#pending;
#stateSignature;
constructor({ campaign, session, providers, authority, maxFrames = 16 }) { constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
Object.assign(this, { campaign, session, providers, authority, maxFrames }); Object.assign(this, { campaign, session, providers, authority, maxFrames });
this.dirty = new Set(); this.dirty = new Set();
@@ -25,19 +38,33 @@ export class MusicController {
} }
update(state) { update(state) {
const input = structuredClone(state); 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(); 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) { control(action, value) {
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) { if (!['pause', 'resume', 'stop', 'seek', 'next', 'repeat'].includes(action) || !this.providers.ma?.control) {
return Promise.reject(new MusicError('unsupported')); return Promise.reject(new MusicError('unsupported'));
} }
const expected = this.generation; const expected = this.generation;
return this.#enqueue(() => { return this.#enqueue(async () => {
if (expected !== this.generation) throw new MusicError('stale'); if (expected !== this.generation) throw new MusicError('stale');
const context = this.#nextContext(); const context = this.#nextContext();
context.check(); 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);}
}); });
} }
cancel() { cancel() {
@@ -59,9 +86,14 @@ export class MusicController {
async transition(state, ctx) { async transition(state, ctx) {
ctx.check(); ctx.check();
const choices = candidates(state), next = choices[0]; 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)); this.frames = this.frames.filter(f => valid.has(f.intent.key));
if (this.current?.key === next.key) return { unchanged: true }; 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]; const provider = next.playlist && this.providers[next.playlist.provider];
if (next.playlist && !provider) throw new MusicError('unsupported'); if (next.playlist && !provider) throw new MusicError('unsupported');
const prepared = provider ? await provider.resolve(next.playlist, ctx) : null; const prepared = provider ? await provider.resolve(next.playlist, ctx) : null;
@@ -70,14 +102,17 @@ export class MusicController {
const snapshot = outgoing ? await outgoing.snapshot(ctx) : null; const snapshot = outgoing ? await outgoing.snapshot(ctx) : null;
ctx.check(); ctx.check();
const frame = this.frames.findLast(f => f.intent.key === next.key); const frame = this.frames.findLast(f => f.intent.key === next.key);
if (old && snapshot && valid.has(old.key)) { if (old && snapshot) {
this.frames = this.frames.filter(f => f.intent.key !== old.key); const shared = choices.filter(intent => samePlaylist(intent.playlist, old.playlist));
this.frames.push({ intent: old, snapshot }); 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); this.frames = this.frames.slice(-this.maxFrames);
} }
const cleanup = new Set([...this.dirty, outgoing].filter(Boolean)); const cleanup = new Set([...this.dirty, outgoing].filter(Boolean));
for (const p of [outgoing, provider]) if (p) this.dirty.add(p); for (const p of [outgoing, provider]) if (p) this.dirty.add(p);
try { try {
await outgoing?.fade?.(false,ctx);
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); } for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
ctx.check(); ctx.check();
if (provider) { if (provider) {
@@ -88,15 +123,17 @@ export class MusicController {
} catch (error) { } catch (error) {
// Stale or uncertain writes require explicit reconciliation. // Stale or uncertain writes require explicit reconciliation.
this.current = null; this.current = null;
if (error.code !== 'stale' && error.code !== 'uncertain') { if (!['stale','uncertain','receiver-access-lost'].includes(error.code)) {
ctx.check(); ctx.check();
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); } 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(); await outgoing.restore(snapshot, ctx); this.current = old; }
this.dirty.clear(); this.dirty.clear();
} }
throw error; throw error;
} finally {
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.dirty.clear();
this.current = next; this.current = next;
return { intent: next, restored: Boolean(frame) }; return { intent: next, restored: Boolean(frame) };
+13 -4
View File
@@ -1,6 +1,9 @@
import { MusicError } from './controller.mjs'; import { MusicError } from './controller.mjs';
export const musicFields = ['ambient','combat','boss','fallback']; export const musicFields = ['ambient','combat','boss','fallback'];
export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : ''; 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}={}) { export function selection(value, choices, {nativeOnly=false}={}) {
if(value==='')return null; 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); 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. // Single music layer: ambient is the base queue interrupted by combat/boss/manual.
// These assignments do not address Foundry AmbientSound or sound effects. // 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 config = scene?.music ?? {};
const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null;
const fallback = config.fallback ?? defaults.fallback ?? null; const fallback = config.fallback ?? defaults.fallback ?? null;
const selected=ref=>ref ? choose(ref,fallback) : null; const ambient = (Object.hasOwn(config,'ambient') ? config.ambient : config.playlist) ?? defaults.ambient;
return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(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)})), overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})),
combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat), 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)}))}))}; bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))};
} }
+124 -8
View File
@@ -1,4 +1,5 @@
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 { MusicError } from '../core/controller.mjs';
const namespace = 'adaptive-music'; const namespace = 'adaptive-music';
const key = ref => JSON.stringify([ref?.provider, ref?.id]); const key = ref => JSON.stringify([ref?.provider, ref?.id]);
@@ -16,9 +17,9 @@ export async function savePlaylistConfiguration({ document, game, choices, selec
await document.setFlag(namespace, 'music', { ...previous, await document.setFlag(namespace, 'music', { ...previous,
playlist: choice ? { provider: choice.provider, id: choice.id } : null }); 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 (!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 dom = container.ownerDocument;
const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration'; const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration';
const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend); const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend);
@@ -31,7 +32,7 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
const current = document.getFlag(namespace, 'music')?.playlist; const current = document.getFlag(namespace, 'music')?.playlist;
if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable'); if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable');
select.value = current ? key(current) : ''; 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 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); const save = dom.createElement('button'); save.type = 'button'; save.textContent = 'Save music playlist'; panel.append(save);
let saving = false; let saving = false;
@@ -47,21 +48,136 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
container.append(panel); return panel; container.append(panel); return panel;
} }
// Explicit development-only UI bootstrap. Importing this file registers nothing. // 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; let disposed = false;
const panels = new Set(); const panels = new Set();
const trackers = new Map();
const render = async (app, html) => { const render = async (app, html) => {
if (!game.user?.isGM) return; 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 container = html?.querySelector ? html : html?.[0];
const document = app.document; const document = app.document;
if (!document || !container) return; if (!document || !container) return;
try { try {
const choices = await getChoices(); const choices = await getChoices();
if (disposed) return; 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); if (panel) panels.add(panel);
} catch { onError(new MusicError('unavailable')); } } catch { onError(new MusicError('unavailable')); }
}; };
const hooks = ['renderSceneConfig','renderCombatConfig'].map(event => [event,Hooks.on(event, render)]); const renderDirectory=async (_app,html)=>{
return { dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); } }; 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.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();
}
};
} }
+65 -15
View File
@@ -4,6 +4,9 @@ import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs
const messages={ 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-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.', '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.', '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-required':'Enter a Music Assistant access token for this server.',
'token-invalid':'Remove line breaks from the access token and try again.', 'token-invalid':'Remove line breaks from the access token and try again.',
@@ -18,24 +21,38 @@ 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.', '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-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.', '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.', '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.', '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.', '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.', '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.', '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.', '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.', '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.', '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.', '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-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.', '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.', '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.', '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.' '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) { 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-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 (['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'; 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 +92,17 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
const initial=connection.draftFields??{}; const initial=connection.draftFields??{};
make('h2','Connect Music Assistant'); 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.'); 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 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 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 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 retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
const actions=make('div');actions.className='adaptive-actions'; const actions=make('div');actions.className='adaptive-actions';
const state=make('p');state.className='adaptive-state'; const state=make('p');state.className='adaptive-state';
const status=make('p');status.setAttribute('role','status'); const status=make('p');status.setAttribute('role','status');
const automaticFailure=make('p');automaticFailure.hidden=true;
const advanced=make('details');make('summary','Advanced',advanced); const advanced=make('details');make('summary','Advanced',advanced);
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields'; 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'); const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
@@ -91,12 +111,13 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local'); const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions'; const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
const report=make('div');report.setAttribute('aria-live','polite'); const report=make('div');report.setAttribute('aria-live','polite');
let transportResults=[],busy=false; let transportResults=[],transportCheckAt,lastConnectFailure,busy=false,hadDeviceCredential=initial.deviceCredential;
const run=async(action,label)=>{ const run=async(action,label,onFailure)=>{
if(busy||!game.user.isGM)return; if(busy||!game.user.isGM)return;
busy=true;retainError.hidden=true;render(); busy=true;retainError.hidden=true;render();
try{await action();} try{await action();}
catch(error){ catch(error){
onFailure?.(error);
busy=false;render();error.field?.focus?.(); busy=false;render();error.field?.focus?.();
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error); retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
}finally{busy=false;render();} }finally{busy=false;render();}
@@ -115,10 +136,13 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
catch{return false;} catch{return false;}
} }
const connect=button(actions,'Connect',()=>run(async()=>{ const connect=button(actions,'Connect',()=>run(async()=>{
lastConnectFailure=undefined;
let maUrl; let maUrl;
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection; const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};} 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}; if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
const targetName=name.value.trim(); 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};} if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
@@ -127,25 +151,43 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};} catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
status.textContent='Contacting Music Assistant…'; status.textContent='Contacting Music Assistant…';
let result; 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='';}} finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
address.value=connection.draftFields?.maUrl??address.value; address.value=connection.draftFields?.maUrl??address.value;
await onCatalog(); 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.'; 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'; connect.className='adaptive-primary';
const nextButton=button(actions,'Choose scene music',()=>next?.()); const nextButton=button(actions,'Choose scene music',()=>next?.());
const disconnect=button(actions,'Disconnect',()=>run(async()=>{ 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')); },'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()=>{ 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); for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
status.textContent='Browser checks complete.'; status.textContent='Browser checks complete.';
},'Browser connection check failed')); },'Browser connection check failed'));
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{ button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
const d=connection.status; 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.'; status.textContent='Connection diagnostics copied.';
},'Could not copy diagnostics')); },'Could not copy diagnostics'));
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions'; const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
@@ -156,17 +198,25 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
if(advancedContent)advanced.append(advancedContent); if(advancedContent)advanced.append(advancedContent);
function render(){ function render(){
const d=connection.status,connected=d.state==='connected'; 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`: const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label; busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
if(state.textContent!==summary)state.textContent=summary; if(state.textContent!==summary)state.textContent=summary;
state.dataset.connected=String(connected); 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; disconnect.hidden=!connected;disconnect.disabled=busy;
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected; nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection); forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy; const draft=connection.draftFields;
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token'; 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); address.addEventListener('input',render);
render(); render();
+129 -27
View File
@@ -8,33 +8,56 @@ import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
import {AutoListeners} from '../audio/auto-listeners.mjs'; import {AutoListeners} from '../audio/auto-listeners.mjs';
import {PeerAudio} from '../audio/peer-audio.mjs'; import {PeerAudio} from '../audio/peer-audio.mjs';
import {ListenerAudio} from './listener-audio.mjs'; import {ListenerAudio} from './listener-audio.mjs';
import {createSetupClass,createListenerClass} from './setup.mjs'; import {createSetupClass,createListenerClass,createPlaybackClass} from './setup.mjs';
import {MusicError} from '../core/controller.mjs'; import {MusicError} from '../core/controller.mjs';
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs'; import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
const id='adaptive-music'; const id='adaptive-music';
const receiverVault=new ReceiverVault(); const receiverVault=new ReceiverVault();
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl}); 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 accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
const savedConnection=()=>game.settings.get(id,'savedConnection'); const savedConnection=()=>game.settings.get(id,'savedConnection');
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource; let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,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; let automationRunning=false,previousController,savedDevice,deviceReconnect=false,devicePaused=false,deviceError,connectionOpening=false;
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 playbackApp,setupType;
const gmAuthority=()=>game.ready&&game.user.isGM&&!game.user.isBanned&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean); 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 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(!game.user.isGM)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(){ 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, 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; return runtime;
} }
function start(){ function playbackMode(){
return {musicMode:runtime?.musicMode,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange};
}
function refreshCombatTrackers(){interfaces?.refreshCombatTrackers();}
function start({preserveQueue=false}={}){
if(!gmAuthority()||automationRunning)return; if(!gmAuthority()||automationRunning)return;
automationRunning=true; 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(){ function stop(){
automationRunning=false; automationRunning=false;
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;} if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
refreshCombatTrackers();
} }
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);} function 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 ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
@@ -45,21 +68,25 @@ function sendInvites(){
if(!bootstrap||!gmHost?.connected||!gmAuthority())return; if(!bootstrap||!gmHost?.connected||!gmAuthority())return;
for(const user of game.users){ for(const user of game.users){
if(!user.active||user.isGM||user.isBanned)continue;const key=bootstrap.recipientKey(user);if(!key)continue; if(!user.active||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; 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,until:Date.now()+1200000});}catch{onError();} 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; });return inviteTail;
} }
const connection={ const connection={
get draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};}, 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'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};}, 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){ 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. // Claim browser audio activation before authentication performs asynchronous work.
const audioContext=gmHost.createContext(); const audioContext=gmHost.createContext();
connectionOpening=true;
const generation=connectionGeneration; const generation=connectionGeneration;
try{ try{
void audioContext.resume().catch(()=>{}); 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){ if(!profile.maUrl){
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope()); const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
gmAccessPolicy(remembered.maUrl,location.href); gmAccessPolicy(remembered.maUrl,location.href);
@@ -67,11 +94,26 @@ const connection={
} }
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale'); if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
const {target}=await connection.test(profile); const {target}=await connection.test(profile);
return await connection.connect(target,{audioContext}); const result=await connection.connect(target,{audioContext,automatic:profile.automatic===true});
}catch(error){ if(generation+1===connectionGeneration&&gmAuthority()){
if(audioContext.state!=='closed')await audioContext.close(); if(profile.remember){
throw error; 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){ async test(profile){
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'}; if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
@@ -88,12 +130,17 @@ const connection={
}catch(error){error.stage??='API authentication';throw error;} }catch(error){error.stage??='API authentication';throw error;}
finally{connectionTesting=false;} 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'); if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
stop();const profile=privateProfile,generation=connectionGeneration; stop();const profile=privateProfile,generation=connectionGeneration;
let result; let result;
try{result=await gmHost.start(profile,{audioContext});} 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'); if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
try{ try{
const saved=await sealAccountConnection(profile,profile.token,accountScope()); const saved=await sealAccountConnection(profile,profile.token,accountScope());
@@ -101,39 +148,81 @@ const connection={
}catch{onError(new MusicError('saved-connection-write-failed'));} }catch{onError(new MusicError('saved-connection-write-failed'));}
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale'); if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites(); 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; 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});}, 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),
async playback(){ async playback(){
if(!gmAuthority())throw new MusicError('denied'); if(!gmAuthority())throw new MusicError('denied');
const current=runtime?.controller.current?.playlist; 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'){ if(current?.provider==='native'){
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing); 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:''}; return {state:'idle',title:''};
}, },
control(action,value){ control(action,value){
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied'); if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
if(action==='stop'&&automationRunning&&runtime?.controller.current?.playlist)return setOverrides([{id:'gm-stop',playlist:null}]);
return ensureRuntime().controller.control(action,value); 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(){ async forgetReceiver(){
const scope=privateDraft&&receiverScope(privateDraft); const profile=privateDraft??savedDevice,scope=profile&&receiverScope(profile);
await connection.disconnect(); await connection.forgetCredentials();
await game.settings.set(id,'savedConnection',{}); await game.settings.set(id,'savedConnection',{});
if(scope)await receiverVault.forget(scope); if(scope)await receiverVault.forget(scope);
}, },
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();} 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);
}
}
}; };
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){ function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only'); if(game.user.isGM||!peers)throw Error('Listener only');
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite); ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
} }
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;} function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
Hooks.once('init',()=>{ Hooks.once('init',()=>{
Hooks.on('getSceneControlButtons',controls=>{
if(!game.user?.isGM||!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,'savedConnection',{scope:'user',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,'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,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false});
@@ -144,6 +233,7 @@ Hooks.once('init',()=>{
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)}, 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}); 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}); const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus:()=>listenerState});
setupType=Setup;
game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Enable Audio',hint:'Connects automatically to GM audio. Enable sound if your browser asks.',icon:'fas fa-headphones',type:Listener,restricted:false}); game.settings.registerMenu(id,'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}); 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});
} }
@@ -154,7 +244,20 @@ Hooks.once('ready',()=>{
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)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(game.socket&&game.user.setFlag){bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{latestInvite=invite;if(listenerStopped)return;peers.reset();await listenWebRTC(invite);}});bootstrap.start().then(sendInvites).catch(onError);inviteTimer=setInterval(()=>{sendInvites();if(game.user.isGM&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);}
gateway=new GatewayClient({origin:globalThis.location?.origin??'http://localhost'});audio=new ListenerAudio(); 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(game.user.isGM){
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&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);
if(!deviceError||['ws-upgrade-failed','ws-disconnected','ws-auth-timeout'].includes(deviceError.code))void reconnectTrustedDevice();
},15000);
}
game.modules.get(id).api={ game.modules.get(id).api={
startDevelopment:start,stopDevelopment:stop,setOverrides, 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(!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;},
@@ -169,5 +272,4 @@ Hooks.once('ready',()=>{
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(), 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();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;}
}; };
if(game.settings.get(id,'enabled'))start();
}); });
+23 -4
View File
@@ -1,6 +1,7 @@
import {MusicError} from '../core/controller.mjs'; import {MusicError} from '../core/controller.mjs';
import {musicFields,referenceKey,selection} from '../core/scene-music.mjs'; import {musicFields,referenceKey,selection} from '../core/scene-music.mjs';
const namespace='adaptive-music'; const namespace='adaptive-music';
export const playlistDragType='application/x-adaptive-music-playlist';
export async function saveMusicAssignments({document,game,choices,values,defaults=false}){ 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'); 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')??{}; 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)'); if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
select.value=referenceKey(replacement||current);return select; 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; if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments'; 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 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 labels={ambient:'Ambient playlist',combat:'Combat playlist',boss:'Default boss music',fallback:'Foundry fallback playlist'};
const controls={}; 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);} for(const field of musicFields){
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); 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 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); 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;}}); 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;}});
+31 -6
View File
@@ -1,16 +1,18 @@
import {connectionMessage} from './connection-wizard.mjs'; 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 clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
const states={playing:'Playing',paused:'Paused',idle:'Stopped'}; 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 dom=container.ownerDocument;
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;}; const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
make('h2','Playback'); make('h2','Playback');
const now=make('section');now.className='adaptive-now'; const now=make('section');now.className='adaptive-now';
const state=make('p','Stopped',now);state.className='adaptive-state'; 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 track=make('h3','Nothing playing',now);
const playlist=make('p',null,now);
const timing=make('p',null,now); const timing=make('p',null,now);
const controls=make('div');controls.className='adaptive-actions'; const controls=make('div');controls.className='adaptive-actions';
const output=make('div');output.className='adaptive-fields'; 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'; volume.type='range';volume.min='0';volume.max='100';volume.value='100';
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel); 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'; 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 summary=make('div');summary.className='adaptive-playback-summary';
const automationText=make('p',null,summary),listeners=make('p',null,summary); const automationText=make('p',null,summary),listeners=make('p',null,summary);
const status=make('p');status.setAttribute('role','status'); const status=make('p');status.setAttribute('role','status');
@@ -30,6 +37,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume')); const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
toggle.className='adaptive-primary'; toggle.className='adaptive-primary';
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop')); 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 unlock=button(controls,'Enable GM audio',()=>connection.resume());
const automation=button(summary,'Enable automation',async()=>{ const automation=button(summary,'Enable automation',async()=>{
const enable=!isRunning(); const enable=!isRunning();
@@ -43,13 +51,18 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
const label=make('label','Override playlist',manual),select=make('select',null,label); const label=make('label','Override playlist',manual),select=make('select',null,label);
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions'; 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,'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');} 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('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;})); 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('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;})); 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){ async function run(action){
if(busy||!game.user.isGM)return; if(busy||!game.user.isGM)return;
@@ -60,9 +73,15 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
} }
function render(){ function render(){
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused'; 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'; const queueError=['uncertain','receiver-access-lost'].includes(d.lastError?.code);
const canControl=connected&&trackStatus?.source==='Music Assistant'&&!queueError;
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped'); state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
const cue=musicModeLabel(d.musicMode);
const modeText=cue?`Music: ${cue}`:'';
if(mode.textContent!==modeText)mode.textContent=modeText;
mode.hidden=!cue;
track.textContent=trackStatus?.title||'Nothing playing'; track.textContent=trackStatus?.title||'Nothing playing';
playlist.textContent=trackStatus?.playlist||'';
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:''; 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(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
if(!seekEditing){ if(!seekEditing){
@@ -71,13 +90,19 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
} }
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused); toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
stopTrack.disabled=busy||!canControl||!(playing||paused); 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; 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; unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
const enabled=isRunning(); const enabled=isRunning();
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off'; automationText.textContent=enabled
? d.overrideActive?'Automatic cues are on hold. Select Return to scene music to resume.':d.awaitingSceneChange?'Automation will resume at the next scene cue':'Automation active'
: game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy; automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`; 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; 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])); 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'; import {MusicError} from '../core/controller.mjs';
// GM browser profile only. A non-extractable key protects the stored receiver // GM browser profile only. A non-extractable key protects the stored receiver
// material; same-origin scripts and the browser profile owner remain trusted. // 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{ export class ReceiverVault{
#database;#tail=Promise.resolve(); #database;#tail=Promise.resolve();
async #db(){ async #db(){
if(!globalThis.indexedDB)throw new MusicError('private-storage-unavailable'); 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; return this.#database;
} }
async #scope({campaign,userId,maUrl}){ async #scope({campaign,userId,maUrl}){
@@ -38,5 +53,41 @@ export class ReceiverVault{
await this.#transaction(id,{key,iv,data}); await this.#transaction(id,{key,iv,data});
});this.#tail=op;return op; });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;
}
} }
+54 -17
View File
@@ -1,4 +1,4 @@
import { MusicController } from '../core/controller.mjs'; import { candidates,combatAppliesToScene,MusicController } from '../core/controller.mjs';
import { buildMusicState } from '../core/scene-music.mjs'; import { buildMusicState } from '../core/scene-music.mjs';
import { NativeProvider } from '../providers/native/provider.mjs'; import { NativeProvider } from '../providers/native/provider.mjs';
export const primaryGM = users => [...users].filter(u => u.active && u.isGM) export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
@@ -7,7 +7,7 @@ export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
// All music configuration uses module-owned flags; no actor/system schema access. // All music configuration uses module-owned flags; no actor/system schema access.
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id, isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
previousController, onError = () => {} }) { previousController, onError = () => {}, onModeChange = () => {} }) {
const flag = d => d?.getFlag('adaptive-music', 'music'); const flag = d => d?.getFlag('adaptive-music', 'music');
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session, const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) }); sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
@@ -16,26 +16,63 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
if (previousController) { if (previousController) {
controller.generation = previousController.generation; controller.generation = previousController.generation;
controller.tail = previousController.tail; 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 = []; 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,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 = () => { const refresh = () => {
if (!isEnabled() || !authority()) return Promise.resolve(); if (!isEnabled() || !authority()) return Promise.resolve();
const scene = [...game.scenes].find(s => s.active); const state=getState();
const defaults=game.settings.get('adaptive-music','musicDefaults')??{}; const intent=candidates(state)[0].key;
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref; if(deferredState===intent)return Promise.resolve();
const state=buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)}, deferredState=undefined;
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose, return controller.update(state).finally(onModeChange);
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);
}; };
if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null }); if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null });
const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant', // Combat start/turn hooks precede the document update on the initiating
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'updateUser', 'deletePlaylist', 'deletePlaylistSound']; // client. Reconcile the committed state on document hooks instead.
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]); const events = ['updateScene', 'canvasReady', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
return { controller, refresh, 'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'deletePlaylist', 'deletePlaylistSound'];
setOverrides: value => { overrides = structuredClone(value); return refresh(); }, 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;},
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(); } dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
}; };
} }
+25 -1
View File
@@ -53,6 +53,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
make('h2','Assign scene music',scenePanel); make('h2','Assign scene music',scenePanel);
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel); 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); 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); const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
if(selected)scenes.value=selected.id; if(selected)scenes.value=selected.id;
@@ -81,7 +82,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.'; ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
},ownershipStatus); },ownershipStatus);
let choices=[]; let choices=[],lastCatalog=connection?.status.catalog;
const showScene=()=>{ const showScene=()=>{
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value); this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError}); if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
@@ -92,6 +93,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
if(document)mountBossEditor({document,game,container:bossBody,choices,onError}); if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
}; };
const refreshAssignments=async()=>{ const refreshAssignments=async()=>{
lastCatalog=connection?.status.catalog;
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren(); choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError}); mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
}; };
@@ -117,6 +119,9 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
this.#timer=setInterval(()=>{ this.#timer=setInterval(()=>{
if(!root.isConnected)return; if(!root.isConnected)return;
if(this.#tab==='connection')refreshConnection(); if(this.#tab==='connection')refreshConnection();
if(connection?.status.catalog!==lastCatalog){
lastCatalog=connection?.status.catalog;void refreshAssignments();
}
if(this.#tab==='playback')void refreshPlayback(); if(this.#tab==='playback')void refreshPlayback();
},1500); },1500);
} }
@@ -127,6 +132,25 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
}; };
} }
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=()=>'Waiting for the GM to connect Music Assistant.',resumeListener=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){ export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,listenerStatus=()=>'Waiting for the GM to connect Music Assistant.',resumeListener=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicListener extends Base { 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:480}};
+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. // Server-only fixed command surface, never a browser route. Target is not an argument.
async mutate(action, args, ctx) { 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']}; 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)) || 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'); !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. // Sequential, bounded and deliberately unauthenticated. No player or queue commands.
for(const path of ['/ws','/sendspin']){ for(const path of ['/ws','/sendspin']){
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:'; 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; 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 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)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}}; 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); events?.addEventListener('securitypolicyviolation',policy);
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs); 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);} 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; 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.', '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.', '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-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. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.' 'upgrade-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.'); }[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) : '', 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, duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
position, position,
repeat: queue.repeat_mode,
}; };
} }
#check(ctx) { #check(ctx) {
@@ -41,7 +42,7 @@ export class MAPlaybackProvider {
async #capture(ctx) { async #capture(ctx) {
this.#check(ctx);await this.#client.verifyTarget(); this.#check(ctx);await this.#client.verifyTarget();
const before=await this.#client.queueState(); 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=[]; 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');} 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(); 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 (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) || 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'); (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); const position=Math.floor(elapsed ?? 0);
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported'); if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
this.#check(ctx); this.#check(ctx);
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000, 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}))}; 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};} 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; 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 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) { async control(action,value,ctx) {
this.#check(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'); if(!Object.hasOwn(args,action))throw new MusicError('denied');
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{ return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{
if(action==='pause'&&this.#client.supportsNativePause?.()===false){ 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; await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
}else if(action==='resume'&&this.#paused){ }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; 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){ }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}; 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));} }else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
this.#epoch++; 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)); 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(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); 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',{}); if(value.state==='idle')await write('stop',{});
} }
}
}); });
} }
} }
+1 -1
View File
@@ -1,5 +1,5 @@
import {MusicError} from '../../core/controller.mjs'; 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. // GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{ export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;#authenticated=false;#onDisconnect; #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 }; return { id: p.id, soundId: sound.id };
} }
async snapshot(ctx) { 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); const p = this.playlist(id, ctx);
return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({ 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, 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) { async stopOwned(ctx) {
for (const id of this.owned) { for (const id of this.owned) {
if(this.sceneConflict(id))continue;
const p = this.playlist(id, ctx); const p = this.playlist(id, ctx);
const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null })); 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); } if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
+8
View File
@@ -43,3 +43,11 @@
#adaptive-music-setup .adaptive-checklist input {min-height:0;} #adaptive-music-setup .adaptive-checklist input {min-height:0;}
#adaptive-music-setup details[open] > :not(summary) {margin-block-start:0.5rem;} #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-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-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;}
+18 -4
View File
@@ -4,14 +4,28 @@
<section id="adaptive-music-setup"><main id="app" class="window-content"></main></section> <section id="adaptive-music-setup"><main id="app" class="window-content"></main></section>
<script type="module"> <script type="module">
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs'; import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
import {startConfigurationInterfaces} from '/src/foundry/configuration.mjs';
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false}; 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 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:[]}; 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=[]; let trackState='playing',position=12,repeat='off';window.controlActions=[];
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90}), 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 trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}}; 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{}}); 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; document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
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()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())}; window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
</script> </script>
+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()=>{ test('configuration hook disposal prevents pending asynchronous render from mounting',async()=>{
const f=fixture(),callbacks=new Map();let resolve;const off=[]; 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 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']); 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/);
});
+55
View File
@@ -67,6 +67,35 @@ test('scene change during manual never resurrects previous scene', async () => {
await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')}); 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); 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 () => { test('boss removed during manual and deleted combat cannot return', async () => {
const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]}; const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]};
await f.controller.update(base); await f.controller.update(big); await f.controller.update(base); await f.controller.update(big);
@@ -152,3 +181,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; 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'); 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);
});
+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']); 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); 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');
});
+1 -1
View File
@@ -8,6 +8,6 @@ test('installable development entry defaults automation off and imports no gatew
try{ try{
await import('../../src/foundry/module.mjs');once.get('init')();once.get('ready')(); 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(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,4);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;} }finally{delete globalThis.game;delete globalThis.Hooks;delete globalThis.ui;}
}); });
+35
View File
@@ -62,3 +62,38 @@ test('Foundry bootstrap registers local settings/hooks and disposes without ambi
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[]}); 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); await runtime.refresh();assert.equal(registered,1);assert.ok(callbacks.size>0);runtime.dispose();assert.equal(callbacks.size,0);
}); });
test('Foundry runtime uses committed unlinked combatant scenes and coalesces initiative changes',async()=>{
const callbacks=new Map(), calls=[];
const Hooks={on(event,callback){callbacks.set(event,callback);return event;},off(event){callbacks.delete(event);}};
const ref=id=>({provider:'ma',id});
const scene={id:'A',active:true,getFlag:()=>({ambient:ref('ambient'),combat:ref('battle'),boss:ref('boss')})};
const encounter={id:'fight',scene:null,active:true,started:false,
combatants:[{id:'token',sceneId:'A',getFlag:()=>undefined}],getFlag:()=>({boss:true})};
const combats=collection([encounter]);
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[scene],combats,
settings:{register(){},get(){return null;}}};
const maProvider={supports:()=>true,resolve:async ref=>ref,apply:async ref=>calls.push(ref.id),stopOwned:async()=>{},snapshot:async()=>({}),
restore:async()=>calls.push('restored')};
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[],maProvider});
await runtime.refresh();
assert.equal(runtime.musicMode,'ambient');
assert.equal(callbacks.has('combatStart'),false);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient']);
combats.set(encounter.id,encounter);
encounter.started=true;
callbacks.get('updateCombat')(encounter,{round:1,turn:0});
await runtime.controller.tail;
assert.equal(runtime.musicMode,'boss');
callbacks.get('updateCombat')(encounter,{turn:1});
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss']);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss','restored']);
assert.equal(runtime.musicMode,'ambient');
runtime.dispose();
});
+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(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); 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()=>{ 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}}; 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'); await saveMusicAssignments({document,game,choices:[],values:{ambient:referenceKey(ma('old'))}});assert.equal(flag.ambient.id,'old');
+36 -1
View File
@@ -2,6 +2,7 @@ import hashlib
import importlib.util import importlib.util
import json import json
from pathlib import Path from pathlib import Path
import stat
import tempfile import tempfile
import unittest import unittest
from unittest.mock import patch 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) root=Path(folder);bundle=release.build_release(output=root);first=bundle.read_bytes();release.build_release(output=root)
self.assertEqual(first,bundle.read_bytes()) self.assertEqual(first,bundle.read_bytes())
with zipfile.ZipFile(bundle) as outer: 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')) standalone=json.loads(outer.read('module.json'))
for row in outer.read('SHA256SUMS').decode().splitlines(): for row in outer.read('SHA256SUMS').decode().splitlines():
digest,name=row.split(' ',1);self.assertEqual(hashlib.sha256(outer.read(name)).hexdigest(),digest) 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(): if (ROOT/evidence).is_file():
self.assertEqual(outer.read(evidence),source.read(f'adaptive-music-source/{evidence}')) self.assertEqual(outer.read(evidence),source.read(f'adaptive-music-source/{evidence}'))
release.validate_package(root/'adaptive-music.zip',standalone) 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').mkdir(exist_ok=True)
(root/'licenses/unmanaged.txt').write_text('must not be swept into the release') (root/'licenses/unmanaged.txt').write_text('must not be swept into the release')
with self.assertRaises(ValueError):release.build_release(output=root) 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): with patch.object(release.subprocess,'check_output',side_effect=FileNotFoundError):
entries=release.source_entries(manifest) entries=release.source_entries(manifest)
self.assertIn('adaptive-music-source/src/audio/gm-host.mjs',entries) 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) 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)