From e488cc3ffd65bdf5257044d415d613df187ec0c7 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Wed, 7 Oct 2026 05:02:42 +0000 Subject: [PATCH 01/18] Implement kit-profile persistence, chart consumption, live scoring, note-state provider, and settings panel (issues #5-#9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Persistence (#5): per-profile kit_updated_at stamps, per_song_overrides, bounded validation/salvage, settings.server_files opt-in for Host-side export/import; GET/POST /kit-profiles exposes the new keys. - Chart consumption (#6): the plugin holds its own listener on the highway WS — core exposes drum_tab/drum_hits to renderer bundles only, with no bus event or getDrumTab() getter (checked). Multi-part picker via ?drum_part=; legacy no-tab packs degrade to 'no chart, scoring off'. - Live scoring (#7): ±50 ms matching window with EARLY/OK/LATE split at 40%, per-frame miss sweep with a connect-time floor re-armed on seek-back, streak/accuracy/extras readouts, bounded surfacing of unmapped strikes and missing chart pieces. Mirrors drum_highway_3d. - Note-state provider (#8): function provider (note, chartTime) => state registered on window.highway only while a device session is open, cleared with setNoteStateProvider(null) on exit/disposal. - Settings panel (#9): settings.html with profile CRUD, active-profile switching, coverage chips per lib/drums.py display conventions, and remap deep-links into the player's single-piece remap path via nav params. Fixes audit drift: piece vocabulary now matches lib/drums.py (18 ids, title-cased fallback for unknown ids); the broken object-wrapper setNoteStateProvider registration and the dead drum-tab/drum-hits/ drum-part bus listeners (events no host component emits) are gone, along with the dead onDrumTabChanged API and an unreachable view-scope registerWithHighway() call. --- CHANGELOG.md | 13 + midi-drums/README.md | 49 +- midi-drums/assets/plugin.css | 150 +++++- midi-drums/plugin.json | 4 + midi-drums/routes.py | 233 ++++++--- midi-drums/screen.html | 58 ++- midi-drums/screen.js | 894 ++++++++++++++++++++++++++++++----- midi-drums/settings.html | 361 ++++++++++++++ 8 files changed, 1568 insertions(+), 194 deletions(-) create mode 100644 midi-drums/settings.html diff --git a/CHANGELOG.md b/CHANGELOG.md index 41113e9..8cea526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,4 +13,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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. +- `midi-drums` kit-profile persistence (#5) — `kit_updated_at` stamps, `per_song_overrides`, bounded server validation, and `settings.server_files` in `plugin.json` for Host-side export/import. +- `midi-drums` drum-chart consumption (#6) — the plugin holds its own listener on the highway WS (core exposes the chart to renderer bundles only, with no bus event or `getDrumTab()` getter), a `?drum_part=` picker for multi-part packs, and "no chart — scoring off" degradation for legacy packs. +- `midi-drums` live scoring engine (#7) — ±50 ms hit matching with EARLY/OK/LATE split, per-frame miss sweep with a connect-time floor and seek-back re-arm, streak/accuracy/streak counters, and bounded surfacing of unmapped strikes/missing chart pieces (mirrors `drum_highway_3d`). +- `midi-drums` note-state provider integration (#8) — a function provider `(note, chartTime) => state` registered on `window.highway` only while a device session is open, cleared with `setNoteStateProvider(null)` on exit/disposal. +- `midi-drums` kit-profile settings panel (#9) — `settings.html` with profile CRUD, active-profile switching, per-profile coverage chips, last-updated stamps, and remap deep-links into the player screen's single-piece remap path. +- `midi-drums` active-kit picker and profile creation on the plugin screen; part picker, chart status, streak/extras and unmapped readouts on the screen. + +### Fixed +- `midi-drums` piece vocabulary drifted from the host's `lib/drums.py` (`tom1`/`floor_tom`/`rim`… were invented ids) — now the canonical 18-id set; unknown ids round-trip with a title-cased fallback. +- `midi-drums` registered an object wrapper with `highway.setNoteStateProvider` (the contract takes a function `(note, chartTime)` and was never invoked) and never cleared the slot — rewritten per feedBack#254, cleared on teardown. +- `midi-drums` calibrated against bus events `drum-tab`/`drum-hits`/`drum-part` that no host component emits; replaced with the plugin's own chart WS. +- `midi-drums` dead code removed: `onDrumTabChanged` runner, the unused note-state wrapper, and an unreachable view-scope `registerWithHighway()` call. + diff --git a/midi-drums/README.md b/midi-drums/README.md index 8380dfa..e6991ad 100644 --- a/midi-drums/README.md +++ b/midi-drums/README.md @@ -1,8 +1,10 @@ # 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. +Input + scoring plugin for MIDI drum controllers. Scans for input devices, +opens several at once, merges their note-ons into a single tagged stream, then +calibrates them into kit profiles, consumes the loaded song's drum chart, and +scores live hits against it — feeding the active highway renderer through +`highway.setNoteStateProvider`. 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 @@ -12,10 +14,11 @@ domain is absent or mid-version. | 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` | +| `plugin.json` | Manifest — capability declaration, `type: "input"`, nav entry, settings panel, server_files | +| `screen.html` | Device list, kit-profile picker, calibration wizard, chart status (+ part picker), scoring panel, bounded hit log | +| `screen.js` | Device layer + kit-profile CRUD + drum-chart consumption (own WS) + live scoring engine + note-state provider | +| `settings.html` | Kit-profile management panel (list/create/rename/delete/set-active, coverage chips, piece remap deep-links) | +| `routes.py` | Server persistence at `/api/plugins/midi-drums/settings` and `/api/plugins/midi-drums/kit-profiles` | | `assets/plugin.css` | Styling scoped to the plugin | ## How it talks to MIDI @@ -78,6 +81,38 @@ offHits(); stream across every open source; each hit carries the `logicalSourceKey` it came from, so a consumer never has to track connections itself. +## Kit profiles and scoring + +Beyond device identity, the layer stores `kit_profiles` (piece-id → +`{note, channel, logicalSourceKey}` per named profile), `kit_updated_at` +(per-profile last-modified stamps), and `per_song_overrides` (sparse song-key → +piece → mapping overlays), all validated and salvaged key-by-key server-side. + +- **Kit pieces come from `lib/drums.py`.** The 18-id canonical vocabulary is + mirrored in `screen.js`; ids a newer pack references beyond it round-trip + with a title-cased display fallback. +- **The wizard calibrates the active profile.** `Settings → Plugins → MIDI + Drums` owns full CRUD (create/rename/delete/set-active, coverage chips); + piece chips there deep-link into the player screen's single-piece remap + path via nav params. +- **The drum chart comes over the plugin's own WebSocket.** Core's highway + hands `drum_tab`/`drum_hits` only to renderer bundles — no bus event, no + public getter — so the plugin listens on the same `/ws/highway/` + endpoint itself (the server's extraction caches make the second connection + cheap). `?drum_part=` selects the streaming part; multi-part packs surface + a picker. Legacy packs that encode drums as guitar notes stream no + `drum_tab` and are treated as "no chart — scoring off" for this song. +- **Scoring mirrors `drum_highway_3d`.** ±50 ms matching window with an + EARLY/OK/LATE split at 40%, misses swept per animation frame with a + connect-time floor (and re-armed on seek-back), per-hit judgments keyed on + `t|piece`, streak/accuracy readouts, and bounded surfacing of strikes that + match no mapped piece. +- **Renderer feedback goes through `setNoteStateProvider`.** The layer + registers a function provider `(note, chartTime) => state` on + `window.highway` only while a device session is open (the contract is + last-call-wins, so squatters lose), returns decaying `alpha` glows, and + clears with `setNoteStateProvider(null)` on screen exit and disposal. + ## Device identity Sources are keyed by `logicalSourceKey` (`web-midi::`), never by a diff --git a/midi-drums/assets/plugin.css b/midi-drums/assets/plugin.css index fe8d3a6..bc5d171 100644 --- a/midi-drums/assets/plugin.css +++ b/midi-drums/assets/plugin.css @@ -237,4 +237,152 @@ display: flex; gap: 0.5rem; flex-wrap: wrap; -} \ No newline at end of file +} +/* Kit profile row (active-profile picker + inline create) */ +.midi-drums__profiles { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin-top: 0.75rem; +} + +.midi-drums__profiles-row { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; + align-items: center; +} + +.midi-drums__select, +.midi-drums__input { + padding: 0.35rem 0.5rem; + border: 1px solid rgba(128, 128, 128, 0.4); + border-radius: 6px; + background: transparent; + color: inherit; + font: inherit; +} + +/* Drum-part picker row */ +.midi-drums__part-row { + display: flex; + gap: 0.5rem; + align-items: center; + margin: 0.5rem 0; +} + +.midi-drums__part-row[hidden] { + display: none; +} + +/* Settings-panel kit profile management (scoped to .midi-drums-settings) */ +.midi-drums-settings fieldset { + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.midi-drums-settings__hint, +.midi-drums-settings__count, +.midi-drums-settings__status { + margin: 0; + font-size: 0.85rem; + opacity: 0.8; +} + +.midi-drums-settings__status { + color: #e0a040; +} + +.midi-drums-settings__create { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; +} + +.midi-drums-settings__input { + flex: 1 1 12rem; + padding: 0.35rem 0.5rem; + border: 1px solid rgba(128, 128, 128, 0.4); + border-radius: 6px; + background: transparent; + color: inherit; + font: inherit; +} + +.midi-drums-settings__button { + padding: 0.3rem 0.7rem; + border: 1px solid rgba(128, 128, 128, 0.4); + border-radius: 6px; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} + +.midi-drums-settings__button:hover { + border-color: currentColor; +} + +.midi-drums-settings__button--danger { + border-color: rgba(200, 70, 70, 0.6); + color: #d08080; +} + +.midi-drums-settings__list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.75rem; +} + +.midi-drums-settings__profile { + padding: 0.65rem; + border: 1px solid rgba(128, 128, 128, 0.3); + border-radius: 8px; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.midi-drums-settings__profile-head { + display: flex; + gap: 0.75rem; + align-items: baseline; + flex-wrap: wrap; +} + +.midi-drums-settings__updated { + font-size: 0.8rem; + opacity: 0.7; +} + +.midi-drums-settings__chips { + display: flex; + flex-wrap: wrap; + gap: 0.3rem; +} + +.midi-drums-settings__chip { + padding: 0.15rem 0.5rem; + font-size: 0.78rem; + border: 1px solid rgba(128, 128, 128, 0.35); + border-radius: 999px; + background: transparent; + color: inherit; + opacity: 0.55; + cursor: pointer; +} + +.midi-drums-settings__chip.is-mapped { + opacity: 1; + border-color: rgba(90, 180, 120, 0.8); +} + +.midi-drums-settings__actions { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; +} diff --git a/midi-drums/plugin.json b/midi-drums/plugin.json index 9009cdc..180aa48 100644 --- a/midi-drums/plugin.json +++ b/midi-drums/plugin.json @@ -10,6 +10,10 @@ "scriptType": "classic", "styles": "assets/plugin.css", "routes": "routes.py", + "settings": { + "html": "settings.html", + "server_files": ["midi-drums.json"] + }, "category": "practice", "standards": [ "capability-pipelines.v1", diff --git a/midi-drums/routes.py b/midi-drums/routes.py index 4fed3a6..0020c9a 100644 --- a/midi-drums/routes.py +++ b/midi-drums/routes.py @@ -7,8 +7,9 @@ can change with a driver update, while the domain's logicalSourceKey is stable per provider + source id. -Also persists kit profiles - mappings from drum piece IDs to MIDI trigger -mappings ({note, channel, logicalSourceKey}). +Also persists kit profiles (piece-id -> {note, channel, logicalSourceKey} +mappings), the active profile, per-profile last-modified stamps, and per-song +piece overrides. Follows the same shape as the template's routes.py: all work happens inside setup(), configuration is read tolerantly, routes are namespaced under the @@ -33,10 +34,29 @@ # 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 +# Kit-profile collection bounds. Piece-id values are deliberately NOT checked +# against a closed vocabulary: lib/drums.py lets unknown piece-ids round-trip +# for forward-compat, and a profile saved by a newer plugin build must keep +# loading here. Shape-level bounds only. +MAX_KIT_PROFILES = 64 +MAX_PROFILE_NAME_LEN = 100 +MAX_PIECE_ID_LEN = 50 +MAX_PIECES_PER_PROFILE = 64 +# Per-song overrides are a sparse overlay of the active kit profile, so they +# share the profile bounds plus a generous song-key bound. +MAX_SONG_OVERRIDE_KEYS = 256 +MAX_SONG_ID_LEN = 200 +# The profiles document is the biggest thing this plugin stores (64 profiles of +# up to 18-piece e-kits can plausibly reach ~200 KiB of JSON), so the profile +# routes take their own, larger body cap than the 16 KiB selection cap. +MAX_KIT_PROFILES_BODY_BYTES = 256 * 1024 + _DEFAULTS = { "source_keys": [], "active_kit": "default", "kit_profiles": {}, + "kit_updated_at": {}, + "per_song_overrides": {}, } @@ -55,37 +75,74 @@ def _is_valid_setting(name: str, value: object) -> bool: # this only rejects a hand-edited file, which _read() then salvages. return len(set(value)) == len(value) if name == "active_kit": - return isinstance(value, str) and 0 < len(value) < 100 + return isinstance(value, str) and 0 < len(value) < MAX_PROFILE_NAME_LEN if name == "kit_profiles": - if not isinstance(value, dict): + if not isinstance(value, dict) or len(value) > MAX_KIT_PROFILES: return False # Basic validation - each profile is a dict of piece->mapping for profile_name, profile in value.items(): - if not isinstance(profile_name, str) or len(profile_name) > 100: + if not isinstance(profile_name, str) or not profile_name or len(profile_name) > MAX_PROFILE_NAME_LEN: return False if not isinstance(profile, dict): return False + if len(profile) > MAX_PIECES_PER_PROFILE: + return False for piece_id, mapping in profile.items(): - if not isinstance(piece_id, str) or len(piece_id) > 50: + if not isinstance(piece_id, str) or not piece_id or len(piece_id) > MAX_PIECE_ID_LEN: return False - if not isinstance(mapping, dict): + if not _is_valid_trigger_mapping(mapping): return False - # Validate mapping structure - for key in mapping: - if key not in ("note", "channel", "logicalSourceKey"): - return False - if "note" not in mapping or type(mapping["note"]) is not int or mapping["note"] < 0 or mapping["note"] > 127: - return False - if "channel" not in mapping or type(mapping["channel"]) is not int or mapping["channel"] < 0 or mapping["channel"] > 15: - return False - if "logicalSourceKey" not in mapping: + return True + if name == "kit_updated_at": + if not isinstance(value, dict) or len(value) > MAX_KIT_PROFILES: + return False + # Stamps are display-only ISO strings, so a loose-but-typed check is + # enough: bounded key, bounded string. + return all( + type(stamp_key) is str + and 0 < len(stamp_key) < MAX_PROFILE_NAME_LEN + and type(stamp) is str + and 0 < len(stamp) <= 40 + for stamp_key, stamp in value.items() + ) + if name == "per_song_overrides": + if not isinstance(value, dict) or len(value) > MAX_SONG_OVERRIDE_KEYS: + return False + for song_id, pieces in value.items(): + if type(song_id) is not str or not song_id or len(song_id) > MAX_SONG_ID_LEN: + return False + if not isinstance(pieces, dict) or len(pieces) > MAX_PIECES_PER_PROFILE: + return False + for piece_id, mapping in pieces.items(): + if type(piece_id) is not str or not piece_id or len(piece_id) > MAX_PIECE_ID_LEN: return False - if type(mapping["logicalSourceKey"]) is not str: + if not _is_valid_trigger_mapping(mapping): return False return True return False +def _is_valid_trigger_mapping(mapping: object) -> bool: + """A piece trigger mapping is exactly {note, channel, logicalSourceKey}. + + Exact-keys matching (rather than "has the required keys") keeps a stray + leftover field from a hand-edit out of the stored shape, where it would be + silently carried forever. + """ + if not isinstance(mapping, dict) or len(mapping) != 3: + return False + for key in ("note", "channel", "logicalSourceKey"): + if key not in mapping: + return False + if type(mapping["note"]) is not int or not 0 <= mapping["note"] <= 127: + return False + if type(mapping["channel"]) is not int or not 0 <= mapping["channel"] <= 15: + return False + if type(mapping["logicalSourceKey"]) is not str or not mapping["logicalSourceKey"]: + return False + return True + + def _sanitise_source_keys(keys: object) -> list: """Coerce a persisted source_keys value into something openable. @@ -125,39 +182,85 @@ def setup(app: FastAPI, context: dict) -> None: # interleave their read and write and lose one of the two selections. write_lock = threading.Lock() + def _sanitise_trigger_mapping(mapping: object) -> dict | None: + """Return a clean {note, channel, logicalSourceKey} dict or None.""" + if not isinstance(mapping, dict): + return None + note = mapping.get("note") + channel = mapping.get("channel") + logical_source_key = mapping.get("logicalSourceKey") + if type(note) is not int or note < 0 or note > 127: + return None + if type(channel) is not int or channel < 0 or channel > 15: + return None + if type(logical_source_key) is not str or not logical_source_key: + return None + return { + "note": note, + "channel": channel, + "logicalSourceKey": logical_source_key, + } + + def _sanitise_piece_mappings(mappings: object) -> dict: + """Salvage a piece-id -> mapping dict key-by-key.""" + if not isinstance(mappings, dict): + return {} + clean = {} + for piece_id, mapping in mappings.items(): + if not isinstance(piece_id, str) or not piece_id or len(piece_id) > MAX_PIECE_ID_LEN: + continue + clean_mapping = _sanitise_trigger_mapping(mapping) + if clean_mapping is not None: + clean[piece_id] = clean_mapping + if len(clean) == MAX_PIECES_PER_PROFILE: + break + return clean + def _sanitise_kit_profiles(value: object) -> dict: """Coerce persisted kit profiles into something valid.""" if not isinstance(value, dict): return {} clean = {} for profile_name, profile in value.items(): - if not isinstance(profile_name, str) or len(profile_name) > 100: + if not isinstance(profile_name, str) or not profile_name or len(profile_name) > MAX_PROFILE_NAME_LEN: continue if not isinstance(profile, dict): continue - clean_profile = {} - for piece_id, mapping in profile.items(): - if not isinstance(piece_id, str) or len(piece_id) > 50: - continue - if not isinstance(mapping, dict): - continue - # Validate and extract mapping - note = mapping.get("note") - channel = mapping.get("channel") - logicalSourceKey = mapping.get("logicalSourceKey") - if type(note) is not int or note < 0 or note > 127: - continue - if type(channel) is not int or channel < 0 or channel > 15: - continue - if type(logicalSourceKey) is not str: - continue - clean_profile[piece_id] = { - "note": note, - "channel": channel, - "logicalSourceKey": logicalSourceKey, - } + clean_profile = _sanitise_piece_mappings(profile) if clean_profile: clean[profile_name] = clean_profile + if len(clean) == MAX_KIT_PROFILES: + break + return clean + + def _sanitise_stamps(value: object) -> dict: + """Coerce persisted kit_updated_at stamps into something displayable.""" + if not isinstance(value, dict): + return {} + clean = {} + for profile_name, stamp in value.items(): + if type(profile_name) is not str or not profile_name or len(profile_name) >= MAX_PROFILE_NAME_LEN: + continue + if type(stamp) is not str or not stamp or len(stamp) > 40: + continue + clean[profile_name] = stamp + if len(clean) == MAX_KIT_PROFILES: + break + return clean + + def _sanitise_song_overrides(value: object) -> dict: + """Coerce persisted per-song piece overrides into something valid.""" + if not isinstance(value, dict): + return {} + clean = {} + for song_id, pieces in value.items(): + if type(song_id) is not str or not song_id or len(song_id) > MAX_SONG_ID_LEN: + continue + clean_pieces = _sanitise_piece_mappings(pieces) + if clean_pieces: + clean[song_id] = clean_pieces + if len(clean) == MAX_SONG_OVERRIDE_KEYS: + break return clean def _read() -> dict: @@ -182,11 +285,20 @@ def _read() -> dict: settings[key] = _sanitise_source_keys(value) elif key == "kit_profiles": settings[key] = _sanitise_kit_profiles(value) + elif key == "kit_updated_at": + settings[key] = _sanitise_stamps(value) + elif key == "per_song_overrides": + settings[key] = _sanitise_song_overrides(value) elif key == "active_kit": if isinstance(value, str) and value: - settings[key] = value[:100] + settings[key] = value[:MAX_PROFILE_NAME_LEN - 1] else: settings[key] = "default" + # An active profile that was lost to salvage (or a hand edit) falls + # back to the default profile rather than pointing at nothing. + if settings["active_kit"] not in settings["kit_profiles"]: + has_any = bool(settings["kit_profiles"]) + settings["active_kit"] = next(iter(settings["kit_profiles"]), "default") if has_any else "default" return settings # Fail fast on an unusable config_dir, before any route is registered — a @@ -201,7 +313,7 @@ def _read() -> dict: @app.get(f"/api/plugins/{PLUGIN_ID}/settings") def get_settings() -> JSONResponse: - """Get the saved device selection and kit profiles.""" + """Get the saved device selection, kit profiles, and overrides.""" return JSONResponse(_read()) @app.post(f"/api/plugins/{PLUGIN_ID}/settings") @@ -209,7 +321,7 @@ async def set_settings(request: Request) -> JSONResponse: """Replace the saved settings. Accepts a bounded JSON object holding `source_keys`, `active_kit`, - and/or `kit_profiles`. + `kit_profiles`, `kit_updated_at`, and/or `per_song_overrides`. """ content_length = request.headers.get("content-length") if content_length is not None: @@ -283,26 +395,34 @@ def _merge_and_persist() -> dict: return JSONResponse(merged) - # Kit profile-specific endpoints for easier manipulation + # Kit profile-specific endpoints for easier manipulation. These carry the + # larger document (64 profiles' worth of mappings), so they take their own + # body cap instead of MAX_SETTINGS_BODY_BYTES. @app.get(f"/api/plugins/{PLUGIN_ID}/kit-profiles") def get_kit_profiles() -> JSONResponse: - """Get all kit profiles.""" + """Get all kit profiles with their stamps and per-song overrides.""" settings = _read() return JSONResponse({ "active_kit": settings["active_kit"], "kit_profiles": settings["kit_profiles"], + "kit_updated_at": settings["kit_updated_at"], + "per_song_overrides": settings["per_song_overrides"], }) @app.post(f"/api/plugins/{PLUGIN_ID}/kit-profiles") async def set_kit_profiles(request: Request) -> JSONResponse: - """Update kit profiles.""" + """Update kit profiles, the active profile, stamps, and/or overrides.""" 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 or content_length_value > MAX_SETTINGS_BODY_BYTES: + if content_length_value < 0: + return JSONResponse( + {"error": "invalid Content-Length header"}, status_code=400 + ) + if content_length_value > MAX_KIT_PROFILES_BODY_BYTES: return JSONResponse( - {"error": "invalid content length"}, status_code=400 + {"error": "request body too large"}, status_code=413 ) except ValueError: return JSONResponse( @@ -312,7 +432,7 @@ async def set_kit_profiles(request: Request) -> JSONResponse: body = bytearray() try: async for chunk in request.stream(): - if len(body) + len(chunk) > MAX_SETTINGS_BODY_BYTES: + if len(body) + len(chunk) > MAX_KIT_PROFILES_BODY_BYTES: return JSONResponse( {"error": "request body too large"}, status_code=413 ) @@ -325,24 +445,18 @@ async def set_kit_profiles(request: Request) -> JSONResponse: return JSONResponse( {"error": "body must be a JSON object"}, status_code=400 ) - - # Validate specific fields - if "active_kit" in incoming and not (isinstance(incoming["active_kit"], str) and incoming["active_kit"]): + if incoming.keys() - {"active_kit", "kit_profiles", "kit_updated_at", "per_song_overrides"}: return JSONResponse( - {"error": "body contains invalid setting values"}, status_code=400 + {"error": "body contains unknown settings"}, status_code=400 ) - if "kit_profiles" in incoming and not _is_valid_setting("kit_profiles", incoming["kit_profiles"]): + 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: with write_lock: - merged = {**_read()} - if "active_kit" in incoming: - merged["active_kit"] = incoming["active_kit"][:100] - if "kit_profiles" in incoming: - merged["kit_profiles"] = incoming["kit_profiles"] + merged = {**_read(), **incoming} 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) @@ -350,6 +464,7 @@ def _merge_and_persist() -> dict: try: merged = await asyncio.to_thread(_merge_and_persist) + log.info("%s: kit profiles updated", PLUGIN_ID) return JSONResponse(merged) except Exception as exc: log.error("%s: failed to write settings: %s", PLUGIN_ID, exc) @@ -357,4 +472,4 @@ def _merge_and_persist() -> dict: {"error": "failed to save settings"}, status_code=500 ) - log.info("%s: routes registered", PLUGIN_ID) \ No newline at end of file + log.info("%s: routes registered", PLUGIN_ID) diff --git a/midi-drums/screen.html b/midi-drums/screen.html index ef99049..55131e7 100644 --- a/midi-drums/screen.html +++ b/midi-drums/screen.html @@ -6,9 +6,11 @@ class `screen`) before running screen.js. screen.js finds these nodes by `data-role` inside that root; nothing here is queried globally. - Device access only: this screen owns the midi-input conversation - (discover / list / open / close) and reports what the domain hands back. - Kit calibration, chart reading and scoring land on top of this later. + Covers the whole stack: the midi-input conversation (discover / list / + open / close), kit-profile selection + calibration wizard (remap included), + drum-chart status with the multi-part picker, and the live scoring panel. + Kit-profile create/rename/delete also live in the plugin's Settings panel; + this screen only picks the active profile and creates one. -->
@@ -56,6 +58,32 @@

Kit calibration

Waiting for a loaded song/drum chart to determine which pieces to calibrate.

+
+ +
+ + + +
+

+ Rename, delete and per-piece remapping live in + Settings → Plugins → MIDI Drums. The wizard + always calibrates the active profile. +

+
+