Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c07a468a4 | ||
|
|
4f3fac5f1c | ||
|
|
398749210a | ||
|
|
1d894f59fb | ||
|
|
0b1607cd20 |
No files matched your search
+24
-9
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music architecture — 0.7.0
|
||||
# Adaptive Music architecture — 0.7.2
|
||||
|
||||
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
|
||||
@@ -8,6 +8,11 @@ scaffolding rule. Optional historical gateway source is not required or deployed
|
||||
|
||||
## Setup and receiver ownership
|
||||
|
||||
The Connection tab validates the server, token and optional Advanced network fields
|
||||
before authentication. The Connect gesture starts the GM audio context before
|
||||
authentication, receiver provisioning and catalog loading. Playback reads the
|
||||
dedicated MA queue and submits controls on the same controller as scene transitions.
|
||||
|
||||
The GM supplies the private trusted HTTPS MA origin and access token. Authentication
|
||||
reads account-authorized music providers. The official pinned Sendspin SDK generates
|
||||
one X25519 identity for the campaign, GM user and MA origin. Its identity, pairing
|
||||
@@ -17,6 +22,12 @@ trusted-origin scripts or theft of the complete browser profile. The token is ne
|
||||
persisted. Failed attempts retain private inputs in tab memory; changing the MA
|
||||
origin never reuses its token or identity.
|
||||
|
||||
The logged-in GM account can retain an AES-GCM envelope containing the last
|
||||
successfully connected MA address and receiver name in a Foundry User Setting.
|
||||
The MA token supplied for a connection unlocks the envelope. Its key is derived
|
||||
with a separate purpose label and bound to the Foundry origin, world and user.
|
||||
Foundry persists the encrypted record across devices and server restarts.
|
||||
|
||||
Connect audio first authenticates the `/ws` API session, then authenticates
|
||||
`/sendspin` using that token and the SDK-generated client ID. MA 2.10.6 associates
|
||||
this new web receiver with already-authenticated API sessions for the token. The
|
||||
@@ -31,8 +42,12 @@ There is no household player list or arbitrary target selector.
|
||||
The receiver uses SDK software volume. Fresh receivers do not report volume before
|
||||
capabilities are advertised, so volume cannot be a preconnection requirement. Static
|
||||
account-authorized playlist tracks become opaque HMAC references bound to the stored
|
||||
catalog key and campaign. Scene/world flags persist those references, never MA URIs,
|
||||
endpoints, tokens or receiver secrets.
|
||||
catalog key and campaign. New references use a separate key derived from the MA
|
||||
token, MA origin and campaign so the same authorized catalog resolves on another
|
||||
browser. A browser with its original receiver vault still resolves legacy IDs.
|
||||
Saving that scene again writes the new reference. Scene/world flags hold opaque
|
||||
references. Live connections still depend on the active GM browser and its audio
|
||||
context. Disconnect stops the session and clears the in-memory token.
|
||||
|
||||
## Audio and listeners
|
||||
|
||||
@@ -84,9 +99,9 @@ explicitly owned playlists; effects and AmbientSound remain untouched.
|
||||
|
||||
## Verification boundary
|
||||
|
||||
Source archive evidence separates real MA authentication/provisioning/catalog/audio,
|
||||
actual browser WebRTC, actual Foundry ApplicationV2 rendering and offline regressions.
|
||||
Browser integration uses the deployed Foundry origin with local source assets supplied
|
||||
by Playwright, not an installed logged-in Foundry world. Mac networking, actual User
|
||||
permission enforcement, Foundry socket delivery and WAN behavior still require the
|
||||
single consolidated acceptance sequence in TESTING.md.
|
||||
The installed v0.7.0 module was tested in a logged-in Foundry v14.371 development
|
||||
world through the private Nginx route. The GM connected to MA and two players
|
||||
received audio using Foundry’s module socket for signaling. The test also exercised
|
||||
real combat hooks, ordered ambient restoration, and User document permissions.
|
||||
Earlier browser tests used a Playwright source overlay. The original Mac path,
|
||||
physical-device audibility, invitation renewal and WAN behavior remain unverified.
|
||||
@@ -1,5 +1,18 @@
|
||||
# Changelog
|
||||
|
||||
## 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.
|
||||
- Make newly saved catalog assignments readable across browsers that use the same MA token, server and Foundry world. Preserve legacy reference resolution in the browser that created it.
|
||||
|
||||
## 0.7.1 — AM-006 setup usability
|
||||
|
||||
- Give the resizable GM window three tabs for Connection, Scene Music and Playback.
|
||||
- Connect with one action that validates the inputs, authenticates, provisions the
|
||||
dedicated receiver and loads playlists. Keep listener networking under Advanced.
|
||||
- Show the current track, position, volume, automation state and connected listener
|
||||
count. Queue pause, resume, seek and stop through the existing playback authority.
|
||||
|
||||
## 0.7.0 — integrated campaign receiver
|
||||
|
||||
- Replace receiver JSON import with authenticated automatic dedicated web-receiver
|
||||
|
||||
+29
-36
@@ -1,4 +1,4 @@
|
||||
# Install and connect — 0.7.0
|
||||
# Install and connect — 0.7.2
|
||||
|
||||
## Normal setup
|
||||
|
||||
@@ -7,41 +7,40 @@
|
||||
Foundry user-data `Data/modules/` directory and reload the isolated test world.
|
||||
The ZIP contains one `adaptive-music/` directory. Do not install the outer release
|
||||
bundle or source archive as the module.
|
||||
2. As the single active GM, open Settings → Adaptive Music setup. Enter the private
|
||||
trusted **HTTPS Music Assistant server address** and the dedicated account’s access
|
||||
token, then select **Authenticate**. Use the origin, without a subpath or query.
|
||||
3. Select **Connect audio**. The module automatically creates or reconnects its own
|
||||
campaign receiver and pairs it to the authenticated account. No receiver identity
|
||||
export or JSON backup import is needed. The selector includes only this browser’s
|
||||
campaign-owned receiver; it does not enumerate household speakers.
|
||||
4. Assign ambient and combat playlists to the selected scene and save assignments.
|
||||
World defaults and boss/manual controls are optional. Enable music automation.
|
||||
2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**,
|
||||
enter the private **HTTPS Music Assistant server address** and the dedicated
|
||||
account’s access token. Use the server origin and select **Connect** to create or
|
||||
reconnect the campaign receiver, pair it, and load playlists.
|
||||
3. Select **Choose scene music**. In **Scene Music**, choose the scene and save its
|
||||
ambient, combat, boss and native fallback assignments. You can also set world
|
||||
defaults and individual boss overrides.
|
||||
4. Open **Playback** to enable automation, see the current track and listeners, or
|
||||
adjust campaign volume and control the dedicated MA queue.
|
||||
5. Players connect automatically. If a browser requires activation, open Campaign
|
||||
audio and select **Enable Audio** once. Keep one audio tab per account.
|
||||
|
||||
The token stays in this tab’s memory, including across failed attempts and setup
|
||||
window closure. Reload or Disconnect forgets it. Receiver identity is encrypted in
|
||||
this GM browser’s local storage and reused after reauthentication. A changed MA
|
||||
origin needs a new login and a separately scoped receiver. Clearing site storage
|
||||
forgets the receiver. Receiver options can name a new receiver; existing remembered
|
||||
names remain identity-bound. Forget remembered receiver removes the local identity
|
||||
only, leaving MA resources and queues untouched.
|
||||
After a successful connection, the GM’s Foundry account remembers the encrypted
|
||||
server address and receiver name. On another computer or after reload, enter the
|
||||
same MA token and select **Connect** to unlock the saved address. Reload and
|
||||
**Disconnect** clear the in-memory token. If the token changes, enter the server
|
||||
address with the replacement token. **Advanced → Forget saved connection** clears
|
||||
the account record. The receiver identity remains encrypted in its browser vault.
|
||||
|
||||
Connection recovery → Reconnect remembered receiver reuses this tab’s credentials and preserves the queue while pausing automation. Optional existing STUN/TURN settings are in Receiver options; no public ICE service is enabled by default.
|
||||
New MA playlist assignments resolve across browsers using the same MA token and
|
||||
origin. To update a legacy assignment, connect from the browser that originally
|
||||
saved it and save the scene again. From a different browser, reselect its playlists.
|
||||
Keep the active GM browser open for live MA playback and listener forwarding.
|
||||
|
||||
Reconnecting to an owned nonempty queue preserves it. Apply the automation setting
|
||||
Reconnecting to an owned nonempty queue preserves it. Enable automation in Playback
|
||||
when ready to resume scene control. Unknown mutation outcomes stop automation and
|
||||
require review; they are never silently replayed. Pause is emulated for MA 2.10.6
|
||||
Sendspin by preserving a stopped queue’s index/position in the active GM session.
|
||||
Crossfade and restoration after a GM crash/reload are not guaranteed. Old experimental identity-based assignments may need playlist reselection once; the remembered v0.7.0 receiver keeps subsequent catalog references stable.
|
||||
require review. Pause preserves a stopped queue’s index and position for the active
|
||||
GM session.
|
||||
|
||||
## Connection diagnostics
|
||||
|
||||
Setup displays the actual stage: authentication, Sendspin connection, pairing,
|
||||
clock sync, catalog or ready. It shows decoded frames, GM audio state and connected
|
||||
listeners. **Check browser connection (no MA token)** tests both WebSocket routes
|
||||
from the actual Foundry page and identifies enforced CSP blocks. It does not send
|
||||
an MA authentication frame; normal browser cookies may still accompany the handshake.
|
||||
Connection shows authentication, receiver setup and catalog progress. **Check browser
|
||||
connection** tests both WebSocket routes from the actual Foundry page without sending
|
||||
an MA authentication frame. Normal browser cookies can accompany the handshake.
|
||||
**Copy connection diagnostics** supplies a report without address, token, receiver
|
||||
keys or playlist titles. No browser developer console is required.
|
||||
|
||||
@@ -64,24 +63,18 @@ additional container, service, VM or LXC is required by this module. A direct HT
|
||||
address cannot be used from HTTPS Foundry. Default ICE does not use a public relay;
|
||||
remote players still need a viable existing WebRTC path.
|
||||
|
||||
Ubuntu Firefox and Chromium reached the deployed HTTPS endpoints from the Foundry
|
||||
origin through normal public DNS resolution. The operator’s Mac instead maps MA to
|
||||
the private proxy; that private proxy’s TCP 443 route times out from Ubuntu before
|
||||
TLS. A single temporary VM-to-proxy TCP 443 flow has been proposed to the operator
|
||||
with rollback in ignored .local/PRIVATE-ROUTE-REQUEST.md; it has not been applied.
|
||||
No persistent DNS or broad proxy change is requested. The original Mac path remains
|
||||
unverified. Run TESTING.md’s one acceptance sequence before public publication.
|
||||
See TESTING.md for private-route evidence and the outstanding installed, Mac and WAN checks.
|
||||
|
||||
## Manual Gitea publication
|
||||
|
||||
The existing stable manifest and versioned download mechanism is preserved:
|
||||
|
||||
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
|
||||
- v0.7.0 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.0/adaptive-music.zip`
|
||||
- v0.7.2 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/adaptive-music.zip`
|
||||
|
||||
These are the established repository’s URLs; this work never contacted Gitea or
|
||||
verified public asset availability. After acceptance, manually publish the included
|
||||
source to your existing repository, create tag/release `v0.7.0`, attach
|
||||
source to your existing repository, create tag/release `v0.7.2`, attach
|
||||
`adaptive-music.zip` and the included manifest/checksums, and update the branch
|
||||
manifest only after its versioned asset exists. The outer bundle includes full
|
||||
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
|
||||
|
||||
+14
-8
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music progress — 0.7.0 staged acceptance
|
||||
# Adaptive Music progress — 0.7.2 staged acceptance
|
||||
|
||||
Standalone module work now includes automatic campaign receiver provisioning and
|
||||
account-bound pairing, remembered encrypted browser-local identity, memory-only token
|
||||
@@ -14,13 +14,20 @@ was accessed and no production infrastructure/core versions were changed.
|
||||
| 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-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 | Real deployed-origin authentication works in Ubuntu Firefox/Chromium; same-session receiver ACL, Firefox SDP and buffer bugs fixed | Original Mac-specific pre-upgrade failure is not reproduced or independently resolved |
|
||||
| MA catalog playback | Firefox 159 and Chromium 159 measured real audio at both listeners across ambient, combat and restoration | Actual Foundry world, physical devices and WAN acceptance |
|
||||
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox. Chromium authenticated and paired in the installed Foundry world. The MA front end’s unauthenticated Sendspin interceptor explains the failing control probe. | Original Mac-specific pre-upgrade failure remains unresolved |
|
||||
| AM-006 setup usability | The v0.7.1 browser preview passed layout at 380 and 760 pixels, one-click connection, scene assignment and real playback controls in the development world. | Retry the same workflow with v0.7.1 installed on the server |
|
||||
| Account persistence | The v0.7.2 preview saved an encrypted connection record in the Foundry GM account and connected from a fresh browser with the token alone. New scene references are portable across browsers using that token. | v0.7.2 server installation and Mac acceptance |
|
||||
| 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
|
||||
|
||||
- Tested Foundry page has no CSP header/meta policy. Both HTTPS origins authenticate
|
||||
from Ubuntu using public DNS. The Mac’s private proxy route is a different path; TCP 443 to that proxy times out from Ubuntu. One narrowly scoped temporary access proposal with rollback is prepared under ignored .local/PRIVATE-ROUTE-REQUEST.md and awaits operator execution.
|
||||
- The operator’s scoped firewall exception enabled TCP 443 and trusted TLS to the
|
||||
private Nginx proxy. The test verified the proxy peer before signing in on the
|
||||
normal Foundry hostname. The signed-in page had no enforced CSP header or meta
|
||||
policy and both MA WebSocket upgrades returned HTTP 101.
|
||||
- Browser playback analysers measured audio on both real Foundry listeners even
|
||||
while Chromium’s inbound RTP energy statistic reported zero. The integration
|
||||
test uses the rendered playback signal. No module runtime change was required.
|
||||
- MA grants a new browser receiver access through API sessions authenticated before
|
||||
Sendspin auth. Replacing the API socket breaks a restricted account’s access.
|
||||
- Firefox reached an available paired receiver before MA returned its queue. Setup
|
||||
@@ -43,8 +50,7 @@ startup failed with MA `MediaNotFoundError` in both engines. The cause of those
|
||||
failures remains unconfirmed. The controller preserves the failed command and skips
|
||||
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
|
||||
|
||||
The v0.7.0 bundle is staged locally for acceptance. Publication remains pending the
|
||||
Mac private route, actual Foundry hooks, sockets and User permissions, and physical
|
||||
device, WAN and invitation-renewal checks in TESTING.md.
|
||||
The installed-world evidence is in `evidence/v0.7.0-foundry-private.json`. Publication
|
||||
remains pending Mac, physical-device, WAN and invitation-renewal checks in TESTING.md.
|
||||
Crossfade, durable crash restoration, seamless handover and WAN synchronization
|
||||
remain unsupported.
|
||||
@@ -1,27 +1,27 @@
|
||||
# Adaptive Music — 0.7.0
|
||||
# Adaptive Music — 0.7.2
|
||||
|
||||
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
|
||||
Foundry v14.371 and Music Assistant 2.10.6. System-independent; one Foundry module
|
||||
ZIP, no other required module, container, VM/LXC or companion service.
|
||||
|
||||
Enter your private HTTPS MA address and authenticate in Adaptive Music setup.
|
||||
Connect the automatically provisioned dedicated campaign receiver, assign ambient
|
||||
and combat playlists, and enable automation. Players receive WebRTC audio
|
||||
Enter your private HTTPS MA address and token in **Connection**, then select
|
||||
**Connect**. Assign playlists in **Scene Music** and enable automation in
|
||||
**Playback**. Players receive WebRTC audio
|
||||
automatically, with one Enable Audio click if their browser requires it. No receiver
|
||||
identity export or JSON import is part of setup.
|
||||
|
||||
MA tokens stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
|
||||
The signed-in GM account remembers the encrypted Music Assistant address. Enter the
|
||||
MA token and select **Connect** to unlock it in a new browser session. MA tokens
|
||||
stay in the GM tab’s memory. A campaign/GM/origin-scoped receiver identity
|
||||
is encrypted in that browser’s IndexedDB so reconnecting does not create another
|
||||
receiver. Players receive individually encrypted invitations, not MA credentials.
|
||||
Only that dedicated receiver and explicitly owned Foundry music playlists are
|
||||
controlled. Household speakers, grouping, queue transfers, sound effects and
|
||||
AmbientSound documents are outside the control surface.
|
||||
|
||||
Real MA/browser integration evidence is included in the source archive. Actual
|
||||
Foundry v14.371 ApplicationV2 rendering was tested; a logged-in-world test on the
|
||||
operator’s Mac remains necessary. Ubuntu browser success does not establish Mac
|
||||
network permissions or WAN reachability. This package is staged for that acceptance;
|
||||
publication has not occurred and no Git host was accessed.
|
||||
The v0.7.1 browser preview passed the new graphical setup and playback workflow
|
||||
in a real Foundry v14.371 development world with two listeners. See TESTING.md
|
||||
for the test scope and remaining installed-build checks.
|
||||
|
||||
See INSTALL.md for setup/manual publication, TESTING.md for the consolidated Mac
|
||||
acceptance sequence, SECURITY.md for trust boundaries and PROGRESS.md for status.
|
||||
|
||||
+9
-3
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music security — 0.7.0
|
||||
# Adaptive Music security — 0.7.2
|
||||
|
||||
## Credentials and browser trust
|
||||
|
||||
@@ -8,6 +8,12 @@ and release archives. Setup failures retain it in this tab; disconnect or reload
|
||||
forgets it. Tokens are never reused after an origin change. Use a restricted MA
|
||||
account with only the intended music providers and dedicated receiver permissions.
|
||||
|
||||
The Foundry User Setting stores only a version, random nonce and encrypted MA
|
||||
address and receiver name. The encryption key is derived from the user-entered MA
|
||||
token for this account and world. Use a generated, high-entropy MA token. The
|
||||
envelope cannot be unlocked after rotating that token. Connect with the explicit
|
||||
address and new token to replace it. Forget saved connection removes the envelope.
|
||||
|
||||
Receiver private identity and pairing material are encrypted in the GM browser’s
|
||||
IndexedDB under a campaign/user/origin-derived scope. Encryption uses AES-GCM and
|
||||
a non-extractable key stored in the same browser. It avoids plaintext receiver
|
||||
@@ -42,8 +48,8 @@ sessions reject them. Browser authority cannot replace a distributed server fenc
|
||||
|
||||
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
|
||||
Public ephemeral keys on permission-controlled User documents authenticate invitation
|
||||
delivery. Server-enforced User permissions and role checks are essential; their
|
||||
actual-world behavior remains an acceptance gate. SDP is encrypted, bounded and
|
||||
delivery. Both ordinary test players were denied a write to the GM’s User flags in
|
||||
the installed development world. SDP is encrypted, bounded and
|
||||
replay protected, and validated for one audio direction with media-level SDP
|
||||
inheritance. No microphone, video or data channel is requested. Audio uses DTLS-SRTP.
|
||||
Recipients can record audio or disclose their own capability. Direct peers can
|
||||
|
||||
+79
-15
@@ -1,9 +1,61 @@
|
||||
# Adaptive Music verification — 0.7.0
|
||||
# Adaptive Music verification — 0.7.2
|
||||
|
||||
## Executed evidence
|
||||
|
||||
The source archive includes sanitized evidence separately from private .local inputs.
|
||||
|
||||
### Account persistence and v0.7.0 GUI review
|
||||
|
||||
The installed v0.7.0 was exercised again through Foundry’s Settings and Adaptive
|
||||
Music menus. Playwright filled the server address and access token and pressed
|
||||
Authenticate and Connect audio. The run used the private proxy route with normal
|
||||
TLS validation and did not replace module assets. The GM saved ambient and combat
|
||||
assignments on a review scene and confirmed the GM decoder received live audio.
|
||||
The scene was left in the development world. In the same world, a browser-supplied
|
||||
v0.7.2 candidate saved an encrypted Foundry User Setting. A new browser session
|
||||
logged into the same GM account and connected with the token alone. The server
|
||||
continued serving v0.7.0 during both tests. Closing the GM audio tab ends the
|
||||
browser-hosted connection. See `evidence/v0.7.2-live.json`.
|
||||
|
||||
### AM-006 live graphical workflow
|
||||
|
||||
The v0.7.1 interface ran inside the actual Foundry v14.371 development world with
|
||||
module assets supplied to the test browser by Playwright. The graphical window
|
||||
passed sizing, horizontal fit, scroll containment, keyboard navigation, Advanced
|
||||
visibility and input validation at 380 and 760 pixels. Through the private route,
|
||||
one Connect action authenticated, provisioned the receiver and loaded the catalog.
|
||||
The GM saved scene assignments and enabled automation through the tabs. Both
|
||||
listeners measured audio during real combat and ambient restoration to eight seconds.
|
||||
The Playback tab showed the track and both listeners. Volume, pause, resume and stop
|
||||
worked through the graphical controls. Listener Stop/Enable and reload also passed.
|
||||
The earlier private-route timeout and an ambient startup attempt without a queue
|
||||
write are recorded alongside the passing rerun in `evidence/v0.7.1-live.json`.
|
||||
Verification of the v0.7.1 ZIP installed on the server is pending.
|
||||
|
||||
### Installed development world over private Nginx
|
||||
|
||||
- Chromium 159 signed into Foundry v14.371 as the GM and both players. The installed
|
||||
v0.7.0 module authenticated to MA and paired a dedicated Sendspin receiver. Both
|
||||
WebSocket routes returned HTTP 101 from the signed-in page, which exposed no
|
||||
enforced CSP header or meta policy.
|
||||
- Both players received encrypted invitations through the real Foundry module socket.
|
||||
Foundry denied both ordinary players’ attempts to update a flag on the GM’s User
|
||||
document. Both players measured signal in their actual playback graphs during
|
||||
ambient, combat and restored ambient. The original queue order and seven-second
|
||||
offset were restored. Audio also returned after Stop/Enable and a player reload.
|
||||
Chromium’s inbound RTP energy counter stayed at zero while the playback graphs
|
||||
showed audio, so the test uses the playback signal.
|
||||
- The MA control page replaces `window.WebSocket` and intercepts Sendspin. Its
|
||||
unauthenticated interceptor failed the bare `/sendspin` probe. The native browser
|
||||
constructor opened the same URL from the same page in Chromium and Firefox.
|
||||
The original Mac-specific AM-005 failure did not reproduce on this Ubuntu route.
|
||||
The Ubuntu Firefox build completed transport checks. Its Foundry join UI failed
|
||||
to render in this environment, which could not create a WebGL context.
|
||||
|
||||
See `evidence/v0.7.0-foundry-private.json` for the installed-world results.
|
||||
|
||||
### Earlier browser and source-overlay checks
|
||||
|
||||
- Ubuntu Firefox 159.0 and Chromium 159.0.8154.6
|
||||
authenticated from Foundry’s origin and MA’s origin and retrieved seven providers.
|
||||
The unauthenticated Foundry page returned no enforced CSP header or meta policy.
|
||||
@@ -45,12 +97,13 @@ private HTTPS MA endpoint. It needs no developer console or diagnostic shell com
|
||||
|
||||
1. Install the staged module ZIP, reload, and log in as the sole active GM from your
|
||||
Mac. Open setup at normal and narrow window sizes. Enter the HTTPS MA address and
|
||||
dedicated token, Authenticate, then Connect audio. The receiver should be provisioned
|
||||
dedicated token, then select **Connect**. The receiver should be provisioned
|
||||
and playlists should load without a backup file. If MA reports media error 2 after connection, verify the same content in MA’s own dedicated web player before treating it as a browser transport failure. If connection fails, select Check
|
||||
browser connection and Copy connection diagnostics once, and report that single
|
||||
report with browser/version and whether MA’s own page works in that same browser.
|
||||
2. Choose two authorized static playlists for an active scene’s ambient/combat music,
|
||||
save, and enable automation. Check the GM hears ambient and decoded frames increase.
|
||||
2. In **Scene Music**, choose two authorized static playlists for an active scene’s
|
||||
ambient/combat music and save. In **Playback**, enable automation. Check the GM
|
||||
hears ambient and decoded frames increase.
|
||||
Only the campaign receiver may be controlled. Native fallback remains optional.
|
||||
3. Log in as two ordinary players using separate browser profiles/devices. They should
|
||||
receive audio automatically, needing at most one Enable Audio click. Check late login,
|
||||
@@ -68,18 +121,30 @@ private HTTPS MA endpoint. It needs no developer console or diagnostic shell com
|
||||
failures with Copy connection diagnostics. Repeat on the actual WAN player route;
|
||||
loopback/LAN signal does not establish NAT/TURN reachability or synchronization.
|
||||
|
||||
Acceptance requires audible output on the actual Mac/player devices, a successful
|
||||
original Mac connection path, actual Foundry hooks, socket delivery and User
|
||||
permissions, and the renewal and WAN checks above. Public release readiness remains
|
||||
false until these checks are recorded. If the Mac still cannot reach WSS before
|
||||
opening, its exact device-side cause remains external to the tested Ubuntu path;
|
||||
the exact private-route access request is consolidated in ignored .local/PRIVATE-ROUTE-REQUEST.md. It proposes only temporary VM-to-proxy TCP 443 access with rollback, not a public API or disabled browser protection.
|
||||
The installed-world run covered real Foundry hooks, socket delivery and User
|
||||
permissions. Public release acceptance still requires audibility on the actual
|
||||
Mac/player devices, the original Mac connection, invitation renewal and WAN checks.
|
||||
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp
|
||||
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.
|
||||
|
||||
## Reproduce development checks
|
||||
|
||||
Use the existing pinned Node 24.23.0, Python standard library and Playwright 1.57.0.
|
||||
No upstream installation hook is required.
|
||||
|
||||
For private-route diagnostics, run `node scripts/check_foundry_private_route.mjs`
|
||||
with the existing browser path settings. The probe verifies the HTTPS peer address
|
||||
for both origins and compares WSS upgrades from Foundry and Music Assistant. It
|
||||
captures handshake status and browser policy metadata. Add `--logged-in` after the
|
||||
private route is reachable and the dedicated development world is active. That
|
||||
mode verifies the installed module version, signs in with the three configured
|
||||
test accounts in separate browser contexts, and adds the authenticated Foundry
|
||||
page as a comparison. `--playback` also exercises actual MA audio, Foundry combat,
|
||||
listener recovery, and cleanup with temporary development-world documents and a
|
||||
dedicated integration receiver. Configuration and results remain under ignored
|
||||
`.local/`.
|
||||
|
||||
```sh
|
||||
npm test
|
||||
python3 -m unittest discover -s tests -v
|
||||
@@ -104,8 +169,7 @@ no browser flags. No new distributed dependency was introduced. Supplemental Pla
|
||||
|
||||
## Limits
|
||||
|
||||
No Mac/Safari execution, physical audibility, installed-world acceptance, real User
|
||||
permission adversarial test, WAN relay test, long-run skew/drift, seamless GM handover,
|
||||
crash restore or crossfade is claimed. The upstream single queue does not provide
|
||||
simultaneous outgoing/incoming streams for a true crossfade. Pause is emulated and
|
||||
its saved position remains in memory; a full reload cannot recover that position.
|
||||
Mac/Safari behavior, physical audibility, WAN relay, long-run skew/drift, seamless
|
||||
GM handover, crash restore and crossfade remain unverified or unsupported. The
|
||||
upstream single queue provides one playback stream. Pause is emulated and its
|
||||
saved position lasts for the active GM session.
|
||||
@@ -3,7 +3,7 @@
|
||||
"publicationReady": false,
|
||||
"completedCoreRunPassed": true,
|
||||
"macPrivateRouteVerified": false,
|
||||
"foundryLoggedInWorldVerified": false,
|
||||
"foundryLoggedInWorldVerified": true,
|
||||
"actualMAAuthentication": true,
|
||||
"actualMACatalogPlaylists": 11,
|
||||
"actualMADedicatedProvisioning": true,
|
||||
@@ -87,16 +87,15 @@
|
||||
"networkBoundary": {
|
||||
"sandboxNormalDNS": "public addresses",
|
||||
"operatorMacMAResolution": "private proxy mapping",
|
||||
"sandboxPrivateProxyTCP443": "timeout before TLS",
|
||||
"temporaryAccessRequestPrepared": true,
|
||||
"infrastructureChanged": false
|
||||
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
|
||||
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
|
||||
"infrastructureChangedByTestAgent": false
|
||||
},
|
||||
"remaining": [
|
||||
"operator private-route access and Mac original failure acceptance",
|
||||
"logged-in Foundry hooks, socket and User permission acceptance",
|
||||
"original Mac connection and AM-005 reproduction if the symptom persists",
|
||||
"WAN/30-minute behavior and hardware audibility"
|
||||
],
|
||||
"evidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||
"credentialUseAuthorized": true,
|
||||
"dedicatedReceiverMutationsPerformed": true,
|
||||
"latestCatalogReplayPassed": true,
|
||||
@@ -123,7 +122,7 @@
|
||||
"version": "0.7.0",
|
||||
"scope": "Local acceptance package with isolated browser checks, deployed Foundry ApplicationV2 rendering and dedicated MA receiver tests",
|
||||
"publicationReady": false,
|
||||
"foundryInstalledWorldVerified": false,
|
||||
"foundryInstalledWorldVerified": true,
|
||||
"originalMacConnectionVerified": false,
|
||||
"deployedOriginAuthentication": "Ubuntu Chromium and Firefox",
|
||||
"maReceiver": {
|
||||
@@ -136,7 +135,8 @@
|
||||
"evidence/v0.7.0-live.json",
|
||||
"evidence/v0.7.0-live-follow-up.json",
|
||||
"evidence/foundry-application-v070.json",
|
||||
"evidence/v0.7.0-checks.txt"
|
||||
"evidence/v0.7.0-checks.txt",
|
||||
"evidence/v0.7.0-foundry-private.json"
|
||||
],
|
||||
"regression": {
|
||||
"javascript": 101,
|
||||
@@ -146,7 +146,6 @@
|
||||
"productionInfrastructureChanged": false,
|
||||
"remainingAcceptance": [
|
||||
"Mac private MA route",
|
||||
"installed Foundry world hooks, socket and User permissions",
|
||||
"listener renewal, actual player devices and WAN route"
|
||||
],
|
||||
"history": [
|
||||
@@ -252,5 +251,9 @@
|
||||
"exactUpstreamResolutionCause": "unconfirmed",
|
||||
"automaticMutationRetries": false
|
||||
},
|
||||
"dedicatedReceiverReconnectPassed": true
|
||||
"dedicatedReceiverReconnectPassed": true,
|
||||
"privateNginxRouteVerifiedFromUbuntu": true,
|
||||
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
|
||||
}
|
||||
@@ -28,8 +28,10 @@ its queue. Startup now retries a null queue read briefly on the bound API sessio
|
||||
The offline regression exercises the waiting path. In the passing live reruns both
|
||||
browsers received the queue on the first read.
|
||||
|
||||
The sandbox cannot reach the Mac's private proxy route on TCP 443 (timeout before
|
||||
TLS). A temporary exact-flow proposal/rollback is under ignored .local/ and awaits
|
||||
operator execution. No infrastructure change was made. Original Mac path, logged-in
|
||||
world/User permissions, WAN/renewal and physical audibility remain unverified.
|
||||
Publication readiness is false. No Gitea access or publication occurred.
|
||||
The initial VM-to-proxy TCP probe timed out before TLS. After the operator enabled
|
||||
the scoped firewall exception, private Nginx TLS and Chromium GM/player login passed.
|
||||
Real Foundry signaling, Player User flag denial, dedicated MA playback for both
|
||||
listeners, combat/ambient restore to seven seconds, and listener Stop/Enable and
|
||||
reload passed. See v0.7.0-foundry-private.json. The original Mac issue did not
|
||||
reproduce on Ubuntu. Mac, WAN, renewal and physical audibility remain unverified.
|
||||
Publication readiness remains false.
|
||||
@@ -0,0 +1,612 @@
|
||||
{
|
||||
"scope": "Foundry and Music Assistant through the operator private Nginx HTTPS route, with trusted TLS and a verified proxy peer",
|
||||
"foundryVersion": "14.371",
|
||||
"installedModuleVersion": "0.7.0",
|
||||
"privateRouteVerified": true,
|
||||
"transport": [
|
||||
{
|
||||
"engine": "chromium",
|
||||
"version": "159.0.8154.6",
|
||||
"at": "2026-12-04T15:00:10.335Z",
|
||||
"checks": {
|
||||
"foundryAnonymous": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": false,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-ok"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": []
|
||||
},
|
||||
"maSameOrigin": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": true,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-failed"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": [],
|
||||
"nativeSendspinUpgrade": "upgrade-ok"
|
||||
},
|
||||
"foundryLoggedIn": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": false,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-ok"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"version": "159.0",
|
||||
"at": "2026-12-04T14:51:41.129Z",
|
||||
"checks": {
|
||||
"foundryAnonymous": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": false,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-ok"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [],
|
||||
"failedRequests": [],
|
||||
"policyIssues": []
|
||||
},
|
||||
"maSameOrigin": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": true,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-failed"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [],
|
||||
"failedRequests": [],
|
||||
"policyIssues": [],
|
||||
"nativeSendspinUpgrade": "upgrade-ok"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"signedInPlayers": [
|
||||
{
|
||||
"worldVerified": true,
|
||||
"foundry": "14.371",
|
||||
"moduleVersion": "0.7.0",
|
||||
"foreignWriteDenied": true,
|
||||
"gmActive": true,
|
||||
"apiReady": true,
|
||||
"publicKeyPublished": true
|
||||
},
|
||||
{
|
||||
"worldVerified": true,
|
||||
"foundry": "14.371",
|
||||
"moduleVersion": "0.7.0",
|
||||
"foreignWriteDenied": true,
|
||||
"gmActive": true,
|
||||
"apiReady": true,
|
||||
"publicKeyPublished": true
|
||||
}
|
||||
],
|
||||
"gmVerified": true,
|
||||
"maControlPageFinding": "The Music Assistant frontend replaces window.WebSocket and intercepts Sendspin. The intercepted call failed on its unauthenticated page. The same page opened Sendspin with the native constructor retained before frontend scripts.",
|
||||
"originalMacAM005Reproduced": false,
|
||||
"originalMacAM005RootCauseConfirmed": false,
|
||||
"threeAccountsVerifiedTogether": true,
|
||||
"installedWorldPlaybackBaseline": {
|
||||
"at": "2026-12-04T15:00:10.335Z",
|
||||
"engine": "chromium",
|
||||
"playback": {
|
||||
"stage": "ambient",
|
||||
"publicKeys": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
],
|
||||
"playerCannotWriteGMFlag": true,
|
||||
"maAPIAuthenticated": true,
|
||||
"sendspinAuthenticated": true,
|
||||
"accountPairingPassed": true,
|
||||
"catalogChoices": 11,
|
||||
"listenerStatsAtFailure": [
|
||||
{
|
||||
"bytes": 125468,
|
||||
"energy": 0,
|
||||
"samples": 1560000
|
||||
},
|
||||
{
|
||||
"bytes": 125468,
|
||||
"energy": 0,
|
||||
"samples": 1560480
|
||||
}
|
||||
],
|
||||
"queueWrites": [
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
}
|
||||
],
|
||||
"gmAudioDiagnostics": {
|
||||
"stage": "ready",
|
||||
"state": "connected",
|
||||
"audioContext": "running",
|
||||
"decoded": 1367,
|
||||
"scheduled": 1367,
|
||||
"droppedLate": 0,
|
||||
"droppedAhead": 0,
|
||||
"signalRMS": 0.1258655905070254,
|
||||
"muted": false,
|
||||
"listenerConnections": 2,
|
||||
"volume": 100
|
||||
},
|
||||
"browserAudio": [
|
||||
{
|
||||
"decodedFrames": 1367,
|
||||
"signaling": {
|
||||
"invitationsForMe": 0,
|
||||
"invitationEvents": 0,
|
||||
"offers": 2,
|
||||
"answers": 0,
|
||||
"sentInvitations": 2,
|
||||
"sentSignals": 2
|
||||
},
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"signaling": {
|
||||
"invitationsForMe": 1,
|
||||
"invitationEvents": 2,
|
||||
"offers": 1,
|
||||
"answers": 2,
|
||||
"sentInvitations": 0,
|
||||
"sentSignals": 1
|
||||
},
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"signaling": {
|
||||
"invitationsForMe": 1,
|
||||
"invitationEvents": 2,
|
||||
"offers": 1,
|
||||
"answers": 2,
|
||||
"sentInvitations": 0,
|
||||
"sentSignals": 1
|
||||
},
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"temporaryWorldChangesRestored": true
|
||||
},
|
||||
"failure": {
|
||||
"stage": "installed-world-playback",
|
||||
"code": "listener-audio-energy-did-not-increase"
|
||||
},
|
||||
"interpretation": "Chromium reported zero inbound RTP energy although later direct Web Audio playback measurements in the installed world were positive with the same module files."
|
||||
},
|
||||
"diagnosticBeforePlaybackMeters": {
|
||||
"inboundStats": [
|
||||
{
|
||||
"bytes": 124880,
|
||||
"energy": 0,
|
||||
"samples": 1558080
|
||||
},
|
||||
{
|
||||
"bytes": 124937,
|
||||
"energy": 0,
|
||||
"samples": 1558080
|
||||
}
|
||||
],
|
||||
"senderEnergy": [
|
||||
4.082235420083857,
|
||||
4.082235420083857
|
||||
],
|
||||
"gmAnalyserRMS": [
|
||||
0.1651397004235531
|
||||
]
|
||||
},
|
||||
"installedWorldPlaybackPass": {
|
||||
"at": "2026-12-04T15:05:54.779Z",
|
||||
"engine": "chromium",
|
||||
"browser": "159.0.8154.6",
|
||||
"accounts": {
|
||||
"gm-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": true,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 0,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
},
|
||||
"player-1-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": false,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 1,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
},
|
||||
"player-2-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": false,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 1,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
}
|
||||
},
|
||||
"playback": {
|
||||
"stage": "passed",
|
||||
"publicKeys": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
],
|
||||
"playerCannotWriteGMFlag": true,
|
||||
"maAPIAuthenticated": true,
|
||||
"sendspinAuthenticated": true,
|
||||
"accountPairingPassed": true,
|
||||
"catalogChoices": 11,
|
||||
"ambient": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.004791336274277526,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.004743247823567246,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"combat": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.12556049134588929,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.1205585037803511,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"ambientOrderRestored": true,
|
||||
"ambientRestoreOffset": {
|
||||
"index": 0,
|
||||
"seconds": 7
|
||||
},
|
||||
"ambientIndexAndOffsetRestored": true,
|
||||
"restoredAmbient": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.0457946358080247,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.04364745631856095,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"onlyDedicatedQueueWritten": true,
|
||||
"afterListenerResume": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.04998535387418037,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.051046648244698796,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"afterListenerReload": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.1276089199898213,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.09472793662374407,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"queueWrites": [
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/clear",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/repeat",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_index",
|
||||
"reply": true,
|
||||
"error": null
|
||||
}
|
||||
],
|
||||
"gmAudioDiagnostics": {
|
||||
"stage": "ready",
|
||||
"state": "connected",
|
||||
"audioContext": "running",
|
||||
"decoded": 1608,
|
||||
"scheduled": 1608,
|
||||
"droppedLate": 0,
|
||||
"droppedAhead": 0,
|
||||
"signalRMS": 0.13149861108647076,
|
||||
"muted": false,
|
||||
"listenerConnections": 2,
|
||||
"volume": 100
|
||||
},
|
||||
"browserAudio": [
|
||||
{
|
||||
"decodedFrames": 1608,
|
||||
"signaling": {
|
||||
"invitationsForMe": 0,
|
||||
"invitationEvents": 0,
|
||||
"offers": 4,
|
||||
"answers": 0,
|
||||
"sentInvitations": 5,
|
||||
"sentSignals": 4
|
||||
},
|
||||
"contexts": [
|
||||
{
|
||||
"state": "running",
|
||||
"time": 35.735510204081635,
|
||||
"track": "live"
|
||||
}
|
||||
],
|
||||
"analyserRMS": [
|
||||
0.2428510186200088
|
||||
],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable",
|
||||
"outgoingEnergy": 4.711130388295272
|
||||
},
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable",
|
||||
"outgoingEnergy": 0.2959549249485192
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"signaling": {
|
||||
"invitationsForMe": 2,
|
||||
"invitationEvents": 5,
|
||||
"offers": 2,
|
||||
"answers": 4,
|
||||
"sentInvitations": 0,
|
||||
"sentSignals": 2
|
||||
},
|
||||
"contexts": [],
|
||||
"analyserRMS": [],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"contexts": [],
|
||||
"analyserRMS": [],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"temporaryWorldChangesRestored": true
|
||||
}
|
||||
},
|
||||
"firefoxInstalledWorldBlocker": "The Firefox build completed WSS probes, but the Foundry join form did not render on this headless or Xvfb host. A WebGL 2 context was unavailable."
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"publicationReady": false,
|
||||
"completedCoreRunPassed": true,
|
||||
"macPrivateRouteVerified": false,
|
||||
"foundryLoggedInWorldVerified": false,
|
||||
"foundryLoggedInWorldVerified": true,
|
||||
"actualMAAuthentication": true,
|
||||
"actualMACatalogPlaylists": 11,
|
||||
"actualMADedicatedProvisioning": true,
|
||||
@@ -87,16 +87,15 @@
|
||||
"networkBoundary": {
|
||||
"sandboxNormalDNS": "public addresses",
|
||||
"operatorMacMAResolution": "private proxy mapping",
|
||||
"sandboxPrivateProxyTCP443": "timeout before TLS",
|
||||
"temporaryAccessRequestPrepared": true,
|
||||
"infrastructureChanged": false
|
||||
"initialUbuntuPrivateProxyTCP443": "timeout before TLS",
|
||||
"followUpUbuntuPrivateProxyTCP443": "verified TLS and installed Foundry browser through operator-scoped firewall access",
|
||||
"infrastructureChangedByTestAgent": false
|
||||
},
|
||||
"remaining": [
|
||||
"operator private-route access and Mac original failure acceptance",
|
||||
"logged-in Foundry hooks, socket and User permission acceptance",
|
||||
"original Mac connection and AM-005 reproduction if the symptom persists",
|
||||
"WAN/30-minute behavior and hardware audibility"
|
||||
],
|
||||
"evidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||
"credentialUseAuthorized": true,
|
||||
"dedicatedReceiverMutationsPerformed": true,
|
||||
"latestCatalogReplayPassed": true,
|
||||
@@ -131,5 +130,9 @@
|
||||
"exactUpstreamResolutionCause": "unconfirmed",
|
||||
"automaticMutationRetries": false
|
||||
},
|
||||
"dedicatedReceiverReconnectPassed": true
|
||||
"dedicatedReceiverReconnectPassed": true,
|
||||
"privateNginxRouteVerifiedFromUbuntu": true,
|
||||
"installedFoundryEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||
"priorBrowserEvidenceScope": "deployed Foundry origin with local source overlay; actual MA, PCM, Web Audio and WebRTC; test-runner signaling, not installed world",
|
||||
"evidenceScope": "Installed Foundry and actual MA over the private Nginx HTTPS route. Two real player accounts used Foundry module signaling and browser-measured WebRTC playback."
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
{
|
||||
"version": "0.7.1",
|
||||
"defect": "AM-006",
|
||||
"publicationReady": false,
|
||||
"completedCoreRunPassed": true,
|
||||
"macPrivateRouteVerified": false,
|
||||
"foundryLoggedInWorldVerified": false,
|
||||
"verifiedGraphicalPreview": {
|
||||
"at": "2026-12-04T15:29:05.529Z",
|
||||
"scope": "private Nginx HTTPS route",
|
||||
"checks": {},
|
||||
"engine": "chromium",
|
||||
"browser": "159.0.8154.6",
|
||||
"moduleAssets": "workspace module assets in the test browser",
|
||||
"accounts": {
|
||||
"gm-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": true,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 0,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
}
|
||||
},
|
||||
"layout": {
|
||||
"resizable": true,
|
||||
"layout": [
|
||||
{
|
||||
"width": 760,
|
||||
"tab": "Connection",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
},
|
||||
{
|
||||
"width": 760,
|
||||
"tab": "Scene Music",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
},
|
||||
{
|
||||
"width": 760,
|
||||
"tab": "Playback",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
},
|
||||
{
|
||||
"width": 380,
|
||||
"tab": "Connection",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
},
|
||||
{
|
||||
"width": 380,
|
||||
"tab": "Scene Music",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
},
|
||||
{
|
||||
"width": 380,
|
||||
"tab": "Playback",
|
||||
"horizontalFit": true,
|
||||
"nestedScroll": false
|
||||
}
|
||||
],
|
||||
"keyboardTabs": true,
|
||||
"advancedCollapsed": true,
|
||||
"invalidAddressRejected": true,
|
||||
"missingTokenRejected": true,
|
||||
"routeDiagnostics": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"opened": true
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"opened": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"completed": true
|
||||
},
|
||||
"regression": {
|
||||
"javascript": 102,
|
||||
"python": 15,
|
||||
"offlineBrowserControls": [
|
||||
"connect",
|
||||
"tabs",
|
||||
"save assignments",
|
||||
"current track",
|
||||
"pause",
|
||||
"resume",
|
||||
"seek",
|
||||
"volume",
|
||||
"stop"
|
||||
]
|
||||
},
|
||||
"remaining": [
|
||||
"verify the packaged candidate after a server-side installation in the development environment",
|
||||
"Mac and WAN acceptance"
|
||||
],
|
||||
"previousInstalledWorldEvidence": "evidence/v0.7.0-foundry-private.json",
|
||||
"verifiedLiveWorkflowPreview": {
|
||||
"at": "2026-12-04T15:32:01.859Z",
|
||||
"scope": "private Nginx HTTPS route",
|
||||
"checks": {
|
||||
"foundryAnonymous": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": false,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-ok"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": []
|
||||
},
|
||||
"maSameOrigin": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": true,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-failed"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": [],
|
||||
"nativeSendspinUpgrade": "upgrade-ok"
|
||||
},
|
||||
"foundryLoggedIn": {
|
||||
"pageStatus": 200,
|
||||
"privatePeerVerified": true,
|
||||
"cspHeaderPresent": false,
|
||||
"reportOnlyCspHeaderPresent": false,
|
||||
"cspMetaPresent": false,
|
||||
"secureContext": true,
|
||||
"pageReplacesWebSocket": false,
|
||||
"upgrades": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"code": "upgrade-ok"
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"code": "upgrade-ok"
|
||||
}
|
||||
],
|
||||
"handshakeReplies": [
|
||||
{
|
||||
"path": "/ws",
|
||||
"httpStatus": 101
|
||||
},
|
||||
{
|
||||
"path": "/sendspin",
|
||||
"httpStatus": 101
|
||||
}
|
||||
],
|
||||
"failedRequests": [],
|
||||
"policyIssues": []
|
||||
}
|
||||
},
|
||||
"engine": "chromium",
|
||||
"browser": "159.0.8154.6",
|
||||
"moduleAssets": "workspace module assets in the test browser",
|
||||
"accounts": {
|
||||
"gm-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": true,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 0,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
},
|
||||
"player-1-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": false,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 1,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
},
|
||||
"player-2-login": {
|
||||
"worldMatches": true,
|
||||
"accountMatches": true,
|
||||
"gm": false,
|
||||
"foundryVersion": "14.371",
|
||||
"system": "dnd5e",
|
||||
"otherActiveGMs": 1,
|
||||
"adaptiveMusicActive": true,
|
||||
"adaptiveMusicVersion": "0.7.0",
|
||||
"canvasTickerPaused": true
|
||||
}
|
||||
},
|
||||
"playback": {
|
||||
"stage": "passed",
|
||||
"publicKeys": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
],
|
||||
"playerCannotWriteGMFlag": true,
|
||||
"advancedInitiallyCollapsed": true,
|
||||
"formRejectedMissingTokenWithoutNetwork": true,
|
||||
"oneClickConnection": true,
|
||||
"maAPIAuthenticated": true,
|
||||
"sendspinAuthenticated": true,
|
||||
"accountPairingPassed": true,
|
||||
"catalogChoices": 11,
|
||||
"sceneAssignmentVerified": true,
|
||||
"ambient": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.008014325143255013,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.007670743474125928,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"combat": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.12679305568945426,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.12893801659879386,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"ambientOrderRestored": true,
|
||||
"ambientRestoreOffset": {
|
||||
"index": 0,
|
||||
"seconds": 8
|
||||
},
|
||||
"ambientIndexAndOffsetRestored": true,
|
||||
"restoredAmbient": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.09003888968411675,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.09750464413094424,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"onlyDedicatedQueueWritten": true,
|
||||
"afterListenerResume": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.0868827545622943,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.09662535253515621,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"afterListenerReload": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.08775154314156451,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.08398555055737364,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"afterPlaybackResume": [
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.10693401545725446,
|
||||
"samplesIncreased": true
|
||||
},
|
||||
{
|
||||
"bytesIncreased": true,
|
||||
"energyIncrease": 0,
|
||||
"playbackRMS": 0.14311589172943934,
|
||||
"samplesIncreased": true
|
||||
}
|
||||
],
|
||||
"playbackTabControls": true,
|
||||
"queueWrites": [
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/clear",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/repeat",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_media",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_index",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/play_index",
|
||||
"reply": true,
|
||||
"error": null
|
||||
},
|
||||
{
|
||||
"command": "player_queues/stop",
|
||||
"reply": true,
|
||||
"error": null
|
||||
}
|
||||
],
|
||||
"gmAudioDiagnostics": {
|
||||
"stage": "ready",
|
||||
"state": "connected",
|
||||
"audioContext": "running",
|
||||
"decoded": 1829,
|
||||
"scheduled": 1829,
|
||||
"droppedLate": 0,
|
||||
"droppedAhead": 0,
|
||||
"signalRMS": 0.12175643489717901,
|
||||
"muted": false,
|
||||
"listenerConnections": 2,
|
||||
"volume": 99
|
||||
},
|
||||
"browserAudio": [
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"signaling": {
|
||||
"invitationsForMe": 0,
|
||||
"invitationEvents": 0,
|
||||
"offers": 4,
|
||||
"answers": 0,
|
||||
"sentInvitations": 4,
|
||||
"sentSignals": 4
|
||||
},
|
||||
"contexts": [
|
||||
{
|
||||
"state": "running",
|
||||
"time": 101.05324263038548,
|
||||
"track": "live"
|
||||
}
|
||||
],
|
||||
"analyserRMS": [
|
||||
0
|
||||
],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable",
|
||||
"outgoingEnergy": 2.5731208355109527
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable",
|
||||
"outgoingEnergy": 0.4176949028255943
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"signaling": {
|
||||
"invitationsForMe": 2,
|
||||
"invitationEvents": 4,
|
||||
"offers": 2,
|
||||
"answers": 4,
|
||||
"sentInvitations": 0,
|
||||
"sentSignals": 2
|
||||
},
|
||||
"contexts": [],
|
||||
"analyserRMS": [],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "closed",
|
||||
"ice": "closed",
|
||||
"signaling": "closed"
|
||||
},
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"decodedFrames": null,
|
||||
"contexts": [],
|
||||
"analyserRMS": [],
|
||||
"browsers": [
|
||||
{
|
||||
"connection": "connected",
|
||||
"ice": "connected",
|
||||
"signaling": "stable"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"temporaryWorldChangesRestored": true
|
||||
},
|
||||
"completed": true
|
||||
},
|
||||
"earlierAttempts": [
|
||||
"The private Foundry vhost served the logged-in application. The Music Assistant vhost completed trusted TLS and supplied no HTTP response before the deadline. The in-window token-free checks opened neither WebSocket.",
|
||||
{
|
||||
"at": "2026-12-04T15:29:22.993Z",
|
||||
"failure": {
|
||||
"stage": "installed-world-playback",
|
||||
"code": "ma-play-media-not-observed"
|
||||
},
|
||||
"restoredWorld": true
|
||||
}
|
||||
],
|
||||
"productionDependencyAudit": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 0,
|
||||
"high": 0,
|
||||
"critical": 0,
|
||||
"total": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": "0.7.2",
|
||||
"publicationReady": false,
|
||||
"completedCoreRunPassed": false,
|
||||
"foundryLoggedInWorldVerified": false,
|
||||
"installedV070GuiReview": {
|
||||
"at": "2026-12-04T15:55:39.842Z",
|
||||
"moduleVersion": "0.7.0",
|
||||
"assetOverrides": false,
|
||||
"injectedRuntimeScripts": false,
|
||||
"manualGuiControls": true,
|
||||
"authenticatedAndConnected": true,
|
||||
"catalogCount": 12,
|
||||
"savedScene": true,
|
||||
"decodedFrames": 299,
|
||||
"passed": true,
|
||||
"reviewScene": "Adaptive Music \u2014 GM review"
|
||||
},
|
||||
"accountPersistence": "Encrypted address and name in a Foundry User Setting. The MA token is required for each new browser session. The server does not host the browser audio relay.",
|
||||
"regression": {
|
||||
"javascript": 104,
|
||||
"python": 15
|
||||
},
|
||||
"candidateAccountSettingVerified": {
|
||||
"scope": "Actual development world, v0.7.2 candidate assets supplied in Playwright only",
|
||||
"firstSession": {
|
||||
"settingScope": "user",
|
||||
"hasEnvelope": true,
|
||||
"connected": true,
|
||||
"manualAddressEntry": true,
|
||||
"addressRestored": true
|
||||
},
|
||||
"newBrowserSession": {
|
||||
"settingScope": "user",
|
||||
"hasEnvelope": true,
|
||||
"connected": true,
|
||||
"manualAddressEntry": false,
|
||||
"addressRestored": true
|
||||
}
|
||||
},
|
||||
"productionDependencyAudit": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 0,
|
||||
"high": 0,
|
||||
"critical": 0,
|
||||
"total": 0
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
"id": "adaptive-music",
|
||||
"title": "Adaptive Music",
|
||||
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.2",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CheddahBoxMB"
|
||||
@@ -24,5 +24,5 @@
|
||||
"socket": true,
|
||||
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
|
||||
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
|
||||
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.0/adaptive-music.zip"
|
||||
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.7.2/adaptive-music.zip"
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// Browser diagnostics on the actual private HTTPS hosts. Records metadata only.
|
||||
import {readFile, stat, writeFile} from 'node:fs/promises';
|
||||
import {lookup} from 'node:dns/promises';
|
||||
import {isIP} from 'node:net';
|
||||
import {resolve} from 'node:path';
|
||||
import {probeWebSockets} from '../src/providers/ma/diagnostics.mjs';
|
||||
|
||||
const report = {at: new Date().toISOString(), scope: 'private Nginx HTTPS route', checks: {}};
|
||||
const playback = process.argv.includes('--playback');
|
||||
const layoutOnly = process.argv.includes('--layout-only');
|
||||
const loggedIn = playback || layoutOnly || process.argv.includes('--logged-in');
|
||||
const engine = process.argv.includes('--firefox') ? 'firefox' : 'chromium';
|
||||
const previewModule = process.argv.includes('--preview-module');
|
||||
const expect = (ok, code) => { if (!ok) throw new Error(code); };
|
||||
|
||||
async function privateJSON(name) {
|
||||
const file = `.local/${name}.json`;
|
||||
expect(((await stat(file)).mode & 0o777) === 0o600, 'private-file-mode');
|
||||
return JSON.parse(await readFile(file, 'utf8'));
|
||||
}
|
||||
|
||||
function httpsOrigin(value) {
|
||||
const url = new URL(value);
|
||||
expect(url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' &&
|
||||
!url.search && !url.hash && (!url.port || url.port === '443') &&
|
||||
/^[a-z0-9.-]+$/i.test(url.hostname) && !isIP(url.hostname), 'invalid-https-origin');
|
||||
return url;
|
||||
}
|
||||
|
||||
async function verifyPrivateResponse(response, origin, proxyIP) {
|
||||
expect(response && new URL(response.url()).origin === origin, 'unexpected-navigation-origin');
|
||||
expect((await response.serverAddr())?.ipAddress === proxyIP, 'unexpected-server-address');
|
||||
expect(await response.securityDetails(), 'missing-tls-details');
|
||||
}
|
||||
|
||||
async function openPrivatePage(page, url, proxyIP) {
|
||||
const response = await page.goto(url.href, {waitUntil: 'domcontentloaded', timeout: 30000});
|
||||
await verifyPrivateResponse(response, url.origin, proxyIP);
|
||||
return response;
|
||||
}
|
||||
|
||||
async function retainBrowserWebSocket(page) {
|
||||
await page.addInitScript(() => {
|
||||
Object.defineProperty(window, '__adaptiveMusicProbeNativeSocket', {value: window.WebSocket});
|
||||
});
|
||||
}
|
||||
|
||||
async function collectTransport(page, response, ma) {
|
||||
const headers = await response.allHeaders();
|
||||
const session = engine === 'chromium' ? await page.context().newCDPSession(page) : null;
|
||||
const requests = new Map();
|
||||
const socketResults = [];
|
||||
const failedRequests = [];
|
||||
const policyIssues = [];
|
||||
session?.on('Network.webSocketCreated', ({requestId, url}) => {
|
||||
for (const path of ['/ws', '/sendspin']) {
|
||||
if (url === `wss://${ma.host}${path}`) requests.set(requestId, path);
|
||||
}
|
||||
});
|
||||
session?.on('Network.webSocketHandshakeResponseReceived', ({requestId, response}) => {
|
||||
if (requests.has(requestId)) socketResults.push({path: requests.get(requestId), httpStatus: response.status});
|
||||
});
|
||||
session?.on('Network.loadingFailed', ({requestId, errorText, blockedReason}) => {
|
||||
if (!requests.has(requestId)) return;
|
||||
const error = /^net::ERR_[A-Z0-9_]+$/.test(errorText) ? errorText : null;
|
||||
failedRequests.push({path: requests.get(requestId), error, blockedReason: blockedReason ?? null});
|
||||
});
|
||||
session?.on('Network.webSocketFrameError', ({requestId, errorMessage}) => {
|
||||
if (!requests.has(requestId)) return;
|
||||
const status = errorMessage?.match(/Unexpected response code: (\d{3})/);
|
||||
const error = errorMessage?.match(/\bnet::ERR_[A-Z0-9_]+\b/);
|
||||
if (status || error) failedRequests.push({path: requests.get(requestId), httpStatus: status ? Number(status[1]) : null, error: error?.[0] ?? null});
|
||||
});
|
||||
session?.on('Audits.issueAdded', ({issue}) => {
|
||||
const detail = issue.details?.corsIssueDetails ?? issue.details?.contentSecurityPolicyIssueDetails;
|
||||
const url = detail?.request?.url ?? detail?.blockedURL;
|
||||
if (!URL.canParse(url) || ![ma.origin, `wss://${ma.host}`].includes(new URL(url).origin)) return;
|
||||
policyIssues.push({code: issue.code, reason: detail.corsErrorStatus?.corsError ?? detail.contentSecurityPolicyViolationType});
|
||||
});
|
||||
try {
|
||||
await session?.send('Network.enable');
|
||||
await session?.send('Audits.enable');
|
||||
const details = {
|
||||
pageStatus: response.status(),
|
||||
privatePeerVerified: true,
|
||||
cspHeaderPresent: Boolean(headers['content-security-policy']),
|
||||
reportOnlyCspHeaderPresent: Boolean(headers['content-security-policy-report-only']),
|
||||
cspMetaPresent: await page.locator('meta[http-equiv="Content-Security-Policy" i]').count() > 0,
|
||||
secureContext: await page.evaluate(() => globalThis.isSecureContext),
|
||||
pageReplacesWebSocket: await page.evaluate(() => window.WebSocket !== window.__adaptiveMusicProbeNativeSocket),
|
||||
upgrades: await page.evaluate(probeWebSockets, ma.origin),
|
||||
handshakeReplies: socketResults,
|
||||
failedRequests,
|
||||
policyIssues,
|
||||
};
|
||||
if (details.pageReplacesWebSocket) {
|
||||
details.nativeSendspinUpgrade = await page.evaluate(host => new Promise(resolve => {
|
||||
const socket = new window.__adaptiveMusicProbeNativeSocket(`wss://${host}/sendspin`);
|
||||
const timer = setTimeout(() => finish('upgrade-timeout'), 5000);
|
||||
function finish(code) {
|
||||
clearTimeout(timer);
|
||||
socket.onopen = socket.onerror = socket.onclose = null;
|
||||
socket.close();
|
||||
resolve(code);
|
||||
}
|
||||
socket.onopen = () => finish('upgrade-ok');
|
||||
socket.onerror = socket.onclose = () => finish('upgrade-failed');
|
||||
}), ma.host);
|
||||
}
|
||||
return details;
|
||||
} finally {
|
||||
await session?.detach();
|
||||
}
|
||||
}
|
||||
|
||||
async function joinWorld(browser, foundry, proxyIP, world, {name, gm, password}, progress) {
|
||||
expect(typeof name === 'string' && name && typeof password === 'string' && typeof gm === 'boolean', 'invalid-test-account');
|
||||
const page = await browser.newPage({viewport: {width: 1440, height: 1000}, screen: {width: 1440, height: 1000}});
|
||||
if (previewModule) {
|
||||
const prefix='/modules/adaptive-music/';
|
||||
const root=resolve(import.meta.dirname,'..');
|
||||
await page.context().route(`${foundry.origin}${prefix}**`,async route=>{
|
||||
const file=new URL(route.request().url()).pathname.slice(prefix.length);
|
||||
if(!/^(src\/.+\.mjs|styles\/.+\.css|vendor\/.+\.mjs)$/.test(file)||file.split('/').includes('..'))return route.continue();
|
||||
await route.fulfill({path:resolve(root,file),contentType:file.endsWith('.css')?'text/css':'text/javascript'});
|
||||
});
|
||||
}
|
||||
page.setDefaultTimeout(20000);
|
||||
await retainBrowserWebSocket(page);
|
||||
if (playback) await page.addInitScript(() => {
|
||||
const peers = [];
|
||||
const contexts = [];
|
||||
const analysers = [];
|
||||
const listenerAnalysers = [];
|
||||
window.__adaptiveMusicTestAudio = {contexts, analysers, listenerAnalysers};
|
||||
const createStream = AudioContext.prototype.createMediaStreamDestination;
|
||||
AudioContext.prototype.createMediaStreamDestination = function () {
|
||||
const destination = createStream.call(this);
|
||||
contexts.push({context: this, destination});
|
||||
return destination;
|
||||
};
|
||||
const createAnalyser = AudioContext.prototype.createAnalyser;
|
||||
AudioContext.prototype.createAnalyser = function () {
|
||||
const analyser = createAnalyser.call(this);
|
||||
analysers.push(analyser);
|
||||
return analyser;
|
||||
};
|
||||
const createSource = AudioContext.prototype.createMediaStreamSource;
|
||||
AudioContext.prototype.createMediaStreamSource = function (stream) {
|
||||
const source = createSource.call(this, stream);
|
||||
const analyser = createAnalyser.call(this);
|
||||
source.connect(analyser);
|
||||
listenerAnalysers.push({context: this, stream, analyser});
|
||||
return source;
|
||||
};
|
||||
window.__adaptiveMusicTestPeers = peers;
|
||||
window.RTCPeerConnection = new Proxy(window.RTCPeerConnection, {
|
||||
construct(target, args, newTarget) {
|
||||
const peer = Reflect.construct(target, args, newTarget);
|
||||
peers.push(peer);
|
||||
return peer;
|
||||
},
|
||||
});
|
||||
});
|
||||
const url = new URL('/join', foundry);
|
||||
progress('join-page');
|
||||
await openPrivatePage(page, url, proxyIP);
|
||||
await page.getByText(world.title, {exact: true}).first().waitFor({timeout: 30000});
|
||||
expect(new URL(page.url()).pathname === '/join', 'unexpected-join-path');
|
||||
|
||||
progress('select-account');
|
||||
const form = page.locator('#join-game-form');
|
||||
const users = form.locator('select[name="userId"]');
|
||||
await users.waitFor({state: 'visible'});
|
||||
const option = await users.evaluate((select, name) => {
|
||||
const user = [...select.options].find(option => option.label === name);
|
||||
return user ? {value: user.value, disabled: user.disabled} : null;
|
||||
}, name);
|
||||
expect(option?.value, 'development-account-not-found');
|
||||
expect(!option.disabled, 'development-account-unavailable');
|
||||
await users.selectOption({value: option.value});
|
||||
await form.locator('input[type="password"]').fill(password);
|
||||
progress('submit-join');
|
||||
const navigation = page.waitForResponse(response => response.request().isNavigationRequest() &&
|
||||
response.request().frame() === page.mainFrame() && new URL(response.url()).pathname === '/game');
|
||||
const [response] = await Promise.all([navigation, form.locator('[type="submit"]').click()]);
|
||||
await verifyPrivateResponse(response, foundry.origin, proxyIP);
|
||||
progress('wait-for-game-ready');
|
||||
await page.bringToFront();
|
||||
await page.waitForFunction(() => globalThis.game?.ready && game.socket?.connected, undefined, {polling: 250, timeout: 55000});
|
||||
const state = await page.evaluate(({id, title, account}) => ({
|
||||
worldMatches: game.world.id === id && game.world.title === title,
|
||||
accountMatches: game.user.name === account,
|
||||
gm: game.user.isGM,
|
||||
foundryVersion: game.version,
|
||||
system: game.system.id,
|
||||
otherActiveGMs: game.users.filter(user => user.id !== game.user.id && user.active && user.isGM).length,
|
||||
adaptiveMusicActive: game.modules.get('adaptive-music')?.active === true,
|
||||
adaptiveMusicVersion: game.modules.get('adaptive-music')?.version ?? null,
|
||||
}), {id: world.id, title: world.title, account: name});
|
||||
expect(state.worldMatches && state.accountMatches && state.gm === gm, 'unexpected-world-account-or-role');
|
||||
expect(state.foundryVersion === '14.371' && state.system === 'dnd5e', 'unexpected-foundry-or-system');
|
||||
expect(state.otherActiveGMs === (state.gm ? 0 : 1), 'unexpected-active-gm-count');
|
||||
expect(state.adaptiveMusicActive, 'adaptive-music-inactive');
|
||||
// Keep the unattended canvases from saturating the shared headless renderer.
|
||||
state.canvasTickerPaused = await page.evaluate(() => {
|
||||
const ticker = globalThis.canvas?.app?.ticker;
|
||||
if (!ticker?.started) return false;
|
||||
ticker.stop();
|
||||
return true;
|
||||
});
|
||||
return {page, response, state};
|
||||
}
|
||||
|
||||
let browser, stage = 'configuration';
|
||||
try {
|
||||
const config = await privateJSON('live-environment');
|
||||
const foundry = httpsOrigin(config.foundry), ma = httpsOrigin(config.ma);
|
||||
const proxyIP = config.proxy_ip;
|
||||
expect(isIP(proxyIP) === 4 && foundry.host !== ma.host, 'invalid-private-route');
|
||||
const playwright = await import(process.env.AM_PLAYWRIGHT_MODULE ?? 'playwright');
|
||||
stage = 'browser-launch';
|
||||
if (engine === 'firefox') {
|
||||
for (const host of [foundry.hostname, ma.hostname]) {
|
||||
const answers = await lookup(host, {all: true});
|
||||
expect(answers.length && answers.every(answer => answer.address === proxyIP), 'private-hostname-resolution-required');
|
||||
}
|
||||
}
|
||||
browser = await playwright[engine].launch(engine === 'chromium' ? {args: ['--no-sandbox', '--no-proxy-server',
|
||||
`--host-resolver-rules=MAP ${foundry.hostname} ${proxyIP}, MAP ${ma.hostname} ${proxyIP}`]} :
|
||||
{firefoxUserPrefs: {'network.trr.mode': 5, 'network.proxy.type': 0}});
|
||||
report.engine = engine;
|
||||
report.browser = browser.version();
|
||||
report.moduleAssets = previewModule ? 'workspace module assets in the test browser' : 'installed module assets';
|
||||
|
||||
for (const [name, origin] of (layoutOnly ? [] : [['foundryAnonymous', foundry], ['maSameOrigin', ma]])) {
|
||||
stage = name;
|
||||
const page = await browser.newPage();
|
||||
await retainBrowserWebSocket(page);
|
||||
const response = await openPrivatePage(page, origin, proxyIP);
|
||||
report.checks[name] = await collectTransport(page, response, ma);
|
||||
await page.context().close();
|
||||
}
|
||||
|
||||
if (loggedIn) {
|
||||
stage = 'development-world-configuration';
|
||||
const {world, accounts} = await privateJSON('foundry-development');
|
||||
expect(typeof world?.id === 'string' && world.id && typeof world.title === 'string' && world.title &&
|
||||
Array.isArray(accounts) && accounts.length === 3 && accounts.every((account, index) => account?.gm === (index === 0)) &&
|
||||
new Set(accounts.map(account => account.name)).size === 3, 'invalid-development-world-configuration');
|
||||
report.accounts = {};
|
||||
const pages = [];
|
||||
for (const [index, account] of (layoutOnly ? accounts.slice(0,1) : accounts).entries()) {
|
||||
const login = index === 0 ? 'gm-login' : `player-${index}-login`;
|
||||
const {page, response, state} = await joinWorld(browser, foundry, proxyIP, world, account, step => {
|
||||
stage = `${login}-${step}`;
|
||||
console.error(`Development world authentication stage: ${stage}`);
|
||||
});
|
||||
report.accounts[login] = state;
|
||||
pages.push(page);
|
||||
if (index === 0 && !layoutOnly) {
|
||||
stage = 'foundryLoggedIn';
|
||||
report.checks[stage] = await collectTransport(page, response, ma);
|
||||
}
|
||||
}
|
||||
if(layoutOnly){
|
||||
stage='foundry-graphical-layout';
|
||||
const {checkFoundryLayout}=await import('./live_foundry_playback.mjs');
|
||||
report.layout=await checkFoundryLayout(pages[0],ma);
|
||||
}
|
||||
if (playback) {
|
||||
stage = 'installed-world-playback';
|
||||
const {checkFoundryPlayback} = await import('./live_foundry_playback.mjs');
|
||||
report.playback = {};
|
||||
await checkFoundryPlayback({pages, ma, world, report: report.playback});
|
||||
}
|
||||
}
|
||||
report.completed = true;
|
||||
} catch (error) {
|
||||
report.completed = false;
|
||||
report.failure = {stage, code: /^[a-z][a-z-]+$/.test(error.message) ? error.message : error.code ?? error.name};
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await browser?.close();
|
||||
const resultName=previewModule?`foundry-am006-preview-${engine}`:`foundry-private-route-${engine}`;
|
||||
await writeFile(`.local/${resultName}.json`, JSON.stringify(report, null, 2) + '\n', {mode: 0o600});
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
}
|
||||
@@ -14,16 +14,24 @@ try{
|
||||
for(const width of [380,640,1000]){
|
||||
await page.setViewportSize({width,height:1000});
|
||||
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.getByRole('button',{name:'Connect audio',exact:true}).isVisible(),false,'hidden steps 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.getByRole('button',{name:'Authenticate',exact:true}).click();await page.getByText('Authenticated. Connect this dedicated campaign receiver',{exact:false}).waitFor();
|
||||
await page.getByRole('button',{name:'Connect',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
|
||||
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
|
||||
await page.getByRole('button',{name:'Connect audio',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
|
||||
await page.getByRole('button',{name:'Choose scene music',exact:true}).click();
|
||||
const panel=page.locator('fieldset').filter({has:page.locator('legend',{hasText:'Scene music'})});
|
||||
await panel.locator('select').nth(0).selectOption('["ma","ambient"]');await panel.locator('select').nth(1).selectOption('["ma","combat"]');await panel.getByRole('button',{name:'Save assignments'}).click();
|
||||
assert.deepEqual(await page.evaluate(()=>window.saved.ambient),{provider:'ma',id:'ambient'});assert.deepEqual(await page.evaluate(()=>window.saved.combat),{provider:'ma',id:'combat'});
|
||||
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.locator('.adaptive-music-setup').evaluate(el=>el.scrollTop=0);await page.screenshot({path:resolve(root,'dist/previews/v0.7.0-setup.png'),fullPage:true});
|
||||
await page.getByRole('button',{name:'Go to Playback',exact:true}).click();await page.getByRole('heading',{name:'Forest at night'}).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.getByLabel('Playback position').press('ArrowRight');await page.getByText('0:13 / 1:30',{exact:true}).waitFor();
|
||||
await page.getByLabel('Campaign volume').press('ArrowLeft');
|
||||
assert.equal(await page.getByLabel('Campaign volume').inputValue(),'99');
|
||||
await page.getByRole('button',{name:'Stop playback',exact:true}).click();await page.getByText('Stopped',{exact:true}).waitFor();
|
||||
assert.deepEqual(await page.evaluate(()=>window.controlActions),['pause','resume','seek','stop']);
|
||||
await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-setup.png'),fullPage:true});
|
||||
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
|
||||
console.log(JSON.stringify({status:'pass',browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','hidden steps','wizard render','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','listener activation'],pageErrors:errors},null,2));
|
||||
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));
|
||||
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
|
||||
@@ -0,0 +1,458 @@
|
||||
// Exercises the installed module through the authorized development world.
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import {loadMAToken} from '../gateway/private-config.mjs';
|
||||
|
||||
const moduleId = 'adaptive-music';
|
||||
const check = (value, code) => { if (!value) throw new Error(code); };
|
||||
|
||||
async function until(read, accept, code, timeout = 25000) {
|
||||
const end = Date.now() + timeout;
|
||||
do {
|
||||
const result = await read();
|
||||
if (accept(result)) return result;
|
||||
await delay(300);
|
||||
} while (Date.now() < end);
|
||||
throw new Error(code);
|
||||
}
|
||||
|
||||
function observeMA(page, ma) {
|
||||
const commands = [];
|
||||
let sendspinAuthenticated = false;
|
||||
const json = event => {
|
||||
if (typeof event.payload !== 'string') return null;
|
||||
try { return JSON.parse(event.payload); } catch { return null; }
|
||||
};
|
||||
page.on('websocket', socket => {
|
||||
if (socket.url() === `wss://${ma.host}/sendspin`) {
|
||||
socket.on('framereceived', event => {
|
||||
if (json(event)?.type === 'auth_ok') sendspinAuthenticated = true;
|
||||
});
|
||||
}
|
||||
if (socket.url() !== `wss://${ma.host}/ws`) return;
|
||||
const pending = new Map();
|
||||
socket.on('framesent', event => {
|
||||
const frame = json(event);
|
||||
if (!frame?.message_id || typeof frame.command !== 'string') return;
|
||||
const entry = {command: frame.command, args: frame.command.startsWith('player_queues/') ? frame.args : null};
|
||||
commands.push(entry);
|
||||
pending.set(frame.message_id, entry);
|
||||
});
|
||||
socket.on('framereceived', event => {
|
||||
const frame = json(event);
|
||||
const entry = pending.get(frame?.message_id);
|
||||
if (!entry || frame.partial) return;
|
||||
pending.delete(frame.message_id);
|
||||
entry.reply = true;
|
||||
entry.error = frame.error_code ?? null;
|
||||
if (entry.command === 'auth') entry.authenticated = frame.result?.authenticated === true;
|
||||
if (entry.command === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
|
||||
if (entry.command === 'player_queues/get' && frame.result) {
|
||||
const {state, current_index, elapsed_time} = frame.result;
|
||||
entry.queue = {state, index: current_index, position: elapsed_time};
|
||||
}
|
||||
});
|
||||
});
|
||||
return {commands, sendspinAuthenticated: () => sendspinAuthenticated};
|
||||
}
|
||||
|
||||
function safeStats(page) {
|
||||
return page.evaluate(async moduleId => {
|
||||
const stats = await game.modules.get(moduleId).api.peerStats();
|
||||
const streams = [...document.querySelectorAll('audio')].map(element => element.srcObject).filter(Boolean);
|
||||
const rms = (window.__adaptiveMusicTestAudio?.listenerAnalysers ?? []).filter(sensor => streams.includes(sensor.stream))
|
||||
.reduce((max, {analyser}) => {
|
||||
const samples = new Float32Array(analyser.fftSize);
|
||||
analyser.getFloatTimeDomainData(samples);
|
||||
return Math.max(max, Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length));
|
||||
}, 0);
|
||||
return stats.filter(row => row.type === 'inbound-rtp').reduce((result, row) => ({
|
||||
rms,
|
||||
bytes: result.bytes + (row.bytesReceived ?? 0),
|
||||
energy: result.energy + (row.totalAudioEnergy ?? 0),
|
||||
samples: result.samples + (row.totalSamplesReceived ?? 0),
|
||||
}), {rms, bytes: 0, energy: 0, samples: 0});
|
||||
}, moduleId);
|
||||
}
|
||||
|
||||
async function gmAudioDiagnostics(page, setup) {
|
||||
await page.evaluate(() => {
|
||||
Object.defineProperty(navigator.clipboard, 'writeText', {
|
||||
configurable: true,
|
||||
value: async text => { window.__adaptiveMusicTestDiagnostics = JSON.parse(text); },
|
||||
});
|
||||
});
|
||||
await setup.getByRole('button', {name: 'Copy connection diagnostics', exact: true}).click({timeout: 3000});
|
||||
return page.evaluate(() => {
|
||||
const d = window.__adaptiveMusicTestDiagnostics;
|
||||
if (!d) return null;
|
||||
return {
|
||||
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
|
||||
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead,
|
||||
signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
|
||||
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function openMenu(page, name) {
|
||||
await page.evaluate(async key => {
|
||||
const type = game.settings.menus.get(key)?.type;
|
||||
if (!type) throw Error('missing-installed-module-menu');
|
||||
const app=new type();
|
||||
await app.render({force: true});
|
||||
window.__adaptiveTestWindow=app;
|
||||
}, `${moduleId}.${name}`);
|
||||
}
|
||||
|
||||
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat'].map(action => 'player_queues/' + action));
|
||||
|
||||
export async function checkFoundryLayout(page,ma){
|
||||
await openMenu(page,'setup');
|
||||
const setup=page.locator('#adaptive-music-setup');
|
||||
const tabs=setup.getByRole('tab');
|
||||
check(await tabs.count()===3,'three-foundry-tabs-required');
|
||||
const resizable=await page.evaluate(()=>window.__adaptiveTestWindow.options.window.resizable);
|
||||
check(resizable===true,'foundry-window-not-resizable');
|
||||
const originalWidth=Math.round((await setup.boundingBox()).width);
|
||||
const layout=[];
|
||||
for(const width of [originalWidth,380]){
|
||||
await page.evaluate(width=>window.__adaptiveTestWindow.setPosition({width,height:490}),width);
|
||||
for(const label of ['Connection','Scene Music','Playback']){
|
||||
await setup.getByRole('tab',{name:label,exact:true}).click();
|
||||
const panel=setup.getByRole('tabpanel');
|
||||
await panel.waitFor({state:'visible'});
|
||||
const measurements=await panel.evaluate(el=>{
|
||||
const content=el.closest('.window-content');
|
||||
const horizontalFit=el.scrollWidth<=el.clientWidth+1&&content.scrollWidth<=content.clientWidth+1;
|
||||
const nestedScroll=[...content.querySelectorAll('div,section,details,fieldset')].some(node=>['auto','scroll'].includes(getComputedStyle(node).overflowY));
|
||||
return {horizontalFit,nestedScroll};
|
||||
});
|
||||
check(measurements.horizontalFit&&!measurements.nestedScroll,'foundry-layout-overflow');
|
||||
layout.push({width,tab:label,...measurements});
|
||||
}
|
||||
}
|
||||
await setup.getByRole('tab',{name:'Connection',exact:true}).press('ArrowRight');
|
||||
check(await setup.getByRole('tabpanel',{name:'Scene Music'}).isVisible(),'tab-keyboard-navigation-failed');
|
||||
await setup.getByRole('tab',{name:'Connection',exact:true}).click();
|
||||
const advanced=setup.getByText('Advanced',{exact:true});
|
||||
check(!await setup.getByLabel('ICE server URL').isVisible(),'advanced-visible-by-default');
|
||||
await advanced.click();
|
||||
check(await setup.getByLabel('ICE server URL').isVisible(),'advanced-controls-unreachable');
|
||||
await advanced.click();
|
||||
await setup.getByLabel('Music Assistant server address').fill('https://ma.example.test/path');
|
||||
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||
await setup.getByRole('alert').filter({hasText:'Enter the MA server origin'}).waitFor();
|
||||
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
|
||||
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
|
||||
await setup.getByRole('button',{name:'Check browser connection',exact:true}).click();
|
||||
await setup.getByText('Browser checks complete.',{exact:true}).waitFor();
|
||||
const routeDiagnostics=await setup.locator('[aria-live="polite"] p').evaluateAll(lines=>lines.map(line=>({
|
||||
path:line.textContent.startsWith('/ws')?'/ws':'/sendspin',opened:line.textContent.includes('upgrade succeeded'),
|
||||
})));
|
||||
check(routeDiagnostics.length===2,'missing-graphical-route-diagnostics');
|
||||
return {resizable,layout,keyboardTabs:true,advancedCollapsed:true,invalidAddressRejected:true,missingTokenRejected:true,routeDiagnostics};
|
||||
}
|
||||
|
||||
export async function checkFoundryPlayback({pages, ma, world, report}) {
|
||||
const [gm, ...players] = pages;
|
||||
const run = randomUUID().slice(0, 8);
|
||||
const receiverName = `Adaptive Music integration ${run}`;
|
||||
const fixtureName = `Adaptive Music verification ${run}`;
|
||||
const setup = gm.locator('#adaptive-music-setup');
|
||||
const wire = observeMA(gm, ma);
|
||||
const stage = name => {
|
||||
report.stage = name;
|
||||
console.error(`Installed-world playback stage: ${name}`);
|
||||
};
|
||||
let baseline, sceneId, combatId, receiver;
|
||||
|
||||
const fixture = data => gm.evaluate(async ({world, moduleId, ...data}) => {
|
||||
if (!game.ready || game.world.id !== world || !game.user.isGM || !game.socket?.connected) throw Error('wrong-development-world');
|
||||
if (data.action === 'scene') {
|
||||
const scene = await CONFIG.Scene.documentClass.create({name: data.fixtureName, width: 1200, height: 1000, navigation: false, tokenVision: false});
|
||||
return scene.id;
|
||||
}
|
||||
if (data.action === 'combat') {
|
||||
const combat = await CONFIG.Combat.documentClass.create({scene: data.sceneId, active: true});
|
||||
await combat.createEmbeddedDocuments('Combatant', [{name: data.fixtureName, initiative: 12}]);
|
||||
return combat.id;
|
||||
}
|
||||
if (data.action === 'start-combat') {
|
||||
const combat = game.combats.get(data.combatId);
|
||||
await combat.startCombat();
|
||||
return Boolean(combat.started && combat.active);
|
||||
}
|
||||
if (data.action === 'delete-combat') return game.combats.get(data.combatId)?.delete().then(() => true);
|
||||
if (data.action === 'activate-scene') return game.scenes.get(data.sceneId)?.activate().then(() => true);
|
||||
if (data.action === 'baseline') {
|
||||
const enabled = game.settings.get(moduleId, 'enabled');
|
||||
const scene = game.scenes.active?.id ?? null;
|
||||
if (enabled) {
|
||||
game.modules.get(moduleId).api.stopDevelopment();
|
||||
await game.settings.set(moduleId, 'enabled', false);
|
||||
}
|
||||
return {enabled, scene};
|
||||
}
|
||||
if (data.action === 'cleanup') {
|
||||
const api = game.modules.get(moduleId).api;
|
||||
api.stopDevelopment();
|
||||
await api.closeGMHost();
|
||||
if (data.combatId) await game.combats.get(data.combatId)?.delete();
|
||||
if (data.baseline.scene && game.scenes.active?.id !== data.baseline.scene) await game.scenes.get(data.baseline.scene)?.activate();
|
||||
if (data.sceneId) await game.scenes.get(data.sceneId)?.delete();
|
||||
if (game.settings.get(moduleId, 'enabled') !== data.baseline.enabled) await game.settings.set(moduleId, 'enabled', data.baseline.enabled);
|
||||
return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
|
||||
game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
|
||||
}
|
||||
throw Error('unknown-fixture-operation');
|
||||
}, {world: world.id, moduleId, ...data});
|
||||
|
||||
const command = (from, name, predicate = () => true) => until(
|
||||
() => wire.commands.slice(from).find(entry => entry.command === `player_queues/${name}` && entry.reply && predicate(entry.args)),
|
||||
Boolean, `ma-${name.replaceAll('_', '-')}-not-observed`, 70000).then(entry => {
|
||||
if (entry.error !== null) report.upstreamError = {command: entry.command, code: entry.error};
|
||||
check(entry.error === null, 'ma-queue-command-failed');
|
||||
return entry;
|
||||
});
|
||||
|
||||
const audio = async () => {
|
||||
const before = await Promise.all(players.map(safeStats));
|
||||
try {
|
||||
return await Promise.all(players.map(async (page, index) => {
|
||||
const after = await until(() => safeStats(page), value => value.bytes > before[index].bytes &&
|
||||
(value.energy - before[index].energy > 1e-6 || value.rms > 0.001),
|
||||
'listener-audio-energy-did-not-increase', 30000);
|
||||
return {bytesIncreased: true, energyIncrease: after.energy - before[index].energy, playbackRMS: after.rms,
|
||||
samplesIncreased: after.samples > before[index].samples};
|
||||
}));
|
||||
} catch (error) {
|
||||
report.listenerStatsAtFailure = await Promise.all(players.map(page => safeStats(page).catch(() => null)));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
stage('world-readiness');
|
||||
await gm.waitForFunction(({moduleId, count}) => game.modules.get(moduleId)?.api &&
|
||||
[...game.users].filter(user => user.active && !user.isGM).length >= count &&
|
||||
[...game.users].filter(user => user.active && user.isGM).length === 1, {moduleId, count: players.length});
|
||||
report.publicKeys = await Promise.all(pages.map(page => page.waitForFunction(moduleId => Boolean(game.user.getFlag(moduleId, 'audioPublicKey')?.key), moduleId, {timeout: 8000}).then(() => true, () => false)));
|
||||
await Promise.all(pages.map(page => page.evaluate(() => {
|
||||
const tally = {invitationsForMe: 0, invitationEvents: 0, offers: 0, answers: 0, sentInvitations: 0, sentSignals: 0};
|
||||
window.__adaptiveMusicTestSignaling = tally;
|
||||
game.socket.on('module.adaptive-music', frame => {
|
||||
if (frame?.type === 'audio-invite-v1') {
|
||||
tally.invitationEvents++;
|
||||
if (frame.to === game.user.id) tally.invitationsForMe++;
|
||||
}
|
||||
if (frame?.v === 1 && frame.from === 'listener') tally.offers++;
|
||||
if (frame?.v === 1 && frame.from === 'gm') tally.answers++;
|
||||
});
|
||||
game.socket.onAnyOutgoing?.((event, frame) => {
|
||||
if (event !== 'module.adaptive-music') return;
|
||||
if (frame?.type === 'audio-invite-v1') tally.sentInvitations++;
|
||||
if (frame?.v === 1 && typeof frame.cipher === 'string') tally.sentSignals++;
|
||||
});
|
||||
})));
|
||||
|
||||
stage('user-document-permissions');
|
||||
const gmId = await gm.evaluate(() => game.user.id);
|
||||
const probeFlag = `integrationProbe${run}`;
|
||||
report.playerCannotWriteGMFlag = await players[0].evaluate(async ({gmId, moduleId, probeFlag}) => {
|
||||
try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
|
||||
catch { return true; }
|
||||
}, {gmId, moduleId, probeFlag});
|
||||
if (!report.playerCannotWriteGMFlag) await gm.evaluate(({moduleId, probeFlag}) => game.user.unsetFlag(moduleId, probeFlag), {moduleId, probeFlag});
|
||||
|
||||
stage('create-test-scene');
|
||||
baseline = await fixture({action: 'baseline'});
|
||||
sceneId = await fixture({action: 'scene', fixtureName});
|
||||
await fixture({action: 'activate-scene', sceneId});
|
||||
await openMenu(gm, 'setup');
|
||||
await gm.evaluate(()=>{
|
||||
window.__adaptiveTestNotifications=[];
|
||||
const observer=new MutationObserver(()=>{
|
||||
for(const node of document.querySelectorAll('#notifications .notification')){
|
||||
const text=node.textContent.trim();
|
||||
if(text.startsWith('Adaptive Music: ')&&!window.__adaptiveTestNotifications.includes(text))window.__adaptiveTestNotifications.push(text);
|
||||
}
|
||||
});
|
||||
observer.observe(document.body,{childList:true,subtree:true});
|
||||
});
|
||||
|
||||
stage('ma-authentication');
|
||||
const tabbed=await setup.getByRole('tab',{name:'Connection',exact:true}).count()>0;
|
||||
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
|
||||
if(tabbed){
|
||||
const before=wire.commands.length;
|
||||
report.advancedInitiallyCollapsed=!await setup.getByLabel('ICE server URL').isVisible();
|
||||
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
|
||||
report.formRejectedMissingTokenWithoutNetwork=wire.commands.length===before;
|
||||
check(report.formRejectedMissingTokenWithoutNetwork&&report.advancedInitiallyCollapsed,'connection-form-validation-failed');
|
||||
await setup.getByText('Advanced',{exact:true}).click();
|
||||
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
|
||||
await setup.getByText('Advanced',{exact:true}).click();
|
||||
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
|
||||
await setup.getByRole('button',{name:'Connect',exact:true}).click();
|
||||
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:50000});
|
||||
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
|
||||
check(receiver,'receiver-identity-not-verified');
|
||||
report.oneClickConnection=true;
|
||||
await setup.getByRole('button',{name:'Choose scene music'}).click();
|
||||
}else{
|
||||
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
|
||||
await setup.getByText('Receiver options',{exact:true}).click();
|
||||
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
|
||||
await setup.getByRole('button',{name:'Authenticate',exact:true}).click();
|
||||
const selector=setup.getByLabel('Dedicated campaign receiver');
|
||||
await selector.locator('option').filter({hasText:receiverName}).waitFor({state:'attached',timeout:25000});
|
||||
receiver=await selector.inputValue();
|
||||
await setup.getByRole('button',{name:'Connect audio',exact:true}).click();
|
||||
}
|
||||
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
|
||||
check(receiver && report.maAPIAuthenticated, 'receiver-identity-not-verified');
|
||||
|
||||
stage('dedicated-sendspin-connection');
|
||||
if(!tabbed)await setup.getByText(/^Campaign audio connected\./).waitFor({timeout: 50000});
|
||||
report.sendspinAuthenticated = wire.sendspinAuthenticated();
|
||||
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
|
||||
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
|
||||
|
||||
stage('scene-assignments');
|
||||
const assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
|
||||
const ambient = assignments.getByLabel('Ambient playlist');
|
||||
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",')));
|
||||
report.catalogChoices = references.length;
|
||||
check(references.length >= 2, 'insufficient-ma-catalog-choices');
|
||||
await ambient.selectOption(references[0]);
|
||||
await assignments.getByLabel('Combat playlist').selectOption(references[1]);
|
||||
if(tabbed)await assignments.getByLabel('Default boss music').selectOption(references[1]);
|
||||
await assignments.getByRole('button', {name: 'Save assignments', exact: true}).click();
|
||||
await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
|
||||
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{
|
||||
const scene=game.scenes.get(sceneId);
|
||||
return scene?.active===true&&JSON.stringify(['ma',scene.getFlag('adaptive-music','music')?.ambient?.id])===ambient;
|
||||
},{sceneId,ambient:references[0]});
|
||||
check(report.sceneAssignmentVerified,'assignment-not-saved-to-active-scene');
|
||||
|
||||
stage('activate-listener-audio');
|
||||
await Promise.all(players.map(async page => {
|
||||
await openMenu(page, 'listen');
|
||||
await page.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||
}));
|
||||
|
||||
stage('ambient');
|
||||
const start = wire.commands.length;
|
||||
if(tabbed){
|
||||
await setup.getByRole('button',{name:'Go to Playback'}).click();
|
||||
await setup.getByRole('button',{name:'Enable automation'}).click();
|
||||
await setup.getByText('Automation active',{exact:true}).waitFor({timeout:10000});
|
||||
}else{
|
||||
await setup.getByLabel('Enable music automation').check();
|
||||
await setup.getByRole('button',{name:'Apply automation setting',exact:true}).click();
|
||||
}
|
||||
const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
|
||||
report.ambient = await audio();
|
||||
await delay(6500);
|
||||
|
||||
stage('actual-combat');
|
||||
combatId = await fixture({action: 'combat', sceneId, fixtureName});
|
||||
const interrupt = wire.commands.length;
|
||||
check(await fixture({action: 'start-combat', combatId}), 'foundry-combat-did-not-start');
|
||||
const combatPlay = await command(interrupt, 'play_media', args => args.option === 'replace');
|
||||
check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
|
||||
await delay(4500);
|
||||
report.combat = await audio();
|
||||
|
||||
stage('ambient-restoration');
|
||||
const restore = wire.commands.length;
|
||||
check(await fixture({action: 'delete-combat', combatId}), 'foundry-combat-delete-not-observed');
|
||||
const restored = await command(restore, 'play_media', args => args.option === 'add');
|
||||
const seek = await command(restore, 'play_index');
|
||||
report.ambientOrderRestored = JSON.stringify(restored.args.media) === JSON.stringify(ambientPlay.args.media);
|
||||
const snapshot = wire.commands.slice(interrupt, wire.commands.indexOf(combatPlay)).findLast(entry => entry.queue?.state === 'playing')?.queue;
|
||||
report.ambientRestoreOffset = {index: seek.args.index, seconds: seek.args.seek_position};
|
||||
report.ambientIndexAndOffsetRestored = Boolean(snapshot && seek.args.seek_position > 0 &&
|
||||
snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
|
||||
await delay(4500);
|
||||
report.restoredAmbient = await audio();
|
||||
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');
|
||||
|
||||
stage('listener-stop-and-resume');
|
||||
const listener = players[0].locator('#adaptive-music-listener');
|
||||
await listener.getByRole('button', {name: 'Stop Audio', exact: true}).click();
|
||||
await until(() => safeStats(players[0]), stats => stats.bytes === 0, 'listener-stop-did-not-close-peer');
|
||||
await listener.getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||
report.afterListenerResume = await audio();
|
||||
|
||||
stage('listener-reload');
|
||||
const reloaded = players[1];
|
||||
await reloaded.reload({waitUntil: 'domcontentloaded', timeout: 30000});
|
||||
await reloaded.waitForFunction(id => game.ready && game.world.id === id && !game.user.isGM && game.socket?.connected,
|
||||
world.id, {polling: 250, timeout: 45000});
|
||||
await openMenu(reloaded, 'listen');
|
||||
await reloaded.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
|
||||
report.afterListenerReload = await audio();
|
||||
if(tabbed){
|
||||
stage('playback-tab-controls');
|
||||
await setup.getByText('2 connected listeners',{exact:true}).waitFor();
|
||||
await setup.locator('.adaptive-now h3').filter({hasText:/^(?!Nothing playing).+/}).waitFor();
|
||||
const slider=setup.getByLabel('Campaign volume');
|
||||
await slider.press('ArrowLeft');
|
||||
await setup.getByRole('button',{name:'Pause',exact:true}).click();
|
||||
await setup.getByRole('button',{name:'Resume',exact:true}).click();
|
||||
report.afterPlaybackResume=await audio();
|
||||
await setup.getByRole('button',{name:'Stop playback',exact:true}).click();
|
||||
await setup.getByText('Stopped',{exact:true}).waitFor();
|
||||
report.playbackTabControls=true;
|
||||
}
|
||||
stage('passed');
|
||||
} finally {
|
||||
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
|
||||
report.sendspinAuthenticated = wire.sendspinAuthenticated();
|
||||
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
|
||||
report.queueWrites = wire.commands.filter(entry => writes.has(entry.command)).map(({command, reply, error}) => ({command, reply: reply === true, error}));
|
||||
if(report.stage!=='passed')report.playbackFailureDetails={
|
||||
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
|
||||
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})),
|
||||
};
|
||||
if (receiver) {
|
||||
if(await setup.getByRole('tab',{name:'Connection',exact:true}).count())await setup.getByRole('tab',{name:'Connection',exact:true}).click().catch(()=>{});
|
||||
report.gmAudioDiagnostics = await gmAudioDiagnostics(gm, setup).catch(() => null);
|
||||
}
|
||||
report.browserAudio = await Promise.all(pages.map(page => page.evaluate(async () => {
|
||||
const diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
|
||||
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
|
||||
return {
|
||||
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
|
||||
signaling: window.__adaptiveMusicTestSignaling,
|
||||
contexts: contexts.map(({context, destination}) => ({state: context.state, time: context.currentTime, track: destination.stream.getAudioTracks()[0]?.readyState})),
|
||||
analyserRMS: analysers.map(analyser => {
|
||||
const samples = new Float32Array(analyser.fftSize);
|
||||
analyser.getFloatTimeDomainData(samples);
|
||||
return Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length);
|
||||
}),
|
||||
browsers: await Promise.all((window.__adaptiveMusicTestPeers ?? []).map(async peer => {
|
||||
const stats = peer.connectionState === 'connected' ? [...(await peer.getStats()).values()] : [];
|
||||
return {connection: peer.connectionState, ice: peer.iceConnectionState, signaling: peer.signalingState,
|
||||
outgoingEnergy: stats.find(row => row.type === 'media-source' && row.kind === 'audio')?.totalAudioEnergy};
|
||||
})),
|
||||
};
|
||||
}).catch(() => null)));
|
||||
if (!report.upstreamError) {
|
||||
const lastError = wire.commands.findLast(entry => entry.reply && entry.error !== null);
|
||||
if (lastError) report.upstreamError = {command: lastError.command, code: lastError.error};
|
||||
}
|
||||
if (baseline) {
|
||||
try {
|
||||
if (report.stage === 'passed') await gm.evaluate(moduleId => game.modules.get(moduleId).api.setOverrides([{id: 'integration-cleanup', playlist: null}]), moduleId);
|
||||
} finally {
|
||||
report.temporaryWorldChangesRestored = await fixture({action: 'cleanup', sceneId, combatId, baseline}).catch(() => false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -136,19 +136,25 @@ def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
|
||||
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
|
||||
output.mkdir(parents=True,exist_ok=True)
|
||||
allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
|
||||
evidence_name=f'evidence/v{version}-live.json'
|
||||
if (ROOT/evidence_name).is_file():allowed.add(evidence_name)
|
||||
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
|
||||
for file in output.rglob('*'):
|
||||
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
|
||||
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
|
||||
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
||||
write_zip(output/'adaptive-music-source.zip',source_entries(manifest))
|
||||
source=source_entries(manifest)
|
||||
write_zip(output/'adaptive-music-source.zip',source)
|
||||
evidence=source.get(f'adaptive-music-source/{evidence_name}')
|
||||
if evidence is not None:
|
||||
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
|
||||
(output/evidence_name).write_bytes(evidence)
|
||||
for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes())
|
||||
for path in (ROOT/'licenses').rglob('*'):
|
||||
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
|
||||
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
|
||||
'sourceCommit':local_revision(),'sourceRevisionStatus':'base revision; included source archive is authoritative','sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False}
|
||||
acceptance_file=ROOT/'evidence/v0.7.0-live.json'
|
||||
acceptance=json.loads(acceptance_file.read_text()) if acceptance_file.is_file() else {}
|
||||
acceptance=json.loads(evidence) if evidence is not None else {}
|
||||
metadata['publicationReady']=acceptance.get('publicationReady') is True
|
||||
metadata['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
|
||||
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') is True
|
||||
|
||||
+11
-7
@@ -2,7 +2,7 @@ import {MusicError} from '../core/controller.mjs';
|
||||
import {MAReadClient} from '../providers/ma/client.mjs';
|
||||
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
||||
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
|
||||
import {randomKey} from '../providers/ma/webcrypto.mjs';
|
||||
import {hmac,randomKey} from '../providers/ma/webcrypto.mjs';
|
||||
export function gmAccessPolicy(baseUrl,pageUrl){
|
||||
let target,page;try{target=new URL(baseUrl);page=new URL(pageUrl);}catch{throw new MusicError('address-invalid');}
|
||||
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
|
||||
@@ -19,7 +19,7 @@ export class GMAudioHost{
|
||||
get session(){return this.#session;}
|
||||
get stream(){return this.#destination?.stream;}
|
||||
get connected(){return this.#live;}
|
||||
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
|
||||
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>(c.id===ref.id||c.legacyId&&c.legacyId===ref.id)&&c.kind==='playlist')); }
|
||||
async prepare(profile){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
|
||||
@@ -64,22 +64,24 @@ export class GMAudioHost{
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
|
||||
if(!preserveTransport){this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});}
|
||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||
// The same authorized token, world and MA origin can resolve new assignments on another GM device.
|
||||
const portable=profile.portableCatalog&&await hmac(new TextEncoder().encode(profile.token),'adaptive-music portable catalog\0'+JSON.stringify([base.origin,profile.namespace]));
|
||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:portable||key,legacyCatalogKey:portable?key:undefined,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
||||
}
|
||||
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
|
||||
start(profile,{audioContext}={}){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile,audioContext).finally(()=>{this.#starting=false;});}
|
||||
#connectionLost(epoch,stage){
|
||||
if(epoch!==this.#epoch||!this.#live)return;
|
||||
void this.close();
|
||||
this.#status='connection-lost';this.#phase=stage;
|
||||
this.onDisconnect();
|
||||
}
|
||||
async #start(profile){
|
||||
async #start(profile,audioContext){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
if(!profile.targetName||typeof profile.target!=='string'||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
|
||||
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
||||
this.#lastError=undefined;this.#attachedQueue=false;this.#context=this.createContext();const unlocked=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=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;
|
||||
try{
|
||||
this.#sdk=await this.loadSDK();await unlocked;check();
|
||||
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
|
||||
@@ -106,6 +108,7 @@ export class GMAudioHost{
|
||||
while(!this.#core.timeSyncInfo.synced&&Date.now()<deadline){check();await new Promise(resolve=>setTimeout(resolve,50));}
|
||||
if(!this.#core.timeSyncInfo.synced)throw new MusicError('sendspin-sync-failed');check();
|
||||
if(profile.autoProvision){this.#phase='dedicated receiver verification';Object.assign(profile,await this.inspect(profile,{transport:this.#apiTransport}));check();}
|
||||
this.#phase='catalog retrieval';
|
||||
await this.readCatalog(profile,{reconnecting:true,preserveTransport:true});check();
|
||||
this.#phase='dedicated queue verification';
|
||||
await this.#client.verifyTarget({checkRegistration:check});
|
||||
@@ -119,7 +122,7 @@ export class GMAudioHost{
|
||||
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;this.#phase='ready';
|
||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
||||
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
|
||||
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw new MusicError(this.#lastError.code);}
|
||||
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw Object.assign(new MusicError(this.#lastError.code),this.#lastError);}
|
||||
}
|
||||
#authenticatedSocket(base,token,clientId){
|
||||
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
||||
@@ -161,6 +164,7 @@ export class GMAudioHost{
|
||||
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
|
||||
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
playbackStatus(){return this.#ready().playbackStatus();}
|
||||
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;this.#meter=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
}
|
||||
+24
-2
@@ -25,13 +25,35 @@ export class MusicController {
|
||||
}
|
||||
update(state) {
|
||||
const input = structuredClone(state);
|
||||
const context = this.#nextContext();
|
||||
return this.#enqueue(() => this.transition(input, context));
|
||||
}
|
||||
control(action, value) {
|
||||
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) {
|
||||
return Promise.reject(new MusicError('unsupported'));
|
||||
}
|
||||
const expected = this.generation;
|
||||
return this.#enqueue(() => {
|
||||
if (expected !== this.generation) throw new MusicError('stale');
|
||||
const context = this.#nextContext();
|
||||
context.check();
|
||||
return this.providers.ma.control(action, value, context);
|
||||
});
|
||||
}
|
||||
cancel() {
|
||||
this.generation++;
|
||||
this.abort?.abort();
|
||||
}
|
||||
#nextContext() {
|
||||
const generation = ++this.generation;
|
||||
this.abort?.abort(); this.abort = new AbortController();
|
||||
const context = { campaign: this.campaign, session: this.session, generation,
|
||||
return { campaign: this.campaign, session: this.session, generation,
|
||||
signal: this.abort.signal, check: () => {
|
||||
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
|
||||
} };
|
||||
const task = this.tail.catch(() => {}).then(() => this.transition(input, context));
|
||||
}
|
||||
#enqueue(operation) {
|
||||
const task = this.tail.catch(() => {}).then(operation);
|
||||
this.tail = task; return task;
|
||||
}
|
||||
async transition(state, ctx) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {base64url,hmac} from '../providers/ma/webcrypto.mjs';
|
||||
|
||||
const bytes=new TextEncoder();
|
||||
|
||||
async function key(token,scope){
|
||||
const material=await hmac(bytes.encode(token),'adaptive-music saved connection\0'+scope);
|
||||
return crypto.subtle.importKey('raw',material,'AES-GCM',false,['encrypt','decrypt']);
|
||||
}
|
||||
|
||||
function decode(value){
|
||||
if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('saved-connection-unavailable');
|
||||
return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),char=>char.charCodeAt(0));
|
||||
}
|
||||
|
||||
export async function sealAccountConnection({maUrl,targetName},token,scope){
|
||||
const iv=crypto.getRandomValues(new Uint8Array(12));
|
||||
const content=bytes.encode(JSON.stringify({maUrl,targetName}));
|
||||
if(content.length>2048)throw new MusicError('saved-connection-too-large');
|
||||
const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:bytes.encode(scope)},await key(token,scope),content);
|
||||
return {version:1,iv:base64url(iv),cipher:base64url(new Uint8Array(cipher))};
|
||||
}
|
||||
|
||||
export async function openAccountConnection(saved,token,scope){
|
||||
try{
|
||||
if(saved?.version!==1||saved.iv?.length!==16||!saved.cipher||saved.cipher.length>2800)throw Error();
|
||||
const content=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(saved.iv),additionalData:bytes.encode(scope)},await key(token,scope),decode(saved.cipher));
|
||||
const {maUrl,targetName}=JSON.parse(new TextDecoder().decode(content));
|
||||
if(typeof maUrl!=='string'||typeof targetName!=='string')throw Error();
|
||||
return {maUrl,targetName};
|
||||
}catch{throw new MusicError('saved-connection-unavailable');}
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import {gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {validateIceServers} from '../audio/peer-audio.mjs';
|
||||
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
|
||||
const messages={
|
||||
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
|
||||
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
|
||||
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
|
||||
'token-required':'Enter a Music Assistant access token for this server.',
|
||||
'token-invalid':'Remove line breaks from the access token and try again.',
|
||||
'receiver-name-invalid':'Use at most 120 characters for the receiver name, without line breaks.',
|
||||
'automation-disabled':'Enable automation before applying a manual playlist override.',
|
||||
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
|
||||
'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.',
|
||||
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
|
||||
'ws-auth-denied':'MA rejected the token. Enter a replacement and Authenticate again; the receiver is remembered.',
|
||||
'ws-auth-denied':'MA rejected the token. Enter a replacement and select Connect again; the receiver is remembered.',
|
||||
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
|
||||
'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.',
|
||||
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
|
||||
@@ -27,64 +34,141 @@ const messages={
|
||||
'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;
|
||||
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
|
||||
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),legend=dom.createElement('legend');legend.textContent='1. Music Assistant';panel.append(legend);
|
||||
const note=dom.createElement('p');note.textContent='Enter your server and access token. A dedicated campaign receiver is created and paired automatically. The token stays in this GM tab; its receiver identity is remembered privately in this browser.';panel.append(note);
|
||||
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
|
||||
const steps=Array.from({length:2},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
|
||||
const go=index=>steps.forEach((step,i)=>{step.hidden=i!==index;});
|
||||
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
|
||||
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;show();}});parent.append(b);return b;};
|
||||
const draft=connection.draftFields??{},address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=draft.maUrl??'';
|
||||
const token=field(steps[0],'Private GM access token','password');
|
||||
const advanced=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Receiver options';advanced.append(summary);steps[0].append(advanced);
|
||||
const name=field(advanced,'Dedicated receiver name');name.value=draft.targetName??'Adaptive Music '+(game.world?.title??'campaign');
|
||||
const iceURL=field(advanced,'Existing ICE server URL (optional)');iceURL.placeholder='stun:stun.example.test:3478';
|
||||
const iceUsername=field(advanced,'TURN username (if required)'),iceCredential=field(advanced,'Short-lived TURN credential','password'),iceExpiry=field(advanced,'TURN credential expiry (UTC)','datetime-local');
|
||||
const networkNote=dom.createElement('p');networkNote.textContent='Direct connections use no external ICE service. For remote players, you may supply an existing STUN/TURN service. TURN credentials must expire within one hour; no service is installed.';advanced.append(networkNote);
|
||||
const logging=dom.createElement('p');logging.textContent='Keep MA raw-frame VERBOSE logging disabled: it can record authentication frames. No server logging settings are changed by this module.';advanced.append(logging);
|
||||
button(steps[0],'Authenticate',async()=>{
|
||||
if(!address.value.trim())throw {code:'address-invalid'};status.textContent='Authenticating with Music Assistant…';
|
||||
const network={};
|
||||
if(iceURL.value.trim()){
|
||||
const server={urls:iceURL.value.trim()};
|
||||
if(/^turns?:/.test(server.urls)){server.username=iceUsername.value.trim();server.credential=iceCredential.value;server.expires=Date.parse(iceExpiry.value+'Z');}
|
||||
try{validateIceServers([server]);}catch{throw {code:'ice-config-invalid'};}network.listenerNetwork={iceServers:[server]};
|
||||
}
|
||||
let result;try{result=await connection.test({maUrl:address.value.trim(),token:token.value,targetName:name.value.trim(),allowCatalogPlayback:true,webSocketAuthLogSafe:true,...network});}
|
||||
finally{if(connection.status.hasPrivateDraft){token.value='';}}
|
||||
token.value='';setTarget(result.target,result.targetName);go(1);connect.disabled=false;
|
||||
status.textContent='Authenticated. Connect this dedicated campaign receiver to pair it and load your playlists.';
|
||||
});
|
||||
const target=dom.createElement('select'),label=dom.createElement('label');label.textContent='Dedicated campaign receiver';label.append(target);steps[1].append(label);
|
||||
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;};
|
||||
const connect=button(steps[1],'Connect audio',async()=>{
|
||||
status.textContent='Connecting and pairing the dedicated receiver…';
|
||||
const result=await connection.connect(target.value);await onCatalog();status.textContent=result?.attachedExistingQueue?'Campaign audio reconnected. The existing queue was preserved. Apply the automation setting below when ready to resume scene control.':'Campaign audio connected. Assign ambient and combat playlists below, then enable automation. Players connect automatically.';
|
||||
});
|
||||
button(steps[1],'Enable GM audio',()=>connection.resume());
|
||||
const volume=field(steps[1],'Campaign volume','range');volume.min='0';volume.max='100';volume.value=String(connection.status.volume??100);volume.addEventListener('change',()=>{try{connection.setVolume?.(Number(volume.value));}catch(error){status.textContent=connectionMessage(error);onError(error);}});
|
||||
button(steps[1],'Refresh playlists',async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';});
|
||||
button(steps[1],'Back to authentication',()=>go(0));
|
||||
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');panel.append(diagnostics);
|
||||
const report=dom.createElement('div');report.setAttribute('aria-live','polite');panel.append(report);let transportResults=[];
|
||||
button(panel,'Check browser connection (no MA token)',async()=>{
|
||||
report.replaceChildren();status.textContent='Checking both WebSocket routes from this Foundry page…';
|
||||
try{transportResults=await probeWebSockets(address.value.trim());}catch(error){throw error?.code?error:{code:'address-invalid'};}
|
||||
for(const result of transportResults){const line=dom.createElement('p');line.textContent=result.path+': '+diagnosticMessage(result);report.append(line);}
|
||||
status.textContent='Browser checks complete. No MA token was sent. An open socket still needs authentication, pairing and clock synchronization.';
|
||||
});
|
||||
button(panel,'Copy connection diagnostics',async()=>{
|
||||
const d=connection.status;const text=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,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2);
|
||||
await navigator.clipboard.writeText(text);status.textContent='Diagnostics copied. The report excludes the address, token, receiver identity and catalog titles.';
|
||||
});
|
||||
button(panel,'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Disconnected. The token was forgotten; this browser remembers its campaign receiver.';await onCatalog();});
|
||||
const recovery=dom.createElement('details'),recoveryTitle=dom.createElement('summary');recoveryTitle.textContent='Connection recovery';recovery.append(recoveryTitle);panel.append(recovery);
|
||||
button(recovery,'Reconnect remembered receiver',async()=>{await connection.reconnect();await onCatalog();status.textContent='Receiver reconnected using retained private inputs. The queue was preserved and automation is paused. Review it, then Apply automation setting when ready.';});
|
||||
button(recovery,'Forget remembered receiver',async()=>{await (connection.forgetReceiver?.()??connection.disconnect());token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Local receiver identity forgotten. Reauthenticate to provision a new receiver. Existing MA queues were left untouched.';await onCatalog();});
|
||||
const show=()=>{const d=connection.status;volume.disabled=d.state!=='connected';if(d.hasPrivateDraft)token.placeholder='Retained in this tab; leave blank to retry';connect.disabled=d.state==='connected'||d.state==='connecting';diagnostics.textContent=`${d.state}. ${d.stage??''} Playlists: ${d.catalog??0}. GM audio: ${d.audioContext??'closed'}. Decoded frames: ${d.decodedFrames??0}. Connected listeners: ${d.peers??0}.`;};
|
||||
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);go(1);}else go(0);show();container.append(panel);
|
||||
// Refresh while the actual ApplicationV2 window is mounted; no secret-bearing events.
|
||||
if(globalThis.document===dom&&typeof panel.isConnected==='boolean'){const timer=setInterval(()=>{if(!panel.isConnected){clearInterval(timer);return;}show();},1000);}
|
||||
return panel;
|
||||
|
||||
function failureStage(error) {
|
||||
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
|
||||
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
|
||||
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
|
||||
if (error?.stage === 'Sendspin authentication' || error?.code === 'sendspin-auth-failed') return 'Receiver connection failed';
|
||||
if (error?.stage === 'catalog retrieval' || error?.code === 'catalog-empty') return 'Playlist catalog unavailable';
|
||||
return 'Setup failed';
|
||||
}
|
||||
|
||||
function iceConfiguration(fields) {
|
||||
const {url, username, credential, expires} = fields;
|
||||
if (!url && !username && !credential && !expires) return undefined;
|
||||
const scheme = url.match(/^(stun|stuns|turn|turns):/i)?.[1].toLowerCase();
|
||||
const target = scheme && URL.canParse(`https://${url.slice(scheme.length + 1)}`) && new URL(`https://${url.slice(scheme.length + 1)}`);
|
||||
const turn = scheme?.startsWith('turn');
|
||||
if (!target || !target.hostname || target.username || target.password || target.pathname !== '/' || target.hash ||
|
||||
/[\s/]/.test(url) || (target.search && !(turn && /^\?transport=(udp|tcp)$/.test(target.search))) ||
|
||||
(!turn && (username || credential || expires))) throw {code:'ice-config-invalid'};
|
||||
const server = {urls:url, ...(turn ? {username, credential, expires:Date.parse(expires + 'Z')} : {})};
|
||||
try{validateIceServers([server]);}
|
||||
catch{throw {code:'ice-config-invalid'};}
|
||||
return {iceServers:[server]};
|
||||
}
|
||||
|
||||
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{},next,advancedContent}) {
|
||||
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 input=(parent,label,type='text')=>{
|
||||
const wrapper=make('label',label,parent),field=make('input',null,wrapper);
|
||||
field.type=type;field.autocomplete='off';field.spellcheck=false;
|
||||
return field;
|
||||
};
|
||||
const initial=connection.draftFields??{};
|
||||
make('h2','Connect Music Assistant');
|
||||
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
|
||||
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
|
||||
const fields=make('div');fields.className='adaptive-fields';
|
||||
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
|
||||
const token=input(fields,'Private GM access token','password');
|
||||
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
|
||||
const actions=make('div');actions.className='adaptive-actions';
|
||||
const state=make('p');state.className='adaptive-state';
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
const advanced=make('details');make('summary','Advanced',advanced);
|
||||
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
|
||||
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
|
||||
const iceURL=input(advancedFields,'ICE server URL');iceURL.placeholder='stun:stun.example.test:3478';
|
||||
const iceUsername=input(advancedFields,'TURN username'),iceCredential=input(advancedFields,'TURN credential','password');
|
||||
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
|
||||
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
|
||||
const report=make('div');report.setAttribute('aria-live','polite');
|
||||
let transportResults=[],busy=false;
|
||||
const run=async(action,label)=>{
|
||||
if(busy||!game.user.isGM)return;
|
||||
busy=true;retainError.hidden=true;render();
|
||||
try{await action();}
|
||||
catch(error){
|
||||
busy=false;render();error.field?.focus?.();
|
||||
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
|
||||
}finally{busy=false;render();}
|
||||
};
|
||||
const button=(parent,label,action)=>{
|
||||
const b=make('button',label,parent);b.type='button';b.addEventListener('click',action);return b;
|
||||
};
|
||||
const pageUrl=()=>dom.location?.href??globalThis.location?.href??'https://foundry.invalid';
|
||||
function validatedAddress(){
|
||||
try{return gmAccessPolicy(address.value.trim(),pageUrl()).origin;}
|
||||
catch(error){if(error.code==='denied')throw {code:'address-invalid'};throw error;}
|
||||
}
|
||||
function retainedToken(){
|
||||
const draft=connection.draftFields??{};
|
||||
try{return draft.retainedToken===true&&new URL(draft.maUrl).origin===validatedAddress();}
|
||||
catch{return false;}
|
||||
}
|
||||
const connect=button(actions,'Connect',()=>run(async()=>{
|
||||
let maUrl;
|
||||
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
|
||||
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
|
||||
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
|
||||
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
|
||||
const targetName=name.value.trim();
|
||||
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
|
||||
let listenerNetwork;
|
||||
try{listenerNetwork=iceConfiguration({url:iceURL.value.trim(),username:iceUsername.value.trim(),credential:iceCredential.value,expires:iceExpiry.value});}
|
||||
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
|
||||
status.textContent='Contacting Music Assistant…';
|
||||
let result;
|
||||
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
|
||||
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
|
||||
address.value=connection.draftFields?.maUrl??address.value;
|
||||
await onCatalog();
|
||||
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
|
||||
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
|
||||
connect.className='adaptive-primary';
|
||||
const nextButton=button(actions,'Choose scene music',()=>next?.());
|
||||
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
|
||||
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
|
||||
},'Disconnect failed'));
|
||||
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
|
||||
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
|
||||
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
|
||||
status.textContent='Browser checks complete.';
|
||||
},'Browser connection check failed'));
|
||||
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
|
||||
const d=connection.status;
|
||||
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
|
||||
status.textContent='Connection diagnostics copied.';
|
||||
},'Could not copy diagnostics'));
|
||||
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
|
||||
const refresh=button(advancedActions,'Refresh playlists',()=>run(async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';},'Catalog refresh failed'));
|
||||
const forget=button(advancedActions,'Forget saved connection',()=>run(async()=>{
|
||||
await connection.forgetReceiver();address.value='';token.value='';iceCredential.value='';name.value='';status.textContent='Saved connection removed from this account.';await onCatalog();
|
||||
},'Could not forget the connection'));
|
||||
if(advancedContent)advanced.append(advancedContent);
|
||||
function render(){
|
||||
const d=connection.status,connected=d.state==='connected';
|
||||
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
|
||||
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
|
||||
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
|
||||
if(state.textContent!==summary)state.textContent=summary;
|
||||
state.dataset.connected=String(connected);
|
||||
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
|
||||
disconnect.hidden=!connected;disconnect.disabled=busy;
|
||||
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
|
||||
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
|
||||
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
|
||||
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
|
||||
}
|
||||
address.addEventListener('input',render);
|
||||
render();
|
||||
return render;
|
||||
}
|
||||
+82
-13
@@ -4,26 +4,39 @@ import {connectionDraft} from './connection-draft.mjs';
|
||||
import {startNativeRuntime,primaryGM} from './runtime.mjs';
|
||||
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
|
||||
import {GatewayClient} from '../providers/ma/remote.mjs';
|
||||
import {GMAudioHost} from '../audio/gm-host.mjs';
|
||||
import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {AutoListeners} from '../audio/auto-listeners.mjs';
|
||||
import {PeerAudio} from '../audio/peer-audio.mjs';
|
||||
import {ListenerAudio} from './listener-audio.mjs';
|
||||
import {createSetupClass,createListenerClass} from './setup.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
|
||||
const id='adaptive-music';
|
||||
const receiverVault=new ReceiverVault();
|
||||
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
|
||||
const accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
|
||||
const savedConnection=()=>game.settings.get(id,'savedConnection');
|
||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
|
||||
let automationRunning=false,previousController;
|
||||
const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
|
||||
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean);
|
||||
const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
|
||||
const onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
|
||||
function start(){
|
||||
if(!game.user.isGM||runtime)return;
|
||||
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
|
||||
runtime.refresh().catch(onError);
|
||||
function ensureRuntime(){
|
||||
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
|
||||
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
|
||||
return runtime;
|
||||
}
|
||||
function stop(){runtime?.dispose();runtime=null;}
|
||||
function setOverrides(value){if(!runtime)throw Error('Automation is disabled');return runtime.setOverrides(value);}
|
||||
function start(){
|
||||
if(!gmAuthority()||automationRunning)return;
|
||||
automationRunning=true;
|
||||
return ensureRuntime().refresh().catch(onError);
|
||||
}
|
||||
function stop(){
|
||||
automationRunning=false;
|
||||
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
|
||||
}
|
||||
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
|
||||
function ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
|
||||
function attachListenerSource(stream){listenerSource?.disconnect();if(listenerContext){listenerSource=listenerContext.createMediaStreamSource(stream);listenerSource.connect(listenerContext.destination);remoteAudio.muted=true;}}
|
||||
function resumeListener(){if(game.user.isGM)return gmHost.resumeAudio();listenerStopped=false;const element=ensureRemoteAudio();let resumed=Promise.resolve();if(globalThis.AudioContext){listenerContext??=new AudioContext();resumed=listenerContext.resume();if(element.srcObject)attachListenerSource(element.srcObject);}const play=element.play();play.catch(()=>{});if(!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);return resumed.then(()=>{listenerState=element.srcObject?'Campaign audio enabled.':'Audio enabled. Waiting for GM audio.';});}
|
||||
@@ -38,8 +51,28 @@ function sendInvites(){
|
||||
});return inviteTail;
|
||||
}
|
||||
const connection={
|
||||
get draftFields(){return privateDraft?{maUrl:privateDraft.maUrl,targetName:privateDraft.targetName,webSocketAuthLogSafe:privateDraft.webSocketAuthLogSafe,allowCatalogPlayback:privateDraft.allowCatalogPlayback}:{};},
|
||||
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,listenerDiagnostics:peers?.diagnostics(),peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
|
||||
get draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};},
|
||||
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};},
|
||||
async open(profile){
|
||||
if(!gmAuthority()||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
|
||||
// Claim browser audio activation before authentication performs asynchronous work.
|
||||
const audioContext=gmHost.createContext();
|
||||
const generation=connectionGeneration;
|
||||
try{
|
||||
void audioContext.resume().catch(()=>{});
|
||||
if(!profile.maUrl){
|
||||
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
|
||||
gmAccessPolicy(remembered.maUrl,location.href);
|
||||
profile={...profile,maUrl:remembered.maUrl,targetName:profile.targetName??remembered.targetName};
|
||||
}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
const {target}=await connection.test(profile);
|
||||
return await connection.connect(target,{audioContext});
|
||||
}catch(error){
|
||||
if(audioContext.state!=='closed')await audioContext.close();
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
async test(profile){
|
||||
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
|
||||
connectionTesting=true;stop();const generation=++connectionGeneration;privateProfile=null;
|
||||
@@ -48,16 +81,51 @@ const connection={
|
||||
await gmHost.close();check();
|
||||
const candidate=connectionDraft(privateDraft,profile,game.world.id);privateDraft=candidate;
|
||||
if(!candidate.identityStorage?.['sendspin-identity-sk'])Object.assign(candidate,await receiverVault.load(receiverScope(candidate))??{});check();
|
||||
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;
|
||||
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;candidate.portableCatalog=true;
|
||||
const result=await gmHost.prepare(candidate);check();
|
||||
await receiverVault.save(receiverScope(result),result);check();
|
||||
privateProfile=result;privateDraft=result;return {target:result.target,targetName:result.targetName};
|
||||
}finally{connectionTesting=false;}
|
||||
}catch(error){error.stage??='API authentication';throw error;}
|
||||
finally{connectionTesting=false;}
|
||||
},
|
||||
async connect(target,{resumeAutomation=true,audioContext}={}){
|
||||
if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
|
||||
stop();const profile=privateProfile,generation=connectionGeneration;
|
||||
let result;
|
||||
try{result=await gmHost.start(profile,{audioContext});}
|
||||
finally{if(generation===connectionGeneration)await receiverVault.save(receiverScope(profile),profile);}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
try{
|
||||
const saved=await sealAccountConnection(profile,profile.token,accountScope());
|
||||
if(generation===connectionGeneration)await game.settings.set(id,'savedConnection',saved);
|
||||
}catch{onError(new MusicError('saved-connection-write-failed'));}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();
|
||||
if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();
|
||||
return result;
|
||||
},
|
||||
async connect(target,{resumeAutomation=true}={}){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);let result;try{result=await pending;}finally{if(privateProfile)await receiverVault.save(receiverScope(privateProfile),privateProfile);}peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();return result;},
|
||||
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
|
||||
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||
async forgetReceiver(){if(privateDraft){const scope=receiverScope(privateDraft);await connection.disconnect();await receiverVault.forget(scope);}},
|
||||
async playback(){
|
||||
if(!gmAuthority())throw new MusicError('denied');
|
||||
const current=runtime?.controller.current?.playlist;
|
||||
if(current?.provider==='native'){
|
||||
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing);
|
||||
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??''};
|
||||
}
|
||||
if(gmHost.connected)return {source:'Music Assistant',...await gmHost.playbackStatus()};
|
||||
return {state:'idle',title:''};
|
||||
},
|
||||
control(action,value){
|
||||
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
|
||||
return ensureRuntime().controller.control(action,value);
|
||||
},
|
||||
async forgetReceiver(){
|
||||
const scope=privateDraft&&receiverScope(privateDraft);
|
||||
await connection.disconnect();
|
||||
await game.settings.set(id,'savedConnection',{});
|
||||
if(scope)await receiverVault.forget(scope);
|
||||
},
|
||||
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
|
||||
};
|
||||
function listenWebRTC(invite){
|
||||
@@ -66,6 +134,7 @@ function listenWebRTC(invite){
|
||||
}
|
||||
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',()=>{
|
||||
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,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false});
|
||||
game.settings.register(id,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true});
|
||||
|
||||
@@ -18,8 +18,9 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
|
||||
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
|
||||
add('',empty);
|
||||
for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'Music Assistant':'Foundry'}: ${c.name}`);
|
||||
if(current&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||
select.value=referenceKey(current);return select;
|
||||
const replacement=current?.provider==='ma'&&choices.find(c=>c.provider==='ma'&&c.legacyId===current.id);
|
||||
if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||
select.value=referenceKey(replacement||current);return select;
|
||||
}
|
||||
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
|
||||
if(!game.user?.isGM)return null;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import {connectionMessage} from './connection-wizard.mjs';
|
||||
import {referenceKey,selection} from '../core/scene-music.mjs';
|
||||
|
||||
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
|
||||
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
|
||||
|
||||
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError}) {
|
||||
const dom=container.ownerDocument;
|
||||
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
make('h2','Playback');
|
||||
const now=make('section');now.className='adaptive-now';
|
||||
const state=make('p','Stopped',now);state.className='adaptive-state';
|
||||
const track=make('h3','Nothing playing',now);
|
||||
const timing=make('p',null,now);
|
||||
const controls=make('div');controls.className='adaptive-actions';
|
||||
const output=make('div');output.className='adaptive-fields';
|
||||
const volumeLabel=make('label','Campaign volume',output),volume=make('input',null,volumeLabel);
|
||||
volume.type='range';volume.min='0';volume.max='100';volume.value='100';
|
||||
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel);
|
||||
seek.type='range';seek.min='0';seek.max='0';seek.step='1';seek.value='0';
|
||||
const summary=make('div');summary.className='adaptive-playback-summary';
|
||||
const automationText=make('p',null,summary),listeners=make('p',null,summary);
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
const failure=make('p');failure.setAttribute('role','alert');failure.hidden=true;
|
||||
let trackStatus,refreshing=false,busy=false,volumeEditing=false,seekEditing=false,oldChoices='';
|
||||
|
||||
const button=(parent,label,action)=>{
|
||||
const b=make('button',label,parent);b.type='button';b.addEventListener('click',()=>run(action));return b;
|
||||
};
|
||||
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
|
||||
toggle.className='adaptive-primary';
|
||||
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop'));
|
||||
const unlock=button(controls,'Enable GM audio',()=>connection.resume());
|
||||
const automation=button(summary,'Enable automation',async()=>{
|
||||
const enable=!isRunning();
|
||||
if(!enable)stop();
|
||||
await game.settings.set('adaptive-music','enabled',enable);
|
||||
if(enable)await start();
|
||||
status.textContent=enable?'Scene automation enabled.':'Scene automation disabled.';
|
||||
});
|
||||
|
||||
const manual=make('details');make('summary','Manual playlist override',manual);
|
||||
const label=make('label','Override playlist',manual),select=make('select',null,label);
|
||||
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions';
|
||||
button(manualActions,'Apply override',()=>setOverrides([{id:'gm-manual',playlist:selection(select.value,getChoices())}]));
|
||||
button(manualActions,'Clear override',()=>setOverrides([]));
|
||||
function isRunning(){return connection?.status.automationRunning??game.settings.get('adaptive-music','enabled');}
|
||||
|
||||
volume.addEventListener('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
|
||||
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;}));
|
||||
seek.addEventListener('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
|
||||
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;}));
|
||||
|
||||
async function run(action){
|
||||
if(busy||!game.user.isGM)return;
|
||||
busy=true;failure.hidden=true;render();
|
||||
try{await action();}
|
||||
catch(error){failure.textContent=`Playback action failed. ${connectionMessage(error)}`;failure.hidden=false;onError(error);}
|
||||
finally{busy=false;await refresh();}
|
||||
}
|
||||
function render(){
|
||||
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused';
|
||||
const canControl=connected&&trackStatus?.source==='Music Assistant'&&d.lastError?.code!=='uncertain';
|
||||
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
|
||||
track.textContent=trackStatus?.title||'Nothing playing';
|
||||
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
|
||||
if(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
|
||||
if(!seekEditing){
|
||||
seek.max=String(Math.max(0,(trackStatus?.duration??0)-1));seek.value=String(Math.min(Number(seek.max),trackStatus?.position??0));
|
||||
seek.setAttribute('aria-valuetext',clock(Number(seek.value)));
|
||||
}
|
||||
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
|
||||
stopTrack.disabled=busy||!canControl||!(playing||paused);
|
||||
volume.disabled=busy||!connected;seek.disabled=busy||!canControl||!(playing||paused)||Number(seek.max)<=0;
|
||||
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
|
||||
const enabled=isRunning();
|
||||
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
|
||||
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
|
||||
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
|
||||
if(d.lastError?.code==='uncertain'){
|
||||
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]));
|
||||
if(display!==oldChoices){
|
||||
const previous=select.value;select.replaceChildren();
|
||||
const empty=make('option','Silence',select);empty.value='';
|
||||
for(const choice of choices){const option=make('option',choice.name,select);option.value=referenceKey(choice);}
|
||||
if(choices.some(choice=>referenceKey(choice)===previous))select.value=previous;
|
||||
oldChoices=display;
|
||||
}
|
||||
}
|
||||
async function refresh(){
|
||||
render();if(refreshing||busy)return;
|
||||
refreshing=true;
|
||||
try{trackStatus=await connection?.playback?.();}
|
||||
catch{trackStatus={state:'unavailable'};}
|
||||
finally{refreshing=false;render();}
|
||||
}
|
||||
render();
|
||||
return refresh;
|
||||
}
|
||||
+10
-4
@@ -5,15 +5,21 @@ export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
|
||||
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
|
||||
// Explicit development bootstrap. No hooks or document mutations occur on import.
|
||||
// All music configuration uses module-owned flags; no actor/system schema access.
|
||||
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) {
|
||||
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
|
||||
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
|
||||
previousController, onError = () => {} }) {
|
||||
const flag = d => d?.getFlag('adaptive-music', 'music');
|
||||
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
|
||||
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
|
||||
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
|
||||
authority: () => game.ready && primaryGM(game.users) === game.user.id });
|
||||
authority });
|
||||
if (previousController) {
|
||||
controller.generation = previousController.generation;
|
||||
controller.tail = previousController.tail;
|
||||
}
|
||||
let overrides = [];
|
||||
const refresh = () => {
|
||||
if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve();
|
||||
if (!isEnabled() || !authority()) return Promise.resolve();
|
||||
const scene = [...game.scenes].find(s => s.active);
|
||||
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
|
||||
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
|
||||
@@ -30,6 +36,6 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
|
||||
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
|
||||
return { controller, refresh,
|
||||
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
|
||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); }
|
||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
|
||||
};
|
||||
}
|
||||
+116
-41
@@ -1,54 +1,129 @@
|
||||
import {mountConnectionWizard} from './connection-wizard.mjs';
|
||||
import {mountConnectionWizard,connectionMessage} from './connection-wizard.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {selection} from '../core/scene-music.mjs';
|
||||
import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs';
|
||||
import {mountMusicAssignments,mountBossEditor} from './music-editor.mjs';
|
||||
import {mountPlaybackPanel} from './playback-panel.mjs';
|
||||
|
||||
const namespace='adaptive-music';
|
||||
const tabs=[['connection','Connection'],['scene','Scene Music'],['playback','Playback']];
|
||||
|
||||
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,connection,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicSetup extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}};
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music',resizable:true},position:{width:760,height:620}};
|
||||
#tab='connection';
|
||||
#scene;
|
||||
#timer;
|
||||
|
||||
async _renderHTML(){
|
||||
if(!game.user.isGM)throw new MusicError('denied');
|
||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
||||
const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;};
|
||||
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
|
||||
const button=(label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw new MusicError('denied');await action();}catch(e){status.textContent='Could not apply this change. Check ownership, active GM authority and connection diagnostics.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
|
||||
const assignmentRoot=dom.createElement('div');
|
||||
if(connection)mountConnectionWizard({game,container:root,connection,onCatalog:()=>renderAssignments(),onError});
|
||||
const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean));
|
||||
const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='2. Foundry music and fallback';ownedPanel.append(legend);
|
||||
for(const playlist of game.playlists){const label=dom.createElement('label'),input=dom.createElement('input');input.type='checkbox';input.checked=owned.has(playlist.id);label.textContent=playlist.name+' ';label.append(input);ownedPanel.append(label);boxes.push({id:playlist.id,input});}root.append(ownedPanel);
|
||||
text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.');
|
||||
button('Save native ownership',async()=>{stop();await game.settings.set('adaptive-music','enabled',false);await game.settings.set('adaptive-music','ownedPlaylistIds',boxes.filter(b=>b.input.checked).map(b=>b.id).join(','));status.textContent='Ownership saved. Reload this world before enabling automation.';});
|
||||
const advanced=game.settings.get('adaptive-music','advancedDevelopment')===true;
|
||||
if(advanced){
|
||||
const dev=dom.createElement('details'),title=dom.createElement('summary');title.textContent='Advanced development: optional companion';dev.append(title);root.append(dev);
|
||||
const label=dom.createElement('label');label.textContent='Companion controller code';const code=dom.createElement('input');code.type='password';code.autocomplete='off';label.append(code);dev.append(label);
|
||||
const connect=button('Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await renderAssignments();});dev.append(connect);
|
||||
const disconnect=button('Disconnect optional companion',()=>gateway.disconnect());dev.append(disconnect);
|
||||
const listen=dom.createElement('input');listen.type='password';listen.setAttribute('aria-label','Companion test capability');dev.append(listen);
|
||||
const enable=button('Enable synthetic test audio',()=>{const value=JSON.parse(listen.value);listen.value='';return audio.start(gateway.audioRequest(value));});dev.append(enable);
|
||||
const disable=button('Stop test audio',()=>audio.stop());dev.append(disable);
|
||||
}
|
||||
const renderAssignments=async()=>{
|
||||
assignmentRoot.replaceChildren();const choices=await getChoices();
|
||||
const defaults=dom.createElement('details'),defaultsTitle=dom.createElement('summary');defaultsTitle.textContent='World music defaults';defaults.append(defaultsTitle);mountMusicAssignments({game,container:defaults,choices,defaults:true,onError});assignmentRoot.append(defaults);
|
||||
const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select');
|
||||
for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel);
|
||||
const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel);
|
||||
const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});};
|
||||
const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene();
|
||||
const more=dom.createElement('details'),moreTitle=dom.createElement('summary');moreTitle.textContent='Boss music and manual controls';more.append(moreTitle);assignmentRoot.append(more);
|
||||
const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map();
|
||||
for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);more.append(bossLabel);
|
||||
const bossPanel=dom.createElement('div');more.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
|
||||
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');more.append(manual);
|
||||
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));more.append(b);}
|
||||
const make=(tag,text,parent=root)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
const nav=make('div');nav.className='adaptive-tabs';nav.setAttribute('role','tablist');nav.setAttribute('aria-label','Adaptive Music setup');
|
||||
const panels=new Map();
|
||||
let refreshPlayback=()=>{};
|
||||
const switchTab=(id,focus=false)=>{
|
||||
this.#tab=id;
|
||||
for(const [key,{tab,panel}] of panels){
|
||||
const selected=key===id;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;panel.hidden=!selected;
|
||||
}
|
||||
if(focus)panels.get(id).tab.focus?.();
|
||||
if(id==='playback')void refreshPlayback();
|
||||
};
|
||||
await renderAssignments();root.append(assignmentRoot);
|
||||
const enabledLabel=dom.createElement('label');enabledLabel.textContent='Enable music automation ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=game.settings.get('adaptive-music','enabled');enabledLabel.append(enabled);root.append(enabledLabel);
|
||||
button('Apply automation setting',async()=>{await game.settings.set('adaptive-music','enabled',enabled.checked);if(enabled.checked)start();else stop();status.textContent=enabled.checked?'Automation enabled. MA assignments require authorized content; otherwise the configured native fallback is selected.':'Automation disabled; current playback is retained.';});
|
||||
for(const [index,[id,label]] of tabs.entries()){
|
||||
const tab=make('button',label,nav);tab.type='button';tab.id=`adaptive-tab-${id}`;tab.setAttribute('role','tab');
|
||||
const panel=make('section');panel.className='adaptive-panel';panel.id=`adaptive-panel-${id}`;panel.setAttribute('role','tabpanel');
|
||||
tab.setAttribute('aria-controls',panel.id);panel.setAttribute('aria-labelledby',tab.id);
|
||||
tab.addEventListener('click',()=>switchTab(id));
|
||||
tab.addEventListener('keydown',event=>{
|
||||
const positions={ArrowRight:(index+1)%tabs.length,ArrowLeft:(index+tabs.length-1)%tabs.length,Home:0,End:tabs.length-1};
|
||||
if(!Object.hasOwn(positions,event.key))return;
|
||||
event.preventDefault();switchTab(tabs[positions[event.key]][0],true);
|
||||
});
|
||||
panels.set(id,{tab,panel});
|
||||
}
|
||||
const connectionPanel=panels.get('connection').panel,scenePanel=panels.get('scene').panel,playbackPanel=panels.get('playback').panel;
|
||||
const button=(parent,label,action,status,className)=>{
|
||||
const b=make('button',label,parent);b.type='button';if(className)b.className=className;
|
||||
b.addEventListener('click',async()=>{
|
||||
if(!game.user.isGM||b.disabled)return;
|
||||
b.disabled=true;
|
||||
try{await action();}catch(error){if(status)status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;}
|
||||
});return b;
|
||||
};
|
||||
const addOption=(select,value,label)=>{const option=make('option',label,select);option.value=value;return option;};
|
||||
|
||||
make('h2','Assign scene music',scenePanel);
|
||||
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel);
|
||||
for(const scene of game.scenes)addOption(scenes,scene.id,scene.name);
|
||||
const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
|
||||
if(selected)scenes.value=selected.id;
|
||||
const assignments=make('div',null,scenePanel);
|
||||
const sceneActions=make('div',null,scenePanel);sceneActions.className='adaptive-actions';
|
||||
button(sceneActions,'Go to Playback',()=>switchTab('playback',true));
|
||||
const defaults=make('details',null,scenePanel);make('summary','World defaults and boss combatants',defaults);
|
||||
const defaultBody=make('div',null,defaults),bossLabel=make('label','Boss combatant',defaults);
|
||||
const bosses=make('select',null,bossLabel),bossBody=make('div',null,defaults),documents=new Map();
|
||||
for(const combat of game.combats??[])for(const combatant of combat.combatants){
|
||||
const key=`${combat.id}:${combatant.id}`;documents.set(key,combatant);addOption(bosses,key,combatant.name??combatant.id);
|
||||
}
|
||||
if(!documents.size){bossLabel.hidden=true;make('p','Create a combatant to assign a boss override.',defaults);}
|
||||
const ownedDetails=make('details',null,scenePanel);make('summary','Foundry fallback playlists',ownedDetails);
|
||||
make('p','Select dedicated music playlists for fallback playback. After saving ownership, reload the world before enabling automation.',ownedDetails);
|
||||
const owned=new Set(game.settings.get(namespace,'ownedPlaylistIds').split(',').filter(Boolean)),boxes=[];
|
||||
const ownedChoices=make('div',null,ownedDetails);ownedChoices.className='adaptive-checklist';
|
||||
for(const playlist of game.playlists){
|
||||
const label=make('label',null,ownedChoices),check=make('input',null,label);check.type='checkbox';check.checked=owned.has(playlist.id);
|
||||
make('span',playlist.name,label);boxes.push({id:playlist.id,check});
|
||||
}
|
||||
const ownershipStatus=make('p',null,ownedDetails);ownershipStatus.setAttribute('role','status');
|
||||
button(ownedDetails,'Save fallback ownership',async()=>{
|
||||
stop();await game.settings.set(namespace,'enabled',false);
|
||||
await game.settings.set(namespace,'ownedPlaylistIds',boxes.filter(box=>box.check.checked).map(box=>box.id).join(','));
|
||||
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
|
||||
},ownershipStatus);
|
||||
|
||||
let choices=[];
|
||||
const showScene=()=>{
|
||||
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
|
||||
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
|
||||
else make('p','Create a scene to assign its playlists.',assignments);
|
||||
};
|
||||
const showBoss=()=>{
|
||||
bossBody.replaceChildren();const document=documents.get(bosses.value);
|
||||
if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
|
||||
};
|
||||
const refreshAssignments=async()=>{
|
||||
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
|
||||
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
|
||||
};
|
||||
scenes.addEventListener('change',showScene);bosses.addEventListener('change',showBoss);
|
||||
await refreshAssignments();
|
||||
|
||||
let development;
|
||||
if(game.settings.get(namespace,'advancedDevelopment')===true){
|
||||
development=dom.createElement('section');make('h3','Optional companion',development);
|
||||
const label=make('label','Companion controller code',development),code=make('input',null,label);code.type='password';code.autocomplete='off';
|
||||
const status=make('p',null,development);status.setAttribute('role','status');
|
||||
button(development,'Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await refreshAssignments();},status);
|
||||
button(development,'Disconnect optional companion',async()=>{await gateway.disconnect();await refreshAssignments();},status);
|
||||
const capabilityLabel=make('label','Companion test capability',development),capability=make('input',null,capabilityLabel);capability.type='password';
|
||||
button(development,'Enable synthetic test audio',async()=>{const value=JSON.parse(capability.value);capability.value='';await audio.start(gateway.audioRequest(value));},status);
|
||||
button(development,'Stop test audio',()=>audio.stop(),status);
|
||||
}
|
||||
const refreshConnection=connection?mountConnectionWizard({game,container:connectionPanel,connection,onCatalog:refreshAssignments,onError,next:()=>switchTab('scene',true),advancedContent:development}):()=>{};
|
||||
refreshPlayback=mountPlaybackPanel({game,container:playbackPanel,connection,getChoices:()=>choices,start,stop,setOverrides,onError});
|
||||
switchTab(this.#tab);
|
||||
clearInterval(this.#timer);
|
||||
if(globalThis.document===dom&&typeof root.isConnected==='boolean'){
|
||||
this.#timer=setInterval(()=>{
|
||||
if(!root.isConnected)return;
|
||||
if(this.#tab==='connection')refreshConnection();
|
||||
if(this.#tab==='playback')void refreshPlayback();
|
||||
},1500);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ import {randomKey,hmac,base64url} from './webcrypto.mjs';
|
||||
import { MusicError } from '../../core/controller.mjs';
|
||||
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
|
||||
export class MAReadClient {
|
||||
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain; #authorizedMedia = new Set(); #targetVolume; #nativePause;
|
||||
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
||||
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #legacyCatalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain; #authorizedMedia = new Set(); #targetVolume; #nativePause;
|
||||
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), legacyCatalogKey, campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
||||
const url = new URL(baseUrl);
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
|
||||
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
|
||||
@@ -13,6 +13,7 @@ export class MAReadClient {
|
||||
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
|
||||
this.#providers = [...new Set(approvedProviders)];
|
||||
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
|
||||
if (legacyCatalogKey) this.#legacyCatalogKey = Uint8Array.from(legacyCatalogKey);
|
||||
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
|
||||
this.#synthetic = structuredClone(syntheticSequences);
|
||||
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
|
||||
@@ -96,8 +97,9 @@ export class MAReadClient {
|
||||
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
|
||||
if (next.has(key)) continue;
|
||||
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
|
||||
next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
||||
choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
||||
const legacyId = this.#legacyCatalogKey && base64url(await hmac(this.#legacyCatalogKey,JSON.stringify([this.#campaign,key])));
|
||||
next.set(key, { id, legacyId, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
||||
choices.push({ provider: 'ma', id, ...(legacyId && {legacyId}), kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
||||
}
|
||||
if (page.length < 100) { complete = true; break; }
|
||||
}
|
||||
@@ -108,7 +110,7 @@ export class MAReadClient {
|
||||
}
|
||||
resolveCatalog(ref) {
|
||||
if (ref?.provider !== 'ma') throw new MusicError('denied');
|
||||
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
|
||||
const entry = [...this.#catalog.values()].find(e => e.id === ref.id || e.legacyId && e.legacyId === ref.id);
|
||||
if (!entry) throw new MusicError('expired-media');
|
||||
if(entry.dynamic)throw new MusicError('unsupported');
|
||||
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
|
||||
@@ -123,7 +125,7 @@ export class MAReadClient {
|
||||
await this.inspectSynthetic(media);
|
||||
return media;
|
||||
}
|
||||
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
|
||||
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id || e.legacyId && e.legacyId===ref.id);
|
||||
if(entry.type==='radio')return media;
|
||||
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
|
||||
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
|
||||
|
||||
@@ -8,6 +8,21 @@ export class MAPlaybackProvider {
|
||||
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
|
||||
}
|
||||
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
|
||||
async playbackStatus() {
|
||||
this.#authority(this.#fence);
|
||||
const queue = await this.#client.queueState();
|
||||
this.#authority(this.#fence);
|
||||
const item = queue.current_item;
|
||||
const paused = this.#paused && queue.state === 'idle' && queue.current_index === this.#paused.index;
|
||||
const elapsed = paused ? this.#paused.position : queue.elapsed_time;
|
||||
const position = Number.isFinite(elapsed) ? Math.max(0, Math.floor(elapsed)) : 0;
|
||||
return {
|
||||
state: paused ? 'paused' : queue.state,
|
||||
title: typeof item?.name === 'string' ? item.name.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 180) : '',
|
||||
duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
|
||||
position,
|
||||
};
|
||||
}
|
||||
#check(ctx) {
|
||||
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
|
||||
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
|
||||
|
||||
@@ -10,8 +10,6 @@
|
||||
.adaptive-music-setup details {padding:0.6rem;border:1px solid var(--color-border-light-primary,#777);border-radius:6px;}
|
||||
.adaptive-music-setup details[open] {display:grid;gap:0.65rem;}
|
||||
.adaptive-music-setup summary {cursor:pointer;font-weight:600;}
|
||||
.adaptive-music-step {display:grid;gap:0.65rem;}
|
||||
.adaptive-music-step[hidden] {display:none;}
|
||||
/* ApplicationV2 and small windows must not inherit theme flex label sizing. */
|
||||
#adaptive-music-setup .window-content {min-width:0;overflow:auto;}
|
||||
#adaptive-music-setup .adaptive-music-setup {width:100%;min-width:0;box-sizing:border-box;align-content:start;}
|
||||
@@ -19,3 +17,29 @@
|
||||
#adaptive-music-setup .adaptive-music-setup input {box-sizing:border-box;}
|
||||
#adaptive-music-setup .adaptive-music-setup input[type="file"] {max-width:100%;height:auto;}
|
||||
#adaptive-music-setup .adaptive-music-setup button {width:100%;flex:none;}
|
||||
|
||||
/* Foundry owns the window. Its content pane is the only scrolling surface. */
|
||||
#adaptive-music-setup {max-inline-size:calc(100vw - 12px);max-block-size:calc(100dvh - 12px);min-inline-size:min(320px,calc(100vw - 12px));min-block-size:min(280px,calc(100dvh - 12px));}
|
||||
#adaptive-music-setup .window-content {overflow:auto;overscroll-behavior:contain;padding:0;}
|
||||
#adaptive-music-setup .adaptive-music-setup {display:block;overflow:visible;max-height:none;padding:0;}
|
||||
#adaptive-music-setup .adaptive-tabs {display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:0.25rem;padding:0.4rem 1rem 0;border-bottom:1px solid var(--color-border-light-primary,#777);}
|
||||
#adaptive-music-setup .adaptive-tabs button {background:transparent;color:inherit;border:0;border-bottom:3px solid transparent;border-radius:0;padding:0.65rem 0.2rem;font-weight:650;line-height:1.25;}
|
||||
#adaptive-music-setup .adaptive-tabs [aria-selected="true"] {border-bottom-color:var(--color-warm-2,#b86b42);color:var(--color-text-emphatic,inherit);}
|
||||
#adaptive-music-setup .adaptive-panel {display:grid;gap:0.8rem;padding:clamp(0.7rem,3vw,1.35rem);min-width:0;}
|
||||
#adaptive-music-setup [hidden] {display:none!important;}
|
||||
#adaptive-music-setup .adaptive-panel h2,#adaptive-music-setup .adaptive-now h3 {margin:0;overflow-wrap:anywhere;}
|
||||
#adaptive-music-setup .adaptive-panel h2 {font-size:1.3rem;font-weight:700;}
|
||||
#adaptive-music-setup .adaptive-fields {display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,13rem),1fr));gap:0.7rem;}
|
||||
#adaptive-music-setup .adaptive-panel label {gap:0.3rem;min-width:0;}
|
||||
#adaptive-music-setup .adaptive-panel input,#adaptive-music-setup .adaptive-panel select {max-width:100%;min-height:2rem;}
|
||||
#adaptive-music-setup .adaptive-actions {display:flex;flex-wrap:wrap;gap:0.45rem;align-items:center;}
|
||||
#adaptive-music-setup .adaptive-actions button,#adaptive-music-setup .adaptive-playback-summary button {width:auto;max-width:100%;padding-inline:0.7rem;}
|
||||
#adaptive-music-setup .adaptive-panel button.adaptive-primary {background:var(--color-cool-4,#264852);color:white;border-color:var(--color-cool-4,#264852);font-weight:700;min-width:min(100%,7.5rem);}
|
||||
#adaptive-music-setup .adaptive-state {font-size:0.85rem;font-weight:700;overflow-wrap:anywhere;}
|
||||
#adaptive-music-setup .adaptive-state[data-connected="true"] {color:var(--color-level-success,#326b48);}
|
||||
#adaptive-music-setup .adaptive-now {display:grid;gap:0.3rem;padding:0.85rem 1rem;border:1px solid var(--color-border-light-primary,#777);border-radius:0.45rem;}
|
||||
#adaptive-music-setup .adaptive-playback-summary {display:flex;align-items:center;flex-wrap:wrap;gap:0.55rem 1rem;}
|
||||
#adaptive-music-setup .adaptive-checklist label {display:flex;align-items:center;gap:0.5rem;}
|
||||
#adaptive-music-setup .adaptive-checklist input {min-height:0;}
|
||||
#adaptive-music-setup details[open] > :not(summary) {margin-block-start:0.5rem;}
|
||||
#adaptive-music-setup [role="alert"] {padding:0.55rem;border-inline-start:3px solid var(--color-level-error,#aa3b30);overflow-wrap:anywhere;}
|
||||
@@ -8,7 +8,9 @@ let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{
|
||||
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 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 connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},test: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:'catalog-ready',catalog:2,audioContext:'closed'};return {target:'dedicated',targetName:'Adaptive Music DEV'}},connect:async()=>{connection.status={state:'connected',catalog:2,audioContext:'running',catalogPlayback:true}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{}};
|
||||
let trackState='playing',position=12;window.controlActions=[];
|
||||
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90}),
|
||||
control:async(action,value)=>{window.controlActions.push(action);if(action==='seek')position=value;else trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}};
|
||||
const Setup=createSetupClass({game,connection,getChoices:async()=>[{provider:'native',id:'native',name:'Foundry fallback'},...catalog],start(){},stop(){},setOverrides(){},onError(){},Base:class{}});
|
||||
document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
|
||||
window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {openAccountConnection,sealAccountConnection} from '../../src/foundry/account-connection.mjs';
|
||||
import {MAReadClient} from '../../src/providers/ma/client.mjs';
|
||||
import {hmac} from '../../src/providers/ma/webcrypto.mjs';
|
||||
|
||||
test('saved account connection is portable ciphertext bound to the same token, world and user',async()=>{
|
||||
const config={maUrl:'https://ma.example.test',targetName:'Development receiver',token:'fixture-token',identityStorage:{secret:'excluded'}};
|
||||
const scope='["https://foundry.example.test","world","gm"]';
|
||||
const saved=await sealAccountConnection(config,config.token,scope);
|
||||
assert.ok(!JSON.stringify(saved).includes(config.maUrl));
|
||||
assert.ok(!JSON.stringify(saved).includes(config.token));
|
||||
assert.deepEqual(await openAccountConnection(JSON.parse(JSON.stringify(saved)),config.token,scope),{maUrl:config.maUrl,targetName:config.targetName});
|
||||
await assert.rejects(openAccountConnection(saved,'different-token',scope),{code:'saved-connection-unavailable'});
|
||||
await assert.rejects(openAccountConnection(saved,config.token,scope.replace('gm','player')),{code:'saved-connection-unavailable'});
|
||||
});
|
||||
|
||||
test('new playlist references are shared across browsers and the original can still resolve its old reference',async()=>{
|
||||
const fetchImpl=async(_url,options)=>Response.json(JSON.parse(options.body).command.includes('/playlists/')?[
|
||||
{name:'Ambient',media_type:'playlist',is_playable:true,provider_mappings:[{provider_instance:'music',item_id:'ambient',available:true}]},
|
||||
]:[]);
|
||||
const common={baseUrl:'https://ma.example.test',token:'fixture-token',target:'dedicated',approvedProviders:['music'],campaign:'test',fetchImpl};
|
||||
const catalogKey=await hmac(new TextEncoder().encode(common.token),'test portable catalog');
|
||||
const originalKey=new Uint8Array(32).fill(1),otherKey=new Uint8Array(32).fill(2);
|
||||
const [old]=await new MAReadClient({...common,catalogKey:originalKey}).catalog();
|
||||
const first=new MAReadClient({...common,catalogKey,legacyCatalogKey:originalKey});
|
||||
const other=new MAReadClient({...common,catalogKey,legacyCatalogKey:otherKey});
|
||||
const [a]=await first.catalog(),[b]=await other.catalog();
|
||||
assert.equal(a.id,b.id);
|
||||
assert.equal(a.legacyId,old.id);
|
||||
assert.notEqual(a.legacyId,b.legacyId);
|
||||
assert.equal(first.resolveCatalog(old),other.resolveCatalog(a));
|
||||
});
|
||||
@@ -25,6 +25,22 @@ test('policy precedence and explicit silence', () => {
|
||||
assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world');
|
||||
assert.equal(candidates({})[0].playlist,null);
|
||||
});
|
||||
test('manual MA controls wait for the scene transition and carry the current fence', async () => {
|
||||
const {controller,provider,log}=fixture();
|
||||
controller.providers.ma=provider;
|
||||
provider.control=async(action,value,ctx)=>{
|
||||
ctx.check();
|
||||
log.push([action,value,ctx.campaign,ctx.session,ctx.generation]);
|
||||
};
|
||||
const transition=controller.update({scene:{id:'ambient',playlist:{provider:'ma',id:'ambient'}}});
|
||||
const pause=controller.control('pause');
|
||||
await Promise.all([transition,pause]);
|
||||
assert.deepEqual(log,[['resolve','ambient'],['apply','ambient'],['pause',undefined,'campaign','session',2]]);
|
||||
const obsolete=controller.control('resume');
|
||||
controller.cancel();
|
||||
await assert.rejects(obsolete,{code:'stale'});
|
||||
assert.equal(log.length,3);
|
||||
});
|
||||
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
|
||||
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
|
||||
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
|
||||
|
||||
@@ -16,11 +16,11 @@ test('GM setup connects catalog into independent scene editors and never persist
|
||||
let flag={},catalog=[];const settings={ownedPlaylistIds:'owned',musicDefaults:{},enabled:false},writes=[];
|
||||
const scene={id:'scene',name:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,value)=>{flag=value;}};
|
||||
const game={user:{isGM:true},playlists:collection([{id:'owned',name:'Owned'}]),scenes:collection([scene]),combats:[],settings:{get:(ns,k)=>settings[k],set:async(ns,k,value)=>{settings[k]=value;writes.push({k,value});}}};
|
||||
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async test(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];return {target:'dedicated',targetName:'Adaptive Music DEV'};},async connect(target){assert.equal(target,'dedicated');},refresh:async()=>{},disconnect:async()=>{}};
|
||||
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},async open(profile){assert.equal(profile.token,'capability-fixture');assert.equal(profile.maUrl,'https://ma.example.test');catalog=[{provider:'ma',id:'opaque-ma',name:'MA fixture',kind:'playlist'}];this.status={state:'connected',hasPrivateDraft:true,catalog:1};},refresh:async()=>{},disconnect:async()=>{}};
|
||||
try{
|
||||
const Setup=createSetupClass({game,connection,audio:{},getChoices:async()=>[{provider:'native',id:'owned',name:'Owned'},...catalog],start(){},stop(){},setOverrides(){},onError:assert.fail,Base:class{}});
|
||||
const root=await new Setup()._renderHTML();const code=descendants(root).find(e=>e.tag==='input'&&e.type==='password');code.value='capability-fixture';descendants(root).find(e=>e.type==='url').value='https://ma.example.test';
|
||||
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Authenticate').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));await descendants(root).find(e=>e.textContent==='Connect audio').listeners.click();
|
||||
await descendants(root).find(e=>e.tag==='button'&&e.textContent==='Connect').listeners.click();assert.equal(code.value,'');assert.ok(!descendants(root).some(e=>e.textContent==='Connect optional companion'));assert.ok(descendants(root).some(e=>e.textContent==='Choose scene music'));
|
||||
const panel=descendants(root).find(e=>e.tag==='fieldset'&&e.children.some(c=>c.tag==='legend'&&c.textContent==='Scene music'));
|
||||
const selects=descendants(panel).filter(e=>e.tag==='select');assert.equal(selects.length,4);assert.ok(selects[0].children.some(o=>o.textContent.includes('MA fixture')));
|
||||
selects[0].value='["ma","opaque-ma"]';selects[1].value='["native","owned"]';selects[3].value='["native","owned"]';
|
||||
@@ -45,10 +45,10 @@ test('failed wizard authentication can retry without reentering token',async()=>
|
||||
const {connectionDraft}=await import('../../src/foundry/connection-draft.mjs');
|
||||
const {mountConnectionWizard}=await import('../../src/foundry/connection-wizard.mjs');
|
||||
const dom={createElement:tag=>new Element(tag,dom)};const container=new Element('div',dom);let draft,attempts=0,errors=0;
|
||||
const connection={get status(){return {hasPrivateDraft:!!draft,state:'disconnected',catalog:0};},async test(profile){draft=connectionDraft(draft,profile,'world');attempts++;assert.equal(draft.token,'private-fixture');if(attempts===1)throw {code:'ws-auth-denied'};return {target:'dedicated',targetName:'Campaign receiver'};}};
|
||||
const connection={get status(){return {hasPrivateDraft:!!draft,state:'disconnected',catalog:0};},get draftFields(){return draft?{maUrl:draft.maUrl,retainedToken:!!draft.token}:{};},async open(profile){draft=connectionDraft(draft,profile,'world');attempts++;assert.equal(draft.token,'private-fixture');if(attempts===1)throw {code:'ws-auth-denied'};}};
|
||||
mountConnectionWizard({game:{user:{isGM:true}},container,connection,onError:()=>errors++});
|
||||
const all=()=>descendants(container);all().find(e=>e.type==='url').value='https://ma.example.test';const token=all().find(e=>e.type==='password');token.value='private-fixture';
|
||||
assert.equal(all().filter(e=>e.type==='file').length,0);
|
||||
const submit=all().find(e=>e.textContent==='Authenticate');await submit.listeners.click();assert.equal(errors,1);assert.equal(token.value,'');
|
||||
const submit=all().find(e=>e.textContent==='Connect');await submit.listeners.click();assert.equal(errors,1);assert.equal(token.value,'');
|
||||
await submit.listeners.click();assert.equal(attempts,2);assert.equal(errors,1);
|
||||
});
|
||||
@@ -35,6 +35,9 @@ class ReleaseTests(unittest.TestCase):
|
||||
with zipfile.ZipFile(io.BytesIO(outer.read('adaptive-music-source.zip'))) as source:
|
||||
self.assertIn('adaptive-music-source/gateway/ma-client.mjs',source.namelist())
|
||||
self.assertFalse(any('/.local/' in n or '/node_modules/' in n for n in source.namelist()))
|
||||
evidence=f"evidence/v{standalone['version']}-live.json"
|
||||
if (ROOT/evidence).is_file():
|
||||
self.assertEqual(outer.read(evidence),source.read(f'adaptive-music-source/{evidence}'))
|
||||
release.validate_package(root/'adaptive-music.zip',standalone)
|
||||
(root/'licenses').mkdir(exist_ok=True)
|
||||
(root/'licenses/unmanaged.txt').write_text('must not be swept into the release')
|
||||
|
||||
Reference in new issue
Block a user