From 78e184a49911b5b8f5f97538c4bf7bb2c203d127 Mon Sep 17 00:00:00 2001 From: "pullfrog[bot]" <226033991+pullfrog[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:14:35 +0000 Subject: [PATCH 1/4] feat: add midi-drums device-access layer Scans for MIDI input devices through the Host's window.feedBack.midiInput capability, opens several at once, and merges their note-ons into one stream tagged by logicalSourceKey. Exposes window.midiDrumsDevices and persists the ticked selection server-side. Notes on a few decisions: - Availability is gated on the midi-input domain being present at version 1, not on navigator.requestMIDIAccess. A missing or mid-version domain is a no-op rather than an error. - discover() is the permission boundary and runs only once the screen is active, so the prompt never appears on someone else's screen. A denied result is recorded but never latched, so Rescan can retry it. - Ticked keys are stored, not labels. A missing device keeps its tick and reopens when it returns; no substitute is ever switched in. - Opens and closes for one source are serialised. The domain refcounts an open session by requester name, so two concurrent opens add a single reference while two closes would remove it twice and orphan the surviving handle. - Device labels are written with textContent throughout: a MIDI device name is user-controlled hardware text. Verified with throwaway jsdom and FastAPI harnesses outside the tree; the repo has no build, lint, or test tooling. --- .gitignore | 2 + CHANGELOG.md | 1 + README.md | 9 + midi-drums/README.md | 151 ++++++++ midi-drums/assets/plugin.css | 168 ++++++++ midi-drums/plugin.json | 32 ++ midi-drums/routes.py | 209 ++++++++++ midi-drums/screen.html | 59 +++ midi-drums/screen.js | 733 +++++++++++++++++++++++++++++++++++ 9 files changed, 1364 insertions(+) create mode 100644 .gitignore create mode 100644 midi-drums/README.md create mode 100644 midi-drums/assets/plugin.css create mode 100644 midi-drums/plugin.json create mode 100644 midi-drums/routes.py create mode 100644 midi-drums/screen.html create mode 100644 midi-drums/screen.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..029519e --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.py[cod] \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c780cd4..41113e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `midi-drums/` — device-access layer for MIDI drum controllers. Scans for input devices through the core `window.feedBack.midiInput` capability, opens several at once, merges their note-ons into one stream tagged with `logicalSourceKey`, and exposes `window.midiDrumsDevices` (`getState`, `subscribe`, `discover`, `setEnabled`, `setActive`, `onHit`, `dispose`). Saved device keys persist server-side through `/api/plugins/midi-drums/settings`. Degrades to a no-op on a Host without the domain and retries a denied permission request rather than latching it. - `nav` field in `my-plugin/plugin.json` (`{ "label": "My Plugin", "screen": "plugin-my-plugin" }`) so the plugin registers a sidebar entry. - `AGENTS.md` — reference guide for AI assistants/contributors covering the actual API shape, plugin conventions, known code notes, and a verification checklist. diff --git a/README.md b/README.md index fbf9d98..8c4f490 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,15 @@ A reference template for creating [feedBack plugins](https://github.com/got-feedBack/feedback-plugin-spec). +## Plugins in this repository + +| Directory | Purpose | +|---|---| +| `my-plugin/` | The reference template described below. Copy and rename it — it is not used as-is. | +| `midi-drums/` | Device-access layer for MIDI drum controllers. Opens several input devices at once and merges their note-ons into one tagged stream, via the Host's `window.feedBack.midiInput` capability rather than the Web MIDI API. See [`midi-drums/README.md`](midi-drums/README.md). | + +Everything below this section documents `my-plugin/` specifically. + ## ⚠️ DISCLAIMER AND WARRANTY **This template is provided "AS-IS" without any warranty of any kind, express or implied.** No warranty is given that this template is correct, complete, safe, or fit for any particular purpose. diff --git a/midi-drums/README.md b/midi-drums/README.md new file mode 100644 index 0000000..8380dfa --- /dev/null +++ b/midi-drums/README.md @@ -0,0 +1,151 @@ +# midi-drums + +Device-access layer for MIDI drum controllers. Scans for input devices, opens +several at once, and merges their note-ons into a single tagged stream — the +foundation the kit-profile work builds on. + +This plugin never touches the Web MIDI API. It goes through the Host's +capability layer, `window.feedBack.midiInput`, and is written to work when that +domain is absent or mid-version. + +## Files + +| File | Purpose | +|---|---| +| `plugin.json` | Manifest — capability declaration, `type: "input"`, nav entry, no settings panel | +| `screen.html` | Device list, rescan control, saved-device status, bounded hit log | +| `screen.js` | Device layer (`window.midiDrumsDevices`) + screen lifecycle | +| `routes.py` | Server-persisted selection (`source_keys`) at `/api/plugins/midi-drums/settings` | +| `assets/plugin.css` | Styling scoped to the plugin | + +## How it talks to MIDI + +`plugin.json` asks for a narrow slice of the domain: + +```json +"capabilities": { + "midiInput": { + "roles": ["requester"], + "requests": ["discover", "list-sources", "select-source", "open-source", "close-source"], + "mode": "active", + "compatibility": "degrade-noop", + "ownership": "requester-only", + "safety": "sensitive", + "version": 1 + } +} +``` + +- **`mode: "active"`** — the screen calls `discover()` only once it is the + active screen, so the permission prompt never appears while the user is on + some other part of the Host. +- **`compatibility: "degrade-noop"`** — an older Host without the domain still + loads the plugin. The screen explains the situation instead of failing. +- **`ownership: "requester-only"`** — the plugin never asserts itself as a MIDI + provider, so it cannot collide with core `input_setup`. +- **`safety: "sensitive"`** — device access is a deliberate user act, reached + through an explicit tick per device. + +`availability` is gated on `mi && mi.version === 1`, not on +`navigator.requestMIDIAccess`. A version mismatch, a late-loading domain, and a +genuinely unavailable Host all read as "not available" rather than as a crash. + +## The `window.midiDrumsDevices` API + +```js +const devices = window.midiDrumsDevices; + +const state = devices.getState(); +// { available, ready, discovered, active, sources, savedKeys, openKeys, +// status: 'idle'|'scanning'|'ready'|'empty'|'denied'|'unavailable'|'failed', +// reason } + +const stop = devices.subscribe((state) => { /* re-render */ }); +stop(); // unsubscribe + +await devices.discover({ force: true }); // retry after denial +devices.setEnabled('web-midi::pads', true); +devices.setActive(false); // close everything, no rediscovery +devices.dispose(); // release listeners + bus handles + +const offHits = devices.onHit((hit) => { +// hit.logicalSourceKey, hit.note, hit.velocity, hit.channel (0-based) +}); +offHits(); +``` + +`subscribe` fires immediately with the current state. `onHit` is the merged +stream across every open source; each hit carries the `logicalSourceKey` it came +from, so a consumer never has to track connections itself. + +## Device identity + +Sources are keyed by `logicalSourceKey` (`web-midi::`), never by a +label or list index. Labels come from user-supplied hardware and can change or +be duplicated between connections; keys do not. The selected keys are persisted +in `routes.py`, so a selection survives reloads. + +## Behaviour worth knowing + +- **Replug, no fallback-switching.** A ticked device that is unplugged keeps its + tick, the screen says it will reopen automatically, and a different device is + *never* substituted in its place. A stale or renamed device must not silently + become someone else's input. +- **Denial is retryable.** `discover()` is the permission boundary, so a denied + result is recorded but never latched — the rescan button re-runs it. +- **Per-source serialisation.** The domain keeps one shared session per source, + refcounted by requester name. Two concurrent opens add a single reference, + while two closes would remove it twice and tear the session out from under + whichever open survived. Every open and close for a source therefore runs + through a promise chain (`chains` in `screen.js`), and a superseded open + releases the reference it just took. A redundant queued open short-circuits, + which is what keeps one listener per source. +- **Opens never outrun the screen.** `active` is re-checked where the open + actually happens, not just before the loop that started it. A user who + navigates away while a tick's POST is still in flight would otherwise leave a + session that `closeAll()` had already walked past. +- **Generation guard.** Each source carries a generation counter, bumped on + every close. An `open()` that resolves against a retired generation is + discarded rather than resurrecting a session the user has already cancelled. +- **Everything closes.** Sessions are released on untick, unplug, `screen: + changing`, `pagehide`, and view disposal. `screen:changed` and `pageshow` + reopen the saved selection. `screen:changing` is best-effort rather than a + spec guarantee; `pagehide` is the guaranteed backstop. +- **Late Host wiring.** `window.feedBack` and the `midiInput` domain can both + appear after this script runs. The bus subscription is retried on every + activation, including no-op transitions, so a late bus cannot silently kill + replug recovery for the session. +- **Only declared verbs.** The plugin calls the five verbs in `plugin.json` and + nothing else. `getSelected()` is treated as an optional optimisation: absent + or throwing is normal, since a Host may implement only what is declared. +- **Device labels use `textContent`.** A MIDI device name is user-controlled + hardware text and is never parsed as markup. +- **Bounded work.** At most 8 sources and 200 characters per key + (`MAX_SOURCES` / `MAX_SOURCE_KEY_LEN`, matching `routes.py`), so an over-long + key can't turn every save into a rejected POST; the hit log keeps its newest + 12 rows and its own running total. +- **Settings failures degrade.** A failed load leaves discovery intact; a failed + save keeps the session and the in-memory selection working. Saves are + chained, so overlapping POSTs can't roll the file back to an older selection. +- **A hand-edited config can't wipe a selection.** POST validates strictly, but + a file containing one bad entry is salvaged key-by-key on read rather than + discarded wholesale, and writes go through a temp file + rename so a torn + write cannot produce the corrupt JSON that recovery would then treat as empty. + +## Verification + +The repository has no build, lint, or test tooling, so verification was done +with throwaway harnesses outside the tree (jsdom + a fake MIDI domain, and +FastAPI + `httpx` against `routes.py`). Behaviour covered: fail-soft on an +absent domain, late domain arrival, denial then retry, two simultaneous sources +with tagged/merged hits, note-on filtering (note-off, zero-velocity strikes and +other channel traffic ignored), replug without fallback-switching, close and +reopen across screen changes, no discovery while inactive, rescan picking up a +later device, idempotent re-hydration, the source cap and its visible rejection, +the bounded hit log, settings-load/save failure, navigating away mid-save, a +Host without `getSelected()`, and a bus that only appears after the script runs. + +For a manual pass, follow the checklist in the repository `AGENTS.md` against a +real Host build with a device attached: the plugin loads, the nav entry appears, +ticking a device opens it, strikes show in the hit log, and navigating away +closes the session. \ No newline at end of file diff --git a/midi-drums/assets/plugin.css b/midi-drums/assets/plugin.css new file mode 100644 index 0000000..7b60a58 --- /dev/null +++ b/midi-drums/assets/plugin.css @@ -0,0 +1,168 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Styles for midi-drums. + * + * Every selector is scoped under `.midi-drums`, the plugin's own root class, + * so nothing leaks into the rest of the app (spec §6.3, §6.6). The Host applies + * these styles only while the plugin's screen is active. + */ + +.midi-drums { + display: flex; + flex-direction: column; + gap: 1.25rem; + padding: 1.5rem; + max-width: 720px; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, + "Helvetica Neue", Arial, sans-serif; +} + +.midi-drums__header { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.midi-drums__title { + margin: 0; + font-size: 1.4rem; + font-weight: 600; + line-height: 1.2; +} + +.midi-drums__lede { + margin: 0; + font-size: 0.95rem; + opacity: 0.75; +} + +.midi-drums__panel { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1rem; + border: 1px solid rgba(128, 128, 128, 0.3); + border-radius: 8px; +} + +.midi-drums__panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; +} + +.midi-drums__panel-title { + margin: 0; + font-size: 1rem; + font-weight: 600; +} + +.midi-drums__counter { + font-size: 1rem; + font-weight: 700; + font-variant-numeric: tabular-nums; +} + +.midi-drums__hint { + margin: 0; + font-size: 0.85rem; + opacity: 0.7; + line-height: 1.45; +} + +.midi-drums__empty { + margin: 0; + font-size: 0.9rem; + opacity: 0.6; + font-style: italic; +} + +.midi-drums__saved { + margin: 0; + font-size: 0.8rem; + opacity: 0.65; +} + +.midi-drums__devices, +.midi-drums__hits { + margin: 0; + padding: 0; + list-style: none; + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.midi-drums__device { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 0.45rem 0.6rem; + border: 1px solid rgba(128, 128, 128, 0.25); + border-radius: 6px; +} + +.midi-drums__device label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.95rem; + cursor: pointer; + min-width: 0; +} + +.midi-drums__device-box { + width: 1em; + height: 1em; + flex: none; + cursor: pointer; +} + +.midi-drums__device-label { + overflow-wrap: anywhere; +} + +.midi-drums__device-meta { + flex: none; + font-size: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.04em; + opacity: 0.6; + font-variant-numeric: tabular-nums; +} + +.midi-drums__hit { + padding: 0.3rem 0.6rem; + border-left: 3px solid rgba(128, 128, 128, 0.5); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +.midi-drums__button { + padding: 0.35rem 0.9rem; + font: inherit; + font-size: 0.85rem; + color: inherit; + background: transparent; + border: 1px solid currentColor; + border-radius: 4px; + cursor: pointer; + transition: background-color 0.2s; +} + +.midi-drums__button:hover { + background-color: rgba(128, 128, 128, 0.12); +} + +@media (prefers-color-scheme: dark) { + .midi-drums__device, + .midi-drums__panel { + border-color: rgba(255, 255, 255, 0.12); + } + + .midi-drums__hit { + border-left-color: rgba(255, 255, 255, 0.35); + } +} \ No newline at end of file diff --git a/midi-drums/plugin.json b/midi-drums/plugin.json new file mode 100644 index 0000000..9009cdc --- /dev/null +++ b/midi-drums/plugin.json @@ -0,0 +1,32 @@ +{ + "id": "midi-drums", + "name": "MIDI Drums", + "version": "0.1.0", + "description": "Reads drum triggers from MIDI devices through the core midi-input domain, so calibration and scoring work on any keyboard, pad controller or e-kit module.", + "type": "input", + "nav": { "label": "MIDI Drums", "screen": "plugin-midi-drums" }, + "screen": "screen.html", + "script": "screen.js", + "scriptType": "classic", + "styles": "assets/plugin.css", + "routes": "routes.py", + "category": "practice", + "standards": [ + "capability-pipelines.v1", + "plugin-runtime-idempotent.v1" + ], + "capabilities": { + "midi-input": { + "roles": ["requester"], + "requests": ["discover", "list-sources", "select-source", "open-source", "close-source"], + "mode": "active", + "compatibility": "degrade-noop", + "ownership": "requester-only", + "safety": "sensitive", + "version": 1, + "description": "Picks the drum-trigger MIDI devices through the core midi-input domain (the Web-MIDI provider ships built-in with the domain). Absent domain means no MIDI devices; the plugin fails soft." + } + }, + "icon": "🥁", + "minHost": "1.0.0" +} \ No newline at end of file diff --git a/midi-drums/routes.py b/midi-drums/routes.py new file mode 100644 index 0000000..862d316 --- /dev/null +++ b/midi-drums/routes.py @@ -0,0 +1,209 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Server routes for midi-drums. + +Persists which logicalSourceKeys the user has ticked as drum-trigger devices, so +a reload (or a replug after an unplug) reopens the same devices instead of +guessing. Keys — not device labels — are stored: a label is hardware text that +can change with a driver update, while the domain's logicalSourceKey is stable +per provider + source id. + +Follows the same shape as the template's routes.py: all work happens inside +setup(), configuration is read tolerantly, routes are namespaced under the +plugin id, and setup() validates before registering anything. +""" + +import asyncio +import json +import logging +import os +import threading +from pathlib import Path + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse + +PLUGIN_ID = "midi-drums" +MAX_SETTINGS_BODY_BYTES = 16 * 1024 +# Must match MAX_SOURCES in screen.js: the client caps its selection here, and +# the server refuses anything larger rather than silently truncating. +MAX_SOURCE_KEYS = 8 +# Must match MAX_SOURCE_KEY_LEN in screen.js, so an over-long key read back from +# here can still be re-saved without the server rejecting the POST. +MAX_SOURCE_KEY_LEN = 200 +_DEFAULTS = { + "source_keys": [], +} + + +def _is_valid_setting(name: str, value: object) -> bool: + """Return whether a setting value matches the device-selection schema.""" + if name != "source_keys": + return False + if not isinstance(value, list) or len(value) > MAX_SOURCE_KEYS: + return False + # `type(x) is str` rather than isinstance: nothing else should reach here, + # and bool/int slipping in as a key would produce an unopenable selection. + if any(type(item) is not str for item in value): + return False + if any(not item or len(item) > MAX_SOURCE_KEY_LEN for item in value): + return False + # A duplicate would open one device twice — the client never sends one, so + # this only rejects a hand-edited file, which _read() then salvages. + return len(set(value)) == len(value) + + +def _sanitise_source_keys(keys: object) -> list: + """Coerce a persisted source_keys value into something openable. + + Keeps every usable key and drops only the unusable ones, rather than + discarding the whole selection because of one bad entry: a file with a + duplicate, an over-long key, or a stray non-string would otherwise silently + reset the user to "no devices" and lose every valid key in it. Enforced + order and de-duplication also make the "no duplicate opens" invariant hold + even for a hand-edited file. + """ + if not isinstance(keys, list): + return [] + clean = [] + for key in keys: + if type(key) is not str or not key or len(key) > MAX_SOURCE_KEY_LEN: + continue + if key in clean: + continue + clean.append(key) + if len(clean) == MAX_SOURCE_KEYS: + break + return clean + + +def setup(app: FastAPI, context: dict) -> None: + """Register routes for midi-drums. + + Args: + app: FastAPI application instance + context: dict with config_dir and log keys + """ + config_dir = Path(context["config_dir"]) + log = context.get("log") or logging.getLogger(f"feedBack.plugin.{PLUGIN_ID}") + config_file = config_dir / f"{PLUGIN_ID}.json" + # The read-modify-write in _merge_and_persist runs in a worker thread, so it + # is guarded by a threading lock. Two overlapping POSTs would otherwise + # interleave their read and write and lose one of the two selections. + write_lock = threading.Lock() + + def _read() -> dict: + """Read the persisted device selection, tolerating a bad file.""" + if not config_file.exists(): + return {"source_keys": []} + try: + data = json.loads(config_file.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + log.warning("%s: unreadable config, using defaults: %s", PLUGIN_ID, exc) + return {"source_keys": []} + if not isinstance(data, dict): + return {"source_keys": []} + # Rebuilt per read rather than shallow-copied from _DEFAULTS, so an + # in-place edit here can't reach the module-level default list. + settings = {"source_keys": []} + for key, value in data.items(): + if key not in _DEFAULTS: + continue + settings[key] = _sanitise_source_keys(value) + return settings + + # Fail fast on an unusable config_dir, before any route is registered — a + # path we cannot even name would otherwise surface as a 500 on first use. + try: + config_dir.mkdir(parents=True, exist_ok=True) + _read() + log.info("%s: configuration validated", PLUGIN_ID) + except Exception as exc: + log.error("%s: configuration validation failed: %s", PLUGIN_ID, exc) + raise + + @app.get(f"/api/plugins/{PLUGIN_ID}/settings") + def get_settings() -> JSONResponse: + """Get the saved drum-trigger device selection.""" + return JSONResponse(_read()) + + @app.post(f"/api/plugins/{PLUGIN_ID}/settings") + async def set_settings(request: Request) -> JSONResponse: + """Replace the saved drum-trigger device selection. + + Accepts a bounded JSON object holding `source_keys` — the logical source + keys of the ticked devices, in the user's order. Sending the key + replaces the saved selection outright rather than adding to it, so + unticking the last device ("none left") is expressible. + """ + content_length = request.headers.get("content-length") + if content_length is not None: + try: + content_length_value = int(content_length) + if content_length_value < 0: + return JSONResponse( + {"error": "invalid Content-Length header"}, status_code=400 + ) + if content_length_value > MAX_SETTINGS_BODY_BYTES: + return JSONResponse( + {"error": "request body too large"}, status_code=413 + ) + except ValueError: + return JSONResponse( + {"error": "invalid Content-Length header"}, status_code=400 + ) + + body = bytearray() + try: + async for chunk in request.stream(): + if len(body) + len(chunk) > MAX_SETTINGS_BODY_BYTES: + return JSONResponse( + {"error": "request body too large"}, status_code=413 + ) + body.extend(chunk) + incoming = json.loads(body) + except (UnicodeDecodeError, ValueError): + return JSONResponse({"error": "invalid JSON body"}, status_code=400) + + if not isinstance(incoming, dict): + return JSONResponse( + {"error": "body must be a JSON object"}, status_code=400 + ) + if incoming.keys() - _DEFAULTS.keys(): + return JSONResponse( + {"error": "body contains unknown settings"}, status_code=400 + ) + if not all(_is_valid_setting(key, value) for key, value in incoming.items()): + return JSONResponse( + {"error": "body contains invalid setting values"}, status_code=400 + ) + + def _merge_and_persist() -> dict: + """Merge incoming settings with existing ones and persist. Runs off + the event loop (asyncio.to_thread below) since _read() and the write + are blocking filesystem calls, and set_settings must stay `async def` + to stream the request body above.""" + with write_lock: + merged = {**_read(), **incoming} + config_dir.mkdir(parents=True, exist_ok=True) + # Written to a sibling then renamed: a torn or truncated write + # would leave invalid JSON, and _read()'s corrupt-file recovery + # would then reset the user's whole selection to empty. + tmp_file = config_file.with_name(config_file.name + ".tmp") + tmp_file.write_text(json.dumps(merged, indent=2), encoding="utf-8") + os.replace(tmp_file, config_file) + return merged + + try: + merged = await asyncio.to_thread(_merge_and_persist) + log.info("%s: device selection updated (%d source(s))", PLUGIN_ID, len(merged["source_keys"])) + except Exception as exc: + log.error("%s: failed to write settings: %s", PLUGIN_ID, exc) + # The exception text can carry absolute filesystem paths, so it is + # logged rather than returned to the caller. + return JSONResponse( + {"error": "failed to save settings"}, status_code=500 + ) + + return JSONResponse(merged) + + log.info("%s: routes registered", PLUGIN_ID) \ No newline at end of file diff --git a/midi-drums/screen.html b/midi-drums/screen.html new file mode 100644 index 0000000..251b939 --- /dev/null +++ b/midi-drums/screen.html @@ -0,0 +1,59 @@ + +
+
+

MIDI Drums

+

Looking for MIDI devices…

+
+ +
+
+

Trigger devices

+ +
+ +

+ Tick every device that sends drum triggers. A kick pedal on one interface + and pads on another can be open at the same time — each hit is tagged + with the device it came from, so calibration can tell them apart. +

+ + + +
    + + +
    + +
    +
    +

    Incoming hits

    + 0 +
    + +

    + Note-ons from every open device, newest first. If this stays empty while + you are hitting pads, the right device is not ticked. +

    + +

    + Waiting for input… +

    + +
      +
      +
      \ No newline at end of file diff --git a/midi-drums/screen.js b/midi-drums/screen.js new file mode 100644 index 0000000..cb4b559 --- /dev/null +++ b/midi-drums/screen.js @@ -0,0 +1,733 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// +// Client screen + device layer for midi-drums. +// +// MIDI devices are reached through the core `midi-input` capability domain +// (`window.feedBack.midiInput`), never through a private +// `navigator.requestMIDIAccess()` call. That is the shared device-access +// boundary `input_setup` and `drum_highway_3d` already use: one permission +// prompt, one source list, and uniform behaviour for a MIDI keyboard, a generic +// pad controller or an e-kit module — Web MIDI abstracts all three identically +// at this layer. +// +// What this file owns is device access only. Kit calibration, drum-chart +// consumption and scoring build on top of `window.midiDrumsDevices`, which +// already hands them a single logical stream of note-ons tagged with the +// `logicalSourceKey` they arrived on (so a kick pedal on one interface and pads +// on another stay distinguishable). +(function () { + 'use strict'; + + const PLUGIN_ID = 'midi-drums'; + const SCREEN_ID = `plugin-${PLUGIN_ID}`; + // Identifies us to the domain's shared open/close refcount. One requester + // name per plugin, matching `input_setup`'s usage. + const REQUESTER = PLUGIN_ID; + const GLOBAL_KEY = 'midiDrumsDevices'; + const VIEW_KEY = `__${PLUGIN_ID}_view`; + // Bounded so a device farm can't grow the persisted selection without limit. + // These must match MAX_SOURCE_KEYS / MAX_SOURCE_KEY_LEN in routes.py. + const MAX_SOURCES = 8; + const MAX_SOURCE_KEY_LEN = 200; + const MAX_HIT_ROWS = 12; + + // ── domain access ────────────────────────────────────────────────────── + + // Availability is the midi-input DOMAIN being present, not the Web-MIDI + // browser API. The domain coordinates providers — the built-in Web-MIDI one + // plus any native/desktop adapter — so gating on + // `navigator.requestMIDIAccess` would hide a usable non-Web-MIDI provider + // before discover() has ever run. + function midiDomain() { + const mi = window.feedBack && window.feedBack.midiInput; + return (mi && mi.version === 1) ? mi : null; + } + + // ── device layer ─────────────────────────────────────────────────────── + // + // A singleton installed once on `window`. The Host may execute screen.js + // more than once in a session (spec §6.1), and a second copy of this layer + // would mean a second set of bus listeners and a second open session per + // device — each MIDI hit then delivered twice. + function createDeviceLayer() { + // logicalSourceKey → { handle, listener } for every source we hold open. + const sessions = new Map(); + // logicalSourceKey → generation. An open() that resolves after the user + // switched away from that source (or unplugged it) must not install a + // session for it. Scoped per key, so tearing down one device doesn't + // discard an unrelated in-flight open. + const generations = new Map(); + // The user's ticked selection, server-persisted. This is also the + // recovery target after an unplug: a device that disappears is closed, + // never silently replaced by a substitute. + let savedKeys = []; + let keysLoaded = false; + // discover() has succeeded. Only a `handled` outcome latches, so a + // denied or unavailable result leaves the screen able to prompt again. + let discovered = false; + let discovering = null; + let lastOutcome = null; + // Screen-visibility gate (spec §6.2): MIDI delivery is suspended while + // our screen is not the active one. + let active = false; + let sourcesChangedBound = false; + const hitListeners = new Set(); + const stateListeners = new Set(); + const activateListeners = new Set(); + + function nextGeneration(key) { + const next = (generations.get(key) || 0) + 1; + generations.set(key, next); + return next; + } + + function listSources() { + const mi = midiDomain(); + if (!mi) return []; + try { return mi.listSources() || []; } catch (_) { return []; } + } + + function getState() { + const mi = midiDomain(); + return { + available: !!mi, + discovered, + active, + outcome: lastOutcome ? { ...lastOutcome } : null, + sources: mi ? listSources() : [], + openKeys: Array.from(sessions.keys()), + savedKeys: savedKeys.slice(), + }; + } + + function emitState() { + const state = getState(); + stateListeners.forEach((fn) => { + try { fn(state); } catch (_) { /* one bad subscriber must not stop the rest */ } + }); + } + + // ── permission boundary ────────────────────────────────────────────── + + async function discover(opts) { + const force = !!(opts && opts.force); + const mi = midiDomain(); + if (!mi) { + lastOutcome = { outcome: 'unavailable', reason: 'The midi-input domain is not registered.' }; + emitState(); + return lastOutcome; + } + if (discovered && !force) return lastOutcome || { outcome: 'handled', reason: '' }; + if (discovering) return discovering; + + discovering = (async () => { + let result; + try { + // The permission boundary. `requestMIDIAccess()` lives in + // core's built-in Web-MIDI provider, behind this call. + result = await mi.discover(); + } catch (err) { + result = { outcome: 'failed', reason: String((err && err.message) || err) }; + } + lastOutcome = { + outcome: (result && result.outcome) || 'failed', + reason: (result && result.reason) || '', + }; + discovered = lastOutcome.outcome === 'handled'; + // Render before restoring so the view's label map is populated: + // restore() opens sessions, and a device can strike the instant + // it opens, which would otherwise log a bare key on first hits. + emitState(); + await restore(); + return lastOutcome; + })(); + + try { + return await discovering; + } finally { + discovering = null; + } + } + + // ── open / close ───────────────────────────────────────────────────── + // + // The domain keeps one shared open session per source, refcounted by + // requester NAME: two opens under the same name add a single reference, + // while two closes would remove it twice and tear the session out from + // under whichever open survived. So every open and close for a source is + // serialised through `chains`, which keeps our reference count paired + // with the domain's no matter how the calls interleave. + const chains = new Map(); + + function enqueue(key, task) { + const prev = chains.get(key) || Promise.resolve(); + const next = prev.then(task, task); + const tail = next.catch(() => { /* the task handles its own errors */ }); + chains.set(key, tail); + // Forget a source nobody is holding, so a churn of hot-plugged + // device keys can't grow this map for the life of the session. + tail.then(() => { + if (chains.get(key) === tail && !sessions.has(key)) chains.delete(key); + }); + return next; + } + + function closeSource(key) { + // Retire the generation first, so an open() still in flight for + // this key is discarded rather than resurrecting the session. + nextGeneration(key); + const session = sessions.get(key); + if (!session) return; // nothing to release: no reference was taken + sessions.delete(key); + try { session.handle.removeListener(session.listener); } catch (_) { /* best-effort */ } + enqueue(key, () => { + const mi = midiDomain(); + if (!mi) return; + try { mi.close({ requester: REQUESTER, logicalSourceKey: key }); } catch (_) { /* best-effort */ } + }); + } + + async function openSource(key) { + const mi = midiDomain(); + if (!mi || !key) return false; + if (sessions.has(key)) return true; + return enqueue(key, async () => { + // A queued open may have finished while this one waited its + // turn. Re-checking here is what keeps one listener per source: + // the domain returns the same shared handle to a second open, + // so installing a second listener would double every hit. + if (sessions.has(key)) return true; + // The user can leave the screen while this task waits its turn + // (or while the tick's POST is still in flight). Opening then + // would strand a session that closeAll() has already passed. + if (!active) return false; + const gen = nextGeneration(key); + try { + // The domain keeps one selected key. Point it at a source of + // ours so the Host (and `input_setup`) see a coherent pick + // even though several devices are open at once. + await mi.select(key); + } catch (_) { /* selection is advisory — open() is what matters */ } + + let res; + try { + res = await mi.open({ requester: REQUESTER, logicalSourceKey: key }); + } catch (err) { + lastOutcome = { outcome: 'failed', reason: String((err && err.message) || err) }; + emitState(); + return false; + } + // Superseded while opening: the device was unplugged, unticked, + // or the screen was left. Release the reference we just took — + // safe to do unconditionally, because `chains` guarantees no + // other open for this source is pending or live. + if (generations.get(key) !== gen) { + try { mi.close({ requester: REQUESTER, logicalSourceKey: key }); } catch (_) { /* best-effort */ } + return false; + } + if (!res || !res.handle) { + // Deliberately no close() here. A resolved result with no + // handle means the domain declined (denied/failed/ + // unavailable) and, per the domain's own failure paths, + // took no reference — so closing would decrement a refcount + // we never incremented, tearing down a session another + // requester (core `input_setup`) legitimately owns. The + // other two failure branches above us DO hold a handle, and + // so DO release it. + lastOutcome = { + outcome: (res && res.outcome) || 'unavailable', + reason: (res && res.reason) || '', + }; + emitState(); + return false; + } + + const listener = (data) => onHit(key, data); + try { + res.handle.addListener(listener); + } catch (err) { + try { mi.close({ requester: REQUESTER, logicalSourceKey: key }); } catch (_) { /* best-effort */ } + lastOutcome = { outcome: 'failed', reason: String((err && err.message) || err) }; + emitState(); + return false; + } + sessions.set(key, { handle: res.handle, listener }); + return true; + }); + } + + function closeAll() { + for (const key of Array.from(sessions.keys())) closeSource(key); + } + + // Re-open every ticked source that is currently present. Called on + // activation and after a replug; never adds a source the user did not + // tick, so a transient unplug can't switch the kit to another device. + async function restore() { + if (!active || !discovered) return; + const present = new Set(listSources().map((s) => s.logicalSourceKey)); + for (const key of savedKeys) { + // Re-checked per device: each openSource() awaits the network + // and the domain, so the screen can go inactive mid-loop. Opening + // the rest would strand sessions nothing will close. + if (!active) return; + if (present.has(key) && !sessions.has(key)) await openSource(key); + } + syncPrimarySelection(); + } + + // The domain tracks a single selected key. With several devices open we + // pin it to the first ticked one, so the Host's selection stays on a + // source we are actually using rather than oscillating with whichever + // box was ticked last. + function syncPrimarySelection() { + const mi = midiDomain(); + if (!mi) return; + const primary = savedKeys.find((key) => sessions.has(key)) || null; + if (!primary) return; + // getSelected() is an optimisation only, and it is not among the + // verbs this plugin declares in plugin.json. A Host that doesn't + // implement it simply has nothing to compare against — so an + // absent or throwing getter is normal, not an error. + let current = null; + try { current = typeof mi.getSelected === 'function' ? mi.getSelected() : null; } catch (_) { current = null; } + if (primary === current) return; + try { mi.select(primary); } catch (_) { /* best-effort */ } + } + + // ── the merged logical stream ─────────────────────────────────────── + + function onHit(key, data) { + if (!data || data.length < 3) return; + // 0x90 is note-on on any channel; velocity 0 is a note-off under + // running status, so only a real strike counts. + if ((data[0] & 0xf0) !== 0x90 || data[2] <= 0) return; + const hit = { + // Which device this arrived on — the tag calibration needs to + // disambiguate a kick pedal on one interface from pads on another. + logicalSourceKey: key, + note: data[1], + velocity: data[2], + channel: data[0] & 0x0f, + at: performance.now(), + }; + hitListeners.forEach((fn) => { + try { fn(hit); } catch (_) { /* listener isolation */ } + }); + } + + // ── replug / unplug ────────────────────────────────────────────────── + + function onSourcesChanged() { + const present = new Set(listSources().map((s) => s.logicalSourceKey)); + // A vanished source is gone for now: drop its listener and release + // the session. `savedKeys` is deliberately untouched so the same + // device is picked up again when it returns. + for (const key of Array.from(sessions.keys())) { + if (!present.has(key)) closeSource(key); + } + // Recovery for the saved devices that are back — no fallback-switch. + Promise.resolve(restore()).catch(() => {}); + emitState(); + } + + // The bus may not exist yet when screen.js first runs (async Host boot), so + // this stays retryable: without it, a late bus would silently kill + // replug recovery for the whole session. Idempotent — the flag means + // "already subscribed", not "already attempted". + function bindSourcesChanged() { + if (sourcesChangedBound) return; + const bus = window.feedBack; + if (!bus || typeof bus.on !== 'function') return; + sourcesChangedBound = true; + bus.on('midi-input:sources-changed', onSourcesChanged); + } + + // ── selection + persistence ────────────────────────────────────────── + + // Every tick POSTs the whole selection, so overlapping saves would race: an + // earlier-issued request can land after a later one and roll the file + // back. Chaining them keeps saves ordered and last-write-wins. + let persistQueue = Promise.resolve(); + + function persist() { + persistQueue = persistQueue.then(async () => { + try { + const res = await fetch(`/api/plugins/${PLUGIN_ID}/settings`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ source_keys: savedKeys }), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + } catch (err) { + // Fail soft: the selection still works for this session. + console.warn(`${PLUGIN_ID}: could not save the device selection`, err); + } + }); + return persistQueue; + } + + async function loadSaved() { + try { + const res = await fetch(`/api/plugins/${PLUGIN_ID}/settings`); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const settings = await res.json(); + const keys = settings && settings.source_keys; + if (Array.isArray(keys)) { + savedKeys = keys + .filter((key) => typeof key === 'string' && key) + .slice(0, MAX_SOURCES) + // Same bound the server enforces, so an over-long key + // can't turn every save into a rejected POST. + .map((key) => key.slice(0, MAX_SOURCE_KEY_LEN)); + } + } catch (err) { + console.warn(`${PLUGIN_ID}: could not load the saved device selection`, err); + } + keysLoaded = true; + emitState(); + } + + async function setEnabled(key, enabled) { + if (!key) return false; + const next = new Set(savedKeys); + if (enabled) { + if (next.size >= MAX_SOURCES) { + // Re-render so the tick the user just made is visibly + // rejected, instead of leaving a box checked for a device + // we did not open. + emitState(); + return false; + } + next.add(key); + } else { + next.delete(key); + closeSource(key); + } + savedKeys = Array.from(next); + await persist(); + // Persist first: a device that is unplugged the instant after the + // tick must still be in the saved set, or recovery has nothing to + // reconnect to. + // + // openSource() re-checks `active` itself, so a user who leaves the + // screen while this POST is in flight gets no stranded session. + if (enabled) await openSource(key); + syncPrimarySelection(); + emitState(); + return true; + } + + // ── screen lifecycle ───────────────────────────────────────────────── + + function setActive(next) { + // Bus binding is retried on every call, including a no-op + // transition: the Host can install `window.feedBack` after this + // script runs, while the layer is already active. Both hooks are + // flag-guarded, so repeating them costs nothing. + bindSourcesChanged(); + // Views use this to re-subscribe their own bus handlers, which face + // the same late-bus problem. + activateListeners.forEach((fn) => { + try { fn(); } catch (_) { /* one bad listener must not block activation */ } + }); + if (active === !!next) return; + active = !!next; + if (!active) { + // Exit path: release every session rather than leaving a device + // held open behind a screen nobody is looking at. `savedKeys` + // survives, so re-entering restores the same devices. + closeAll(); + emitState(); + return; + } + // The bus may only have appeared since the last activation. + if (!keysLoaded) { + // Serialise: the persisted selection decides what to re-open, + // so it has to land before discovery triggers `restore()`. + loadSaved().then(() => activate()).catch(() => {}); + } else { + activate().catch(() => {}); + } + } + + async function activate() { + await discover(); + // discover() short-circuits once it has succeeded, so it cannot be + // the only thing that re-opens devices: returning to the screen (or + // re-binding after a re-hydration) has to restore them here too. + // restore() skips sources that are already open. + await restore(); + } + + // Terminal teardown, used when screen.js is re-executed so the previous + // layer cannot leave a second set of listeners or a live session behind. + // Callers must re-bind a view afterwards, which is why this clears the + // subscriber sets rather than leaving a half-dead view subscribed to + // state it can no longer render. + function dispose() { + setActive(false); + const bus = window.feedBack; + if (sourcesChangedBound && bus && typeof bus.off === 'function') { + try { bus.off('midi-input:sources-changed', onSourcesChanged); } catch (_) { /* best-effort */ } + } + sourcesChangedBound = false; + hitListeners.clear(); + stateListeners.clear(); + activateListeners.clear(); + } + + bindSourcesChanged(); + + return { + version: 1, + getState, + subscribe(fn) { + if (typeof fn === 'function') stateListeners.add(fn); + return () => stateListeners.delete(fn); + }, + discover, + setEnabled, + setActive, + dispose, + // The merged stream every later stage (calibration, scoring) reads. + onHit(fn) { + if (typeof fn === 'function') hitListeners.add(fn); + return () => hitListeners.delete(fn); + }, + // Internal: lets a view re-subscribe its bus handlers on each + // activation, for a Host that installs `window.feedBack` late. + addActivateListener(fn) { + if (typeof fn === 'function') activateListeners.add(fn); + return () => activateListeners.delete(fn); + }, + }; + } + + // ── screen view ──────────────────────────────────────────────────────── + + function plural(count, word) { + return `${count} ${word}${count === 1 ? '' : 's'}`; + } + + function statusText(state) { + if (!state.available) { + return 'MIDI input is unavailable here — this build has no midi-input capability domain.'; + } + if (!state.discovered) { + const outcome = state.outcome; + const reason = outcome && outcome.reason ? ` (${outcome.reason})` : ''; + if (outcome && outcome.outcome === 'denied') { + return `MIDI access was denied${reason}. Allow it in your browser, then rescan.`; + } + if (outcome) { + return `No MIDI provider could be reached${reason}. Rescan to try again.`; + } + return 'Looking for MIDI devices…'; + } + const connected = state.sources.length + ? `${plural(state.sources.length, 'device')} found` + : 'No devices connected'; + return `${connected} · ${state.openKeys.length} open.`; + } + + function savedHint(state) { + if (!state.savedKeys.length) return ''; + const present = new Set(state.sources.map((s) => s.logicalSourceKey)); + const missing = state.savedKeys.filter((key) => !present.has(key)).length; + const atCap = state.savedKeys.length >= MAX_SOURCES + ? ` Up to ${MAX_SOURCES} can be open at once.` + : ''; + if (!missing) { + return `${plural(state.savedKeys.length, 'device')} saved.${atCap}`; + } + return `${plural(missing, 'saved device')} not connected — ${missing === 1 ? 'it' : 'they'} will reopen automatically when ${missing === 1 ? 'it' : 'they'} return.${atCap}`; + } + + // Builds one row per present source. Rows are rebuilt only when the device + // list changes (scan, tick, replug) — never on the MIDI event path, which + // must stay free of DOM queries (spec §6.4). + function renderDevices(listEl, state, onToggle) { + listEl.textContent = ''; + if (!state.sources.length) return; + + for (const source of state.sources) { + const key = source.logicalSourceKey; + const ticked = state.savedKeys.indexOf(key) !== -1; + const row = document.createElement('li'); + row.className = 'midi-drums__device'; + + const label = document.createElement('label'); + const box = document.createElement('input'); + box.type = 'checkbox'; + box.checked = ticked; + box.className = 'midi-drums__device-box'; + box.addEventListener('change', () => { onToggle(key, box.checked); }); + const name = document.createElement('span'); + name.className = 'midi-drums__device-label'; + // textContent, not innerHTML: a device label is user-controlled + // hardware text and must never be parsed as markup. + name.textContent = source.label || 'MIDI input'; + label.appendChild(box); + label.appendChild(name); + row.appendChild(label); + + const meta = document.createElement('span'); + meta.className = 'midi-drums__device-meta'; + meta.textContent = state.openKeys.indexOf(key) !== -1 + ? (source.availability || 'available') + : `${source.availability || 'available'} · closed`; + row.appendChild(meta); + + listEl.appendChild(row); + } + } + + function bindView(layer) { + const root = document.getElementById(SCREEN_ID); + if (!root) { + console.warn(`${PLUGIN_ID}: screen root #${SCREEN_ID} not found`); + return null; + } + + // Resolve every node once, at bind time (spec §6.4). + const statusEl = root.querySelector('[data-role="status"]'); + const devicesEl = root.querySelector('[data-role="devices"]'); + const devicesEmptyEl = root.querySelector('[data-role="empty"]'); + const savedEl = root.querySelector('[data-role="saved"]'); + const rescanBtn = root.querySelector('[data-role="rescan"]'); + const hitsEl = root.querySelector('[data-role="hits"]'); + const hitsEmptyEl = root.querySelector('[data-role="hit-empty"]'); + const hitCountEl = root.querySelector('[data-role="hit-count"]'); + + // The hit log is a capped FIFO: one row per hit, newest first, oldest + // dropped. Rows are built on the hit path (a drum roll is a handful of + // events per second, not a per-frame render), but the element count + // never exceeds MAX_HIT_ROWS. + let hitTotal = 0; + + // logicalSourceKey → label, for the hit log. Rebuilt with the devices. + const labels = new Map(); + + const onState = (state) => { + labels.clear(); + for (const source of state.sources) labels.set(source.logicalSourceKey, source.label || 'MIDI input'); + if (statusEl) statusEl.textContent = statusText(state); + renderDevices(devicesEl, state, (key, enabled) => { + layer.setEnabled(key, enabled).catch(() => {}); + }); + if (devicesEmptyEl) devicesEmptyEl.hidden = !state.discovered || state.sources.length > 0; + // Nothing to rescan without the domain; the status line explains why. + if (rescanBtn) rescanBtn.disabled = !state.available; + if (savedEl) { + const hint = savedHint(state); + savedEl.textContent = hint; + savedEl.hidden = !hint; + } + }; + + const onHit = (hit) => { + if (!hitsEl) return; + const label = labels.get(hit.logicalSourceKey) || hit.logicalSourceKey; + const row = document.createElement('li'); + row.className = 'midi-drums__hit'; + // textContent, not innerHTML: the label is hardware-supplied text. + row.textContent = `${label} — note ${hit.note}, velocity ${hit.velocity}, channel ${hit.channel + 1}`; + hitsEl.prepend(row); + while (hitsEl.childElementCount > MAX_HIT_ROWS) hitsEl.lastElementChild.remove(); + hitTotal += 1; + if (hitCountEl) hitCountEl.textContent = String(hitTotal); + if (hitsEmptyEl) hitsEmptyEl.hidden = true; + }; + + // A rescan is also the retry for a denied prompt, so it re-runs + // discovery even after a successful one — and restore() follows, which + // picks up a saved device that has since been plugged back in. + const onRescan = () => { layer.discover({ force: true }).catch(() => {}); }; + + // `screen:changing` is best-effort, not a spec guarantee: it lets us release + // sessions before navigation completes rather than after. `pagehide` + // below is the guaranteed backstop. + const onScreenChanging = (ev) => { + const from = (ev && ev.detail && ev.detail.from) || (ev && ev.from) || null; + if (from === SCREEN_ID) layer.setActive(false); + }; + // `screen:changed` is the normative "I am on `id`" signal, so an explicit id + // always wins — the Host may emit it before or after it swaps the + // container's `active` class, and guessing from the class would fight + // it. The class is only the fallback for a Host that sends no id at all, + // so an unreadable payload fails towards the DOM instead of leaving the + // screen permanently inert. + const onScreenChanged = (ev) => { + const id = (ev && ev.detail && ev.detail.id) || (ev && ev.id) || null; + if (id === null) layer.setActive(root.classList.contains('active')); + else layer.setActive(id === SCREEN_ID); + }; + // A full page load is the other exit path. `pageshow` re-syncs so a + // tab restored from bfcache resumes instead of sitting inactive. + const onPageHide = () => layer.setActive(false); + const onPageShow = () => layer.setActive(root.classList.contains('active')); + + const unsubscribeState = layer.subscribe(onState); + const unsubscribeHit = layer.onHit(onHit); + if (rescanBtn) rescanBtn.addEventListener('click', onRescan); + + // Retryable for the same reason as the layer's own bus subscription: the + // screen lifecycle events are what wake this screen back up, so losing + // them would leave it permanently inert. `bindBus` is idempotent and is + // re-run on every activation. + let bus = null; + let busBound = false; + function bindBus() { + if (busBound) return; + const found = window.feedBack; + if (!found || typeof found.on !== 'function') return; + bus = found; + busBound = true; + bus.on('screen:changing', onScreenChanging); + bus.on('screen:changed', onScreenChanged); + } + bindBus(); + const unbindActivation = layer.addActivateListener(bindBus); + + window.addEventListener('pagehide', onPageHide); + window.addEventListener('pageshow', onPageShow); + + onState(layer.getState()); + + return { + dispose() { + unsubscribeState(); + unsubscribeHit(); + unbindActivation(); + if (rescanBtn) rescanBtn.removeEventListener('click', onRescan); + if (busBound && bus && typeof bus.off === 'function') { + bus.off('screen:changing', onScreenChanging); + bus.off('screen:changed', onScreenChanged); + } + window.removeEventListener('pagehide', onPageHide); + window.removeEventListener('pageshow', onPageShow); + layer.setActive(false); + }, + }; + } + + // ── boot ─────────────────────────────────────────────────────────────── + + // The layer is created once and reused; only the view binding is replaced, + // so re-hydration swaps one set of listeners for another instead of + // stacking a second copy (spec §6.1, `plugin-runtime-idempotent.v1`). + if (!window[GLOBAL_KEY] || window[GLOBAL_KEY].version !== 1) { + window[GLOBAL_KEY] = createDeviceLayer(); + } + const layer = window[GLOBAL_KEY]; + + const previous = window[VIEW_KEY]; + if (previous) previous.dispose(); + window[VIEW_KEY] = bindView(layer); + + // The Host toggles `active` on the screen container; adopt whatever state + // the screen is already in, since `screen:changed` only fires on a change. + const root = document.getElementById(SCREEN_ID); + if (root) layer.setActive(root.classList.contains('active')); +})(); \ No newline at end of file From 151fb8c979b3eb24142f537577cac5b68c53cec1 Mon Sep 17 00:00:00 2001 From: "pullfrog[bot]" <226033991+pullfrog[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:24:05 +0000 Subject: [PATCH 2/4] refactor: drop the redundant initial bus bind in the device layer setActive() already binds midi-input:sources-changed on the first boot call, and no session can exist without setActive(true), so the extra call at layer construction only repeated work. --- midi-drums/screen.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/midi-drums/screen.js b/midi-drums/screen.js index cb4b559..ff26c51 100644 --- a/midi-drums/screen.js +++ b/midi-drums/screen.js @@ -477,8 +477,6 @@ activateListeners.clear(); } - bindSourcesChanged(); - return { version: 1, getState, From bc99dda3f2d4743bb2442a4e44be9df694c329bc Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:24:51 +0000 Subject: [PATCH 3/4] fix(screen): skip duplicate restore on activation --- midi-drums/screen.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/midi-drums/screen.js b/midi-drums/screen.js index ff26c51..93b4e68 100644 --- a/midi-drums/screen.js +++ b/midi-drums/screen.js @@ -452,12 +452,14 @@ } async function activate() { + // A fresh discovery already restores, so restoring again here would + // only repeat that work. Once discovery is latched, though, + // discover() short-circuits and this is the only thing that re-opens + // devices: returning to the screen (or re-binding after a + // re-hydration) closed them on the way out. + const alreadyDiscovered = discovered; await discover(); - // discover() short-circuits once it has succeeded, so it cannot be - // the only thing that re-opens devices: returning to the screen (or - // re-binding after a re-hydration) has to restore them here too. - // restore() skips sources that are already open. - await restore(); + if (alreadyDiscovered) await restore(); } // Terminal teardown, used when screen.js is re-executed so the previous From 9ddf2fcace7662b7939f301f5e7f999cf3c6f679 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:25:05 +0000 Subject: [PATCH 4/4] fix(routes): drop redundant config dir mkdir --- midi-drums/routes.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/midi-drums/routes.py b/midi-drums/routes.py index 862d316..c71ca0d 100644 --- a/midi-drums/routes.py +++ b/midi-drums/routes.py @@ -184,7 +184,8 @@ def _merge_and_persist() -> dict: to stream the request body above.""" with write_lock: merged = {**_read(), **incoming} - config_dir.mkdir(parents=True, exist_ok=True) + # config_dir was created in setup() before any route was + # registered, so it is already there. # Written to a sibling then renamed: a torn or truncated write # would leave invalid JSON, and _read()'s corrupt-file recovery # would then reset the user's whole selection to empty.