Johan Le Baut 1 Minggu lalu
induk
melakukan
36b4fe8a07
3 mengubah file dengan 144 tambahan dan 19 penghapusan
  1. 8 7
      README.md
  2. 45 10
      scripts/midi_action_bridge.py
  3. 91 2
      scripts/run_mod_ui_service.py

+ 8 - 7
README.md

@@ -37,12 +37,13 @@ This records the preparation already performed on `rigforge` and is a starting p
 - `scripts/validate_desired_state.py`: validates topology and routing invariants without changing the target.
 - `scripts/observe_pipewire.py`: read-only comparison by default, with explicit one-shot repair for declared missing links.
 - `scripts/midi_action_bridge.py`: translates declared ALSA MIDI note events into NAM model changes through mod-ui's WebSocket.
+- `scripts/run_mod_ui_service.py`: keeps mod-ui's backend session alive and repairs only its two missing guitar audio-boundary cables after pedalboard loads.
 - `scripts/generate_mod_ui_pedalboard.py`: generates the reference NAM→IR pedalboard from the YAML.
 - `scripts/deploy.sh` and `scripts/deploy.py`: scoped user-level installation, removal, reload, and explicit mod-ui reset of declared services and LV2 bundles.
-- `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, and deployment operations.
+- `tests/`: unit tests for desired-state validation, PipeWire observation/reconciliation, pedalboard generation, MIDI WebSocket control, mod-ui audio-boundary repair, and deployment operations.
 - `artifacts/sooperlooper/arm64/`, `artifacts/mod-host/arm64/`, and `artifacts/mod-ui/arm64/`: generated binaries or runtime bundle, dependency reports, and build provenance; commit after reviewing licensing and repository size.
 
-The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. The new mod-host PipeWire boundary nodes and services are local candidates and remain unverified on the target.
+The YAML describes desired state; a control surface is not a second source of truth. The initial audio profile declares 48 kHz and a quantum of 128 frames, which was reported to sound good during a temporary target test. At 48 kHz, 128 frames is about 2.7 ms per period, not the end-to-end latency. This runtime value has not yet been made persistent or measured under sustained load; apply it temporarily on the target with `pw-metadata -n settings 0 clock.force-quantum 128` and return to automatic selection with `pw-metadata -n settings 0 clock.force-quantum 0`. The mod-host boundaries and services are active on the target; the owner has now confirmed an audible NAM→IR path and MIDI model switching. Sustained stability, levels, and recovery after a restart still need verification.
 
 Validate the desired-state file on the development PC with:
 
@@ -145,11 +146,11 @@ Remove the service with `./scripts/deploy.sh uninstall sooperlooper`.
 
 ### mod-host ports and mod-ui guitar board
 
-`install mod-host-ports`, `install mod-host`, and `install mod-ui` are explicit targets and are deliberately excluded from `install all`. `mod-host-ports` starts two mono `/usr/bin/pw-loopback` boundaries: a PipeWire sink `rigforge.mod-host-input` with a paired source visible to mod-ui, and a sink visible to mod-ui paired with the source `rigforge.mod-host-output`. Rigforge's observer manages UMC capture → input sink and output source → guitar mixer/looper. mod-ui is configured to display one “Rigforge Mod-Host Input” and one “Rigforge Mod-Host Output” and owns the internal cables from input to NAM, NAM to IR, and IR to output.
+`install mod-host-ports`, `install mod-host`, and `install mod-ui` are explicit targets and are deliberately excluded from `install all`. `mod-host-ports` starts two mono `/usr/bin/pw-loopback` boundaries: a PipeWire sink `rigforge.mod-host-input` with a paired source visible to mod-ui, and a sink visible to mod-ui paired with the source `rigforge.mod-host-output`. Rigforge's observer manages UMC capture → input sink and output source → guitar mixer/looper. mod-ui is configured to display one “Rigforge Mod-Host Input” and one “Rigforge Mod-Host Output” and owns the internal cables from input to NAM, NAM to IR, and IR to output. After each board load, `run_mod_ui_service.py` checks the two boundary-to-plugin links and uses `pw-link` only to add either exact missing edge; it never removes or changes other links. This supplements mod-ui's board graph because the visible boundary cables were not connected in PipeWire during target testing.
 
 `scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM, one LSP mono IR, the Crunch TB and Vox AC30 assets, the declared NAM output level, and those three mod-ui-owned arcs. During `install mod-ui`, deployment copies the declared NAM models into Rigforge's dedicated `MOD_USER_FILES_DIR/NAM Models/Rigforge` directory and generates a target-specific bundle whose model path points there; the model copies are fingerprinted and removed only if unchanged when mod-ui is uninstalled. The reference bundle is also target-specific, fingerprinted, and protected from local edits. mod-ui then resumes its last saved board across restarts. `./scripts/deploy.sh reset mod-ui` explicitly restores the generated reference and backs up any prior default board and last-state file as adjacent `.rigforge-reset-backup` paths.
 
-The mod-host unit runs `pw-jack mod-host -n -p 5555 -f 5556`; it no longer runs `configure_mod_host.py`. The mod-ui service starts under `pw-jack`, opens a persistent local WebSocket session so the board loads even before a browser connects, and is the sole control/feedback client for mod-host. Install the ARM64 artifacts, NAM/LSP bundles, and the declared audio assets before activation. The target ports, virtual loopback naming, pedalboard loading, and sustained audio still require an on-target test; the YAML marks newly introduced boundary links as `planned`.
+The mod-host unit runs `pw-jack mod-host -n -p 5555 -f 5556`; it no longer runs `configure_mod_host.py`. The mod-ui service starts under `pw-jack`, opens a persistent local WebSocket session so the board loads even before a browser connects, and is the sole control/feedback client for mod-host. After each completed board load, this runner verifies that the guitar capture reaches the NAM input and the IR output reaches the output boundary, restoring only a missing exact connection. Install the ARM64 artifacts, NAM/LSP bundles, and the declared audio assets before activation. Sustained audio and recovery after a service restart still require on-target verification; the external boundary links remain observable by the graph observer.
 
 Both mod-host TCP ports currently listen on all interfaces without authentication, retained by owner request. The mod-ui HTTP/WebSocket server is also reachable on the LAN for the browser UI. Restrict these endpoints before treating the setup as hardened. Keep the repository checkout at its installed path, since the user units refer to it.
 
@@ -157,7 +158,7 @@ Both mod-host TCP ports currently listen on all interfaces without authenticatio
 
 `config/midi-bindings.yaml` maps MIDI Note On events on channel 1 (channel index 0) to actions, rather than storing plugin paths or commands in the controller configuration. Notes 6–9 select the declared guitar NAM models: Crystal Clean TB, Edge of Breakup TB, Crunch TB, and Overdriven TB. Note Off and Note On with velocity zero are ignored. Each selection declares Crystal Clean TB as its missing-file fallback. If both the requested model and fallback are unavailable, the bridge reports the error and leaves the currently loaded model unchanged.
 
-The NAM model catalog and MIDI input/mod-ui WebSocket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs; the bridge resolves the current NAM instance and sends a file-property `patch_set` through mod-ui, without opening mod-host's TCP socket. The pedalboard remains a single NAM→IR board; changing models does not load another board. SooperLooper’s `config/sooperlooper/fcb1010.slb` remains independent and unchanged.
+The NAM model catalog and MIDI input/mod-ui WebSocket settings are declared in `config/desired-state.yaml`. Actions identify their target by chain and processor IDs; the bridge resolves the current NAM instance and sends a file-property `patch_set` through mod-ui, without opening mod-host's TCP socket. It sends the staged copy from mod-ui's `user-files/NAM Models/Rigforge` directory, not the source file in the checkout, so mod-ui can match the path to its selector entry and reflect MIDI changes. The pedalboard remains a single NAM→IR board; changing models does not load another board. SooperLooper’s `config/sooperlooper/fcb1010.slb` remains independent and unchanged.
 
 The bridge uses Debian’s `python3-rtmidi` package, included in the recorded target-preparation command above. Check the configuration and inspect MIDI input names with:
 
@@ -251,8 +252,8 @@ The remaining target checks are:
 1. The read-only observer and one-shot repair have been tested on `rigforge`. Repairing one missing link restored the audible microphone path; after a later filter-chain service restart, reconciliation requested all three missing links and the observer reported no differences. The current local model tracks the external `mod-host-input`/`mod-host-output` boundary links; it deliberately does not track the NAM→IR cable. Do not run one-shot reconciliation against an older checkout: it could restore the dry guitar bypass.
 2. Test direct mixer inputs 2 and 4 with sources when available; their direct-to-mix routes remain unverified. Looper capture inputs 2–4 are now linked but have not been tested with instruments.
 3. Measure sustained stability and headroom at 48 kHz / 128 frames with all active sources; the current `ERR = 0` observation was brief.
-4. Test the new PipeWire loopback boundary ports and verify that mod-ui displays and connects them; then verify mod-host feedback pairing, the generated board's initial NAM/IR state, UI edits across restart, explicit reset, and recovery after unplug/replug.
-5. The owner manually verified FCB notes 6–9 through the old direct mod-host bridge. On 2026-11-23, the upstream Raspberry Pi 5 NAM LV2 binary crashed with SIGSEGV in `NeuralAudio::NAMIsA2` while parsing the declared A2 `SlimmableContainer` model (version 0.7.0), both from the mod-ui picker and the new WebSocket bridge. The NAM file copies matched and memory was available. Rebuilding the same v0.2.3 sources on Debian 13 with GCC 14 and a dynamic system `libstdc++` avoided the crash: bridge-level selections for notes 6, 7, 9, and 8 and a mod-ui selection from the path containing `NAM Models` all completed with zero mod-host restarts. The original shared object is preserved in `~/.lv2/neural_amp_modeler.lv2.rigforge-backup`. This verifies model-load requests and host process survival, not physical FCB delivery, audible model quality, or sustained audio stability. SooperLooper's supplied FCB1010 bindings were also tested successfully over the declared PipeWire MIDI edge. Verify that the updated observer restores this edge after reboot, service restart, and UMC unplug/replug; verify unattended startup, OSC initialization, audio routing, and the persistence/effect of `discrete_prefader 0` separately.
+4. Verify automatic restoration of the two mod-ui audio-boundary links after the runner update is activated by a future mod-ui restart; then verify UI edits across restart, explicit reset, and recovery after unplug/replug.
+5. The owner manually verified FCB notes 6–9 through the old direct mod-host bridge. On 2026-11-23, the upstream Raspberry Pi 5 NAM LV2 binary crashed with SIGSEGV in `NeuralAudio::NAMIsA2` while parsing the declared A2 `SlimmableContainer` model (version 0.7.0), both from the mod-ui picker and the new WebSocket bridge. Rebuilding the same v0.2.3 sources on Debian 13 with GCC 14 and a dynamic system `libstdc++` avoided the crash. A follow-up exposed that the MIDI bridge sent checkout paths rather than mod-ui's staged user-file paths: mod-host accepted the change, but the selector stayed at “choose a NAM model.” The bridge now sends the verified staged copy. On 2026-11-23, note 9 was retested and the open mod-ui page displayed `Vox_AC15CH_Overdriven_TB.nam`; mod-host and mod-ui had zero restarts. The original shared object is preserved in `~/.lv2/neural_amp_modeler.lv2.rigforge-backup`. During the guitar-audio test, capture AUX0 had RMS 0.081, while NAM output was exactly zero; the actual PipeWire links from boundary capture → NAM input and IR output → boundary playback were missing even though the mod-ui cables were visible. Adding those two exact links produced NAM-output RMS 0.0255 and mixer-output RMS 0.0102, and the owner confirmed the speaker was audible. The automatic repair is tracked in `scripts/run_mod_ui_service.py` and has been copied to the target checkout, but the running service has not been restarted; it will take effect at the next mod-ui start/load. The currently active target links were added manually. This verifies an audible path and model/UI switching, not sustained stability or headroom. SooperLooper's supplied FCB1010 bindings were also tested successfully over the declared PipeWire MIDI edge. Unattended startup, OSC initialization, and the persistence/effect of `discrete_prefader 0` remain unverified.
 
 Do not treat planned packages, commands, ports, or service settings as target-validated until these checks have been performed.
 

+ 45 - 10
scripts/midi_action_bridge.py

@@ -2,6 +2,7 @@
 """Translate configured MIDI events into NAM model changes via mod-ui."""
 
 import argparse
+import hashlib
 import sys
 import time
 from pathlib import Path, PurePosixPath
@@ -156,6 +157,31 @@ def resolve_asset(repo_root, relative_path):
     return resolved
 
 
+def resolve_mod_ui_model(state, repo_root, source_path, user_files_root=None):
+    """Resolve a repository NAM model to the matching mod-ui user-files copy."""
+    source_path = Path(source_path).resolve()
+    deployment = state.get("deployment", {}).get("mod_ui", {})
+    user_files_directory = deployment.get("user_files_directory")
+    if not safe_relative_path(user_files_directory):
+        raise ValueError("deployment.mod_ui.user_files_directory must be a safe relative path")
+
+    if user_files_root is None:
+        user_files_root = Path.home() / Path(*PurePosixPath(user_files_directory).parts)
+    user_files_root = Path(user_files_root).resolve()
+    ui_model = (user_files_root / "NAM Models" / "Rigforge" / source_path.name).resolve()
+    if not ui_model.is_relative_to(user_files_root):
+        raise ValueError(f"mod-ui NAM model escapes its user-files directory: {ui_model}")
+    if not ui_model.is_file():
+        raise FileNotFoundError(
+            f"mod-ui NAM model copy is missing: {ui_model}; reinstall mod-ui to stage it"
+        )
+    source_digest = hashlib.sha256(source_path.read_bytes()).digest()
+    ui_digest = hashlib.sha256(ui_model.read_bytes()).digest()
+    if source_digest != ui_digest:
+        raise RuntimeError(f"mod-ui NAM model copy differs from its repository source: {ui_model}")
+    return ui_model
+
+
 def mod_ui_command(config, instance, property_uri, value):
     with ModUiWebSocketClient(
         config["host"],
@@ -165,28 +191,31 @@ def mod_ui_command(config, instance, property_uri, value):
         return client.set_patch(instance, property_uri, value)
 
 
-def select_nam_model(action, state, repo_root, command=None):
+def select_nam_model(action, state, repo_root, command=None, user_files_root=None):
     processor = resolve_processor(state, action["target"])
     models = processor["available_models"]
     requested_id = action["model"]
     fallback_id = action["fallback_model"]
 
-    requested_path = resolve_asset(repo_root, models[requested_id])
+    requested_source = resolve_asset(repo_root, models[requested_id])
     selected_id = requested_id
-    selected_path = requested_path
-    if not requested_path.is_file():
+    selected_source = requested_source
+    if not requested_source.is_file():
         selected_id = fallback_id
-        selected_path = resolve_asset(repo_root, models[fallback_id])
-        if not selected_path.is_file():
+        selected_source = resolve_asset(repo_root, models[fallback_id])
+        if not selected_source.is_file():
             raise FileNotFoundError(
                 f"requested NAM model and fallback are both missing: "
-                f"{requested_path}, {selected_path}"
+                f"{requested_source}, {selected_source}"
             )
         print(
             f"WARNING: NAM model {requested_id!r} is missing; "
-            f"using fallback {fallback_id!r} ({selected_path})",
+            f"using fallback {fallback_id!r} ({selected_source})",
             file=sys.stderr,
         )
+    selected_path = resolve_mod_ui_model(
+        state, repo_root, selected_source, user_files_root=user_files_root
+    )
 
     ui_config = bridge_config(state)["mod_ui"]
     instance = processor["mod_ui_instance"]
@@ -207,7 +236,9 @@ def binding_index(bindings):
     }
 
 
-def handle_midi_message(message, bindings, state, repo_root, command=None):
+def handle_midi_message(
+    message, bindings, state, repo_root, command=None, user_files_root=None
+):
     if not message or len(message) < 3:
         return None
     status, note, velocity = message[:3]
@@ -219,7 +250,11 @@ def handle_midi_message(message, bindings, state, repo_root, command=None):
     if binding is None:
         return None
     model_id, model_path = select_nam_model(
-        binding["action"], state, repo_root, command=command
+        binding["action"],
+        state,
+        repo_root,
+        command=command,
+        user_files_root=user_files_root,
     )
     return {
         "binding": binding["id"],

+ 91 - 2
scripts/run_mod_ui_service.py

@@ -8,10 +8,81 @@ import sys
 import time
 from pathlib import Path
 
+import yaml
+
 from mod_ui_websocket import ModUiWebSocketClient
+from observe_pipewire import list_ports, parse_pw_link_output
+
+
+def mod_ui_audio_boundary_links(state):
+    chain = state["routing"]["mod_host_chains"]["guitar"]
+    processors = chain["processors"]
+    if not processors:
+        raise ValueError("the mod-ui guitar chain has no processors")
+    return (
+        (chain["source_port"], processors[0]["input_port"]),
+        (processors[-1]["output_port"], chain["mod_ui_output_port"]),
+    )
+
+
+def ensure_mod_ui_audio_links(state, runner=subprocess.run):
+    """Restore only the two board-to-boundary audio cables owned by mod-ui."""
+    result = runner(
+        ["pw-link", "-l"],
+        check=True,
+        capture_output=True,
+        text=True,
+    )
+    links = parse_pw_link_output(result.stdout)
+    expected = mod_ui_audio_boundary_links(state)
+    missing = [edge for edge in expected if edge not in links]
+    if not missing:
+        return 0
+
+    outputs = list_ports(runner, "-o")
+    inputs = list_ports(runner, "-i")
+    for source, destination in missing:
+        if source not in outputs:
+            raise RuntimeError(f"mod-ui audio source port is unavailable: {source}")
+        if destination not in inputs:
+            raise RuntimeError(f"mod-ui audio destination port is unavailable: {destination}")
+        runner(
+            ["pw-link", source, destination],
+            check=True,
+            capture_output=True,
+            text=True,
+        )
+        print(f"Restored mod-ui audio cable: {source} -> {destination}")
+
+    result = runner(
+        ["pw-link", "-l"],
+        check=True,
+        capture_output=True,
+        text=True,
+    )
+    remaining = [
+        edge for edge in expected
+        if edge not in parse_pw_link_output(result.stdout)
+    ]
+    if remaining:
+        source, destination = remaining[0]
+        raise RuntimeError(
+            f"mod-ui audio cable is still missing after repair: {source} -> {destination}"
+        )
+    return len(missing)
 
 
-def run_service(launcher, pw_jack, host, port, websocket_path, timeout, popen=subprocess.Popen):
+def run_service(
+    launcher,
+    pw_jack,
+    host,
+    port,
+    websocket_path,
+    timeout,
+    state,
+    popen=subprocess.Popen,
+    pw_link_runner=subprocess.run,
+):
     process = popen([str(pw_jack), str(launcher)])
     stopping = [False]
 
@@ -22,6 +93,8 @@ def run_service(launcher, pw_jack, host, port, websocket_path, timeout, popen=su
     old_int = signal.signal(signal.SIGINT, request_stop)
     client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
     deadline = time.monotonic() + timeout
+    repair_audio_links = False
+    next_audio_link_repair = 0.0
     try:
         while not stopping[0]:
             if process.poll() is not None:
@@ -43,6 +116,7 @@ def run_service(launcher, pw_jack, host, port, websocket_path, timeout, popen=su
                     raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
                 message = client.serve_once(timeout=0.5)
                 if message and message.startswith("loading_end "):
+                    repair_audio_links = True
                     break
                 if time.monotonic() >= deadline:
                     raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
@@ -50,7 +124,19 @@ def run_service(launcher, pw_jack, host, port, websocket_path, timeout, popen=su
         while not stopping[0]:
             if process.poll() is not None:
                 raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
-            client.serve_once(timeout=0.5)
+            message = client.serve_once(timeout=0.5)
+            if message and message.startswith("loading_end "):
+                repair_audio_links = True
+                next_audio_link_repair = 0.0
+            if repair_audio_links and time.monotonic() >= next_audio_link_repair:
+                try:
+                    repaired = ensure_mod_ui_audio_links(state, runner=pw_link_runner)
+                    if repaired == 0:
+                        print("mod-ui audio boundary cables are already connected")
+                    repair_audio_links = False
+                except (OSError, subprocess.CalledProcessError, RuntimeError, ValueError) as error:
+                    print(f"ERROR: could not ensure mod-ui audio boundary cables: {error}", file=sys.stderr)
+                    next_audio_link_repair = time.monotonic() + 2.0
     finally:
         signal.signal(signal.SIGTERM, old_term)
         signal.signal(signal.SIGINT, old_int)
@@ -81,6 +167,8 @@ def main(argv=None):
         print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
         return 1
     try:
+        with (root / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
+            state = yaml.safe_load(stream)
         run_service(
             args.launcher,
             args.pw_jack,
@@ -88,6 +176,7 @@ def main(argv=None):
             args.port,
             args.websocket_path,
             args.timeout,
+            state,
         )
     except (OSError, RuntimeError, ValueError) as error:
         print(f"ERROR: {error}", file=sys.stderr)