Explorar el Código

try fix pedlaboard not connecting pipewire

Johan Le Baut hace 5 días
padre
commit
39394e03ea

+ 4 - 2
README.md

@@ -165,11 +165,13 @@ Remove SLWeb before SooperLooper with `./scripts/deploy.sh uninstall slweb`. The
 
 `scripts/generate_mod_ui_pedalboard.py` builds the reference bundle from the YAML: one NAM defaulting to Vox AC15 Crystal Clean TB, one LSP mono IR using the Vox AC30 asset, the guitar NAM→IR chain, a microphone channel-3 chain (LSP high-pass, compressor and de-esser, then Dragonfly Room reverb with the dry signal retained), plus direct-through bass and synth arcs. The voice-chain settings are conservative starting points only and require listening and level adjustment on target. 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 resumes its last saved board across service restarts within the same boot. `./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.
 
-On each system boot, `rigforge-mod-ui.service` runs `scripts/prepare_mod_ui_pedalboard.py` before launching mod-ui. It regenerates and validates the content-addressed reference bundle from the checkout, replaces the mutable `default.pedalboard` with that clean board, and moves any previous default and last-state file into `mod-ui/boot-backups`, outside the pedalboard scan directory. It also migrates older Rigforge backups out of that scan directory. A marker under the user runtime directory makes this happen only once per boot; a mod-ui service restart during the same boot preserves in-session changes. The Rigforge service uses a dedicated `last-rigforge.json` state file so upstream `last.json` state cannot redirect startup to an unrelated board. If generation or validation fails, mod-ui does not start with a blank board. The service waits for mod-ui to report that it loaded the prepared default board, then verifies the guitar PipeWire boundary links before reporting readiness. This behavior is covered by repository tests but has not yet been deployed or verified on the target.
+Rigforge's mod-ui bridge maps NAM and IR graph ports explicitly to their mod-host LV2 ports and retries boundary restoration only after the declared PipeWire ports are visible. If the UI board is open but boundary links are absent, inspect the active plugin connections in mod-ui and run `python3 scripts/diagnose_mod_ui.py`; the diagnostic falls back to mod-ui's active pedalboard API if the saved last-state path is empty. Do not create the internal effect links manually with `pw-link`; mod-ui is their owner.
+
+On each system boot, `rigforge-mod-ui.service` runs `scripts/prepare_mod_ui_pedalboard.py` before launching mod-ui. It regenerates and validates the content-addressed reference bundle from the checkout, replaces the mutable `default.pedalboard` with that clean board, and moves any previous default and last-state file into `mod-ui/boot-backups`, outside the pedalboard scan directory. It also migrates older Rigforge backups out of that scan directory. A marker under the user runtime directory makes this happen only once per boot; a mod-ui service restart during the same boot preserves in-session changes. The Rigforge service uses a dedicated `last-rigforge.json` state file so upstream `last.json` state cannot redirect startup to an unrelated board. If generation or validation fails, mod-ui does not start with a blank board. The service runner launches mod-ui and holds its WebSocket session so mod-host remains connected; it does not treat the WebSocket's loading messages or PipeWire cable checks as service readiness. Use `python3 scripts/diagnose_mod_ui.py` for a separate read-only check of selected bundle metadata and voice-chain links. This diagnostic uses HTTP and `pw-link`, not a second WebSocket session, and its failure does not restart mod-ui. This startup behavior is covered by repository tests but has not yet been deployed or fully verified on the target.
 
 If `install mod-ui` refuses a changed but registry-managed reference bundle, first inspect why it differs. To explicitly replace only that bundle while preserving its current contents, use `./scripts/deploy.sh install mod-ui --force-reference`; the old bundle is retained in an adjacent `.rigforge-force-backup` path. This flag does not override local edits to the systemd unit, model files, or other managed 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. Its boundary bridge maps four visible input/output pairs to PipeWire and applies only explicit UI Connect/Disconnect operations. Install the ARM64 artifacts, NAM/LSP bundles, and declared audio assets before activation. Sustained audio and recovery after a service restart still require on-target verification; external UMC/boundary/mixer/looper links remain observable by the graph observer.
+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 mod-host remains active even before a browser connects, and is the sole control/feedback client for mod-host. Its boundary bridge maps four visible input/output pairs to PipeWire and applies only explicit UI Connect/Disconnect operations. The runner supervises the processes and keeps the session alive; it does not validate pedalboard loading or cables and does not restart the UI because a link is absent. Use `python3 scripts/diagnose_mod_ui.py` for a separate non-WebSocket diagnostic and run the PipeWire observer for external links. Install the ARM64 artifacts, NAM/LSP bundles, and declared audio assets before activation. Sustained audio and recovery after a service restart still require on-target verification; external UMC/boundary/mixer/looper 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.
 

+ 1 - 1
artifacts/mod-ui/arm64/current/app/mod/host.py

@@ -22,7 +22,7 @@ from random import randint
 from tornado import gen, iostream
 from tornado.ioloop import IOLoop, PeriodicCallback
 from urllib.parse import quote, unquote
-import os, json, socket, time, logging, sys
+import os, json, socket, time, logging, sys, subprocess
 import shutil, tempfile
 
 # only used for HMI screenshots, optional

+ 14 - 4
artifacts/mod-ui/arm64/current/app/mod/rigforge_pipewire.py

@@ -12,7 +12,8 @@ def boundary_connection(
     resolve_host_port,
 ):
     """Translate mod-ui graph boundary cables to concrete PipeWire ports."""
-    capture_symbol = port_from.rsplit("/", 1)[-1]
+    source_path = port_from.removeprefix("/graph/")
+    capture_symbol = source_path.rsplit("/", 1)[-1]
     capture_port = capture_ports.get(capture_symbol)
     if capture_port:
         host_port = resolve_host_port(port_to)
@@ -20,7 +21,8 @@ def boundary_connection(
             return capture_port, host_port
         return None
 
-    playback_symbol = port_to.rsplit("/", 1)[-1]
+    destination_path = port_to.removeprefix("/graph/")
+    playback_symbol = destination_path.rsplit("/", 1)[-1]
     playback_port = playback_ports.get(playback_symbol)
     if playback_port:
         host_port = resolve_host_port(port_from)
@@ -35,9 +37,13 @@ def resolve_pedalboard_port(port, resolve_host_port):
     """Resolve Ingen-style graph ports and LV2 effect_N aliases for pw-link."""
     graph_path = port.removeprefix("/graph/")
     if "/" not in graph_path:
+        if graph_path.startswith("capture_") or graph_path.startswith("playback_"):
+            return resolve_host_port("/graph/" + graph_path)
         return resolve_host_port(port)
     instance, symbol = graph_path.split("/", 1)
     effect_index = {
+        "rigforge_nam": 0,
+        "rigforge_ir": 1,
         "rigforge_voice_high_pass": 2,
         "rigforge_voice_compressor": 3,
         "rigforge_voice_de_esser": 4,
@@ -46,6 +52,8 @@ def resolve_pedalboard_port(port, resolve_host_port):
     if effect_index is None:
         return resolve_host_port(port)
     effect_ports = {
+        "rigforge_nam": {"input": "input", "output": "output"},
+        "rigforge_ir": {"in": "in", "out": "out"},
         "rigforge_voice_high_pass": {"in": "in", "out": "out"},
         "rigforge_voice_compressor": {"in": "in", "out": "out"},
         "rigforge_voice_de_esser": {"in": "in", "out": "out"},
@@ -70,9 +78,11 @@ def pedalboard_connection(
     destination_path = port_to.removeprefix("/graph/")
     captures = dict(capture_ports)
     playbacks = dict(playback_ports)
-    if "/" in source_path:
+    source_is_capture = source_path in captures
+    destination_is_playback = destination_path in playbacks
+    if "/" in source_path and not source_is_capture:
         captures = {}
-    if "/" in destination_path:
+    if "/" in destination_path and not destination_is_playback:
         playbacks = {}
     pipewire_link = boundary_connection(
         port_from,

+ 2 - 2
artifacts/mod-ui/arm64/current/provenance.json

@@ -9,8 +9,8 @@
   "additional_python_requirement": "backports.ssl_match_hostname==3.7.0.1",
   "python_compatibility_patch": "Tornado 4.3 collections.MutableMapping to collections.abc.MutableMapping",
   "rigforge_integration_patch": "build/arm64/patch_mod_ui_rigforge.py",
-  "rigforge_integration_patch_sha256": "9dcb5c0e3e66697ee0d3aef0ff817008a86f3aaba3b0cdcc724e213f668746cc",
+  "rigforge_integration_patch_sha256": "5d434ddc8ea24c932ae8a207e8c981137651dfaf664e65cf8aa18bde3b9bfc2a",
   "rigforge_pipewire_helper": "build/arm64/mod_ui_pipewire.py",
-  "rigforge_pipewire_helper_sha256": "326d79b8fbfaf740cd4eb99d24d6daceaffcac019f40a768913c58a74db16719",
+  "rigforge_pipewire_helper_sha256": "e7fbb717d8299d2f8a4e247afd4068f48fe90fa64021d7409df934892c2811eb",
   "license": "AGPL-3.0-or-later"
 }

+ 14 - 4
build/arm64/mod_ui_pipewire.py

@@ -12,7 +12,8 @@ def boundary_connection(
     resolve_host_port,
 ):
     """Translate mod-ui graph boundary cables to concrete PipeWire ports."""
-    capture_symbol = port_from.rsplit("/", 1)[-1]
+    source_path = port_from.removeprefix("/graph/")
+    capture_symbol = source_path.rsplit("/", 1)[-1]
     capture_port = capture_ports.get(capture_symbol)
     if capture_port:
         host_port = resolve_host_port(port_to)
@@ -20,7 +21,8 @@ def boundary_connection(
             return capture_port, host_port
         return None
 
-    playback_symbol = port_to.rsplit("/", 1)[-1]
+    destination_path = port_to.removeprefix("/graph/")
+    playback_symbol = destination_path.rsplit("/", 1)[-1]
     playback_port = playback_ports.get(playback_symbol)
     if playback_port:
         host_port = resolve_host_port(port_from)
@@ -35,9 +37,13 @@ def resolve_pedalboard_port(port, resolve_host_port):
     """Resolve Ingen-style graph ports and LV2 effect_N aliases for pw-link."""
     graph_path = port.removeprefix("/graph/")
     if "/" not in graph_path:
+        if graph_path.startswith("capture_") or graph_path.startswith("playback_"):
+            return resolve_host_port("/graph/" + graph_path)
         return resolve_host_port(port)
     instance, symbol = graph_path.split("/", 1)
     effect_index = {
+        "rigforge_nam": 0,
+        "rigforge_ir": 1,
         "rigforge_voice_high_pass": 2,
         "rigforge_voice_compressor": 3,
         "rigforge_voice_de_esser": 4,
@@ -46,6 +52,8 @@ def resolve_pedalboard_port(port, resolve_host_port):
     if effect_index is None:
         return resolve_host_port(port)
     effect_ports = {
+        "rigforge_nam": {"input": "input", "output": "output"},
+        "rigforge_ir": {"in": "in", "out": "out"},
         "rigforge_voice_high_pass": {"in": "in", "out": "out"},
         "rigforge_voice_compressor": {"in": "in", "out": "out"},
         "rigforge_voice_de_esser": {"in": "in", "out": "out"},
@@ -70,9 +78,11 @@ def pedalboard_connection(
     destination_path = port_to.removeprefix("/graph/")
     captures = dict(capture_ports)
     playbacks = dict(playback_ports)
-    if "/" in source_path:
+    source_is_capture = source_path in captures
+    destination_is_playback = destination_path in playbacks
+    if "/" in source_path and not source_is_capture:
         captures = {}
-    if "/" in destination_path:
+    if "/" in destination_path and not destination_is_playback:
         playbacks = {}
     pipewire_link = boundary_connection(
         port_from,

+ 72 - 30
build/arm64/patch_mod_ui_rigforge.py

@@ -172,6 +172,47 @@ def patch_host_connection_methods(host):
 def patch_load_connections(host):
     """Make pedalboard restore use the same resolution as manual UI actions."""
     text = host.read_text(encoding="utf-8")
+    original_text = text
+    resolver_marker = "    def _fix_host_connection_port(self, port):"
+    resolver_start = text.find(resolver_marker)
+    if resolver_start < 0:
+        raise RuntimeError(f"could not locate Host._fix_host_connection_port in {host}")
+    resolver_end = text.find(
+        "\n    def ", resolver_start + len(resolver_marker)
+    )
+    if resolver_end < 0:
+        raise RuntimeError(f"could not locate end of Host._fix_host_connection_port in {host}")
+    resolver_method = text[resolver_start:resolver_end]
+    if (
+        "# Rigforge bare boundary port alias; web_connect removes /graph/."
+        not in resolver_method
+    ):
+        marker = '        data = port.split("/")\n'
+        if resolver_method.count(marker) != 1:
+            raise RuntimeError(f"could not identify port resolver body in {host}")
+        updated_resolver = resolver_method.replace(
+            marker,
+            '''        # Rigforge bare boundary port alias; web_connect removes /graph/.
+        if port in self.rigforge_capture_ports:
+            return self.rigforge_capture_ports[port]
+        if port in self.rigforge_playback_ports:
+            return self.rigforge_playback_ports[port]
+        data = port.split("/")
+        if len(data) == 2 and data[0] == "" and (
+            data[1] in self.rigforge_capture_ports
+            or data[1] in self.rigforge_playback_ports
+        ):
+            symbol = data[1]
+            return self.rigforge_capture_ports.get(
+                symbol, self.rigforge_playback_ports.get(symbol)
+            )
+''',
+            1,
+        )
+        if updated_resolver == resolver_method:
+            raise RuntimeError(f"could not add Rigforge alias to {host}")
+        text = text[:resolver_start] + updated_resolver + text[resolver_end:]
+
     method_marker = "    def load_pb_connections("
     method_start = text.find(method_marker)
     if method_start < 0:
@@ -222,7 +263,29 @@ def patch_load_connections(host):
         if self.connections is not connection_list:
             return
 
-        if connect_link(*pipewire_link):
+        if not (
+            self.rigforge_capture_ports
+            and self.rigforge_playback_ports
+            and len(self.audioportsIn) == len(self.rigforge_capture_ports)
+            and len(self.audioportsOut) == len(self.rigforge_playback_ports)
+        ):
+            ready = False
+        else:
+            result = subprocess.run(
+                ["pw-link", "-o"],
+                check=False,
+                capture_output=True,
+                text=True,
+            )
+            ready = result.returncode == 0 and all(
+                port in result.stdout.splitlines()
+                for port in (
+                    *self.rigforge_capture_ports.values(),
+                    *self.rigforge_playback_ports.values(),
+                )
+            )
+
+        if ready and connect_link(*pipewire_link):
             edge = (port_from, port_to)
             if edge not in connection_list:
                 connection_list.append(edge)
@@ -251,7 +314,7 @@ def patch_load_connections(host):
             raise RuntimeError(f"could not insert PipeWire restore method in {host}")
         updated = updated[:position] + restore_method + updated[position:]
 
-    if updated != text:
+    if updated != original_text:
         host.write_text(updated, encoding="utf-8")
 
 
@@ -265,6 +328,11 @@ def apply(source_root):
         "from mod.rigforge_pipewire import boundary_connection, connect_link, disconnect_link, pedalboard_connection\n"
         "from mod import (\n",
     )
+    replace_if_present(
+        app / "mod" / "host.py",
+        "import os, json, socket, time, logging, sys\n",
+        "import os, json, socket, time, logging, sys, subprocess\n",
+    )
 
     replace_if_present(
         app / "mod" / "host.py",
@@ -374,38 +442,12 @@ def apply(source_root):
     )
     replace_if_present(
         app / "mod" / "host.py",
-        '''        if len(data) == 3:
-            # Handle special cases
-            if data[2] == "serial_midi_in":
-''' + "        \n",
-        '''        if len(data) == 3:
-            # Handle special cases
-            if data[2] in self.rigforge_capture_ports:
-                return self.rigforge_capture_ports[data[2]]
-            if data[2] in self.rigforge_playback_ports:
-                return self.rigforge_playback_ports[data[2]]
-            if data[2] == "serial_midi_in":
-''',
-    )
-    replace_if_present(
-        app / "mod" / "host.py",
-        '''        if len(data) == 3:
-            # Handle special cases
-            if data[2] == "serial_midi_in":
-''',
-        '''        if len(data) == 3:
-            # Handle special cases
-            if data[2] in self.rigforge_capture_ports:
-                return self.rigforge_capture_ports[data[2]]
-            if data[2] in self.rigforge_playback_ports:
-                return self.rigforge_playback_ports[data[2]]
-            if data[2] == "serial_midi_in":
-''',
+        "import os, json, socket, time, logging, sys\n",
+        "import os, json, socket, time, logging, sys, subprocess\n",
     )
     host_file = app / "mod" / "host.py"
     patch_load_connections(host_file)
     patch_host_connection_methods(host_file)
-
     replace_if_present(
         app / "mod" / "session.py",
         '''    # Set a plugin block position within the canvas

+ 4 - 4
config/systemd/user/rigforge-mod-ui.service.in

@@ -12,11 +12,11 @@ Environment=MOD_LAST_STATE_JSON=@MOD_LAST_STATE@
 Environment=MOD_USER_PEDALBOARDS_DIR=@PEDALBOARDS_DIR@
 Environment=MOD_USER_FILES_DIR=@USER_FILES_DIR@
 Environment=MOD_DEFAULT_PEDALBOARD=@REFERENCE_PEDALBOARD@
-Environment=MOD_DEVICE_WEBSERVER_PORT=@WEBSOCKET_PORT@
-Environment=MOD_RIGFORGE_CAPTURE_PORTS=@HARDWARE_INPUT_PORTS@
-Environment=MOD_RIGFORGE_PLAYBACK_PORTS=@HARDWARE_OUTPUT_PORTS@
+Environment=MOD_RIGFORGE_CAPTURE_PORTS=@RIGFORGE_CAPTURE_PORTS@
+Environment=MOD_RIGFORGE_PLAYBACK_PORTS=@RIGFORGE_PLAYBACK_PORTS@
+Environment=MOD_DEVICE_WEBSERVER_PORT=8888
 ExecStartPre=@PYTHON@ @BOOT_PREPARE_SCRIPT@ --state @DESIRED_STATE@ --runtime-dir %t/rigforge-mod-ui
-ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@ --host @WEBSOCKET_HOST@ --port @WEBSOCKET_PORT@ --state @DESIRED_STATE@
+ExecStart=@PYTHON@ -u @RUNNER_SCRIPT@ --launcher @MOD_UI_LAUNCHER@ --pw-jack @PW_JACK@
 Restart=on-failure
 RestartSec=5
 TimeoutStopSec=10

+ 16 - 5
scripts/deploy.py

@@ -1034,8 +1034,8 @@ def render_mod_host_service(config):
         "@FEEDBACK_PORT@": str(config["feedback_port"]),
         "@PYTHON@": systemd_quote(config["python_path"]),
         "@READINESS_SCRIPT@": systemd_quote(readiness_script.resolve()),
-        "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]),
         "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
+        "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]),
     }
     content = service_template.read_text(encoding="utf-8")
     for placeholder, replacement in replacements.items():
@@ -1108,9 +1108,11 @@ def render_mod_ui_service(config):
         / config["reference_directory"]
         / f"rigforge-guitar-{bundle_digest.hexdigest()[:16]}.pedalboard"
     )
+    diagnostic_script = ROOT / "scripts" / "diagnose_mod_ui.py"
     for description, path in (
         ("mod-ui launcher", launcher),
         ("mod-ui service runner", runner_script),
+        ("mod-ui diagnostic", diagnostic_script),
         ("mod-ui boot preparation script", boot_prepare_script),
         ("mod-ui service template", service_template),
     ):
@@ -1125,15 +1127,17 @@ def render_mod_ui_service(config):
         "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
         "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()),
         "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
-        "@WEBSOCKET_HOST@": config["websocket_host"],
-        "@WEBSOCKET_PORT@": str(config["websocket_port"]),
         "@MOD_DATA_DIR@": systemd_quote(home / ".local" / "share" / "rigforge" / "mod-ui"),
         "@MOD_LAST_STATE@": systemd_quote(home / config["last_state_file"]),
         "@PEDALBOARDS_DIR@": systemd_quote(home / config["pedalboards_directory"]),
         "@USER_FILES_DIR@": systemd_quote(home / config["user_files_directory"]),
         "@REFERENCE_PEDALBOARD@": systemd_quote(reference_pedalboard),
-        "@HARDWARE_INPUT_PORTS@": systemd_quote(",".join(config["hardware_input_ports"])),
-        "@HARDWARE_OUTPUT_PORTS@": systemd_quote(",".join(config["hardware_output_ports"])),
+        "@RIGFORGE_CAPTURE_PORTS@": systemd_quote(
+            ",".join(config["hardware_input_ports"])
+        ),
+        "@RIGFORGE_PLAYBACK_PORTS@": systemd_quote(
+            ",".join(config["hardware_output_ports"])
+        ),
     }
     content = service_template.read_text(encoding="utf-8")
     for placeholder, replacement in replacements.items():
@@ -1146,7 +1150,14 @@ def render_mod_ui_service(config):
     runtime_digest.update(runner_script.read_bytes())
     runtime_digest.update(boot_prepare_script.read_bytes())
     runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "run_mod_ui_service.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "diagnose_mod_ui.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "observe_pipewire.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "validate_desired_state.py").read_bytes())
     runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.py").read_bytes())
+    runtime_digest.update((ROOT / "scripts" / "diagnose_mod_ui.py").read_bytes())
+    runtime_digest.update((ROOT / "build" / "arm64" / "mod_ui_pipewire.py").read_bytes())
+    runtime_digest.update((ROOT / "build" / "arm64" / "patch_mod_ui_rigforge.py").read_bytes())
     for name, content_bytes in sorted(reference_files.items()):
         runtime_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0")
     content += f"\n# Rigforge runtime fingerprint: {runtime_digest.hexdigest()}\n"

+ 205 - 0
scripts/diagnose_mod_ui.py

@@ -0,0 +1,205 @@
+#!/usr/bin/env python3
+"""Read-only diagnostics for the running mod-ui pedalboard and its PipeWire links."""
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+from urllib.parse import urlencode
+from urllib.request import urlopen
+
+import yaml
+
+from observe_pipewire import parse_pw_link_output
+
+
+def load_mod_ui_board_links(state_path):
+    state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
+    processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
+    links = []
+    for previous, current in zip(processors, processors[1:]):
+        links.append(
+            (
+                f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/"
+                f"{previous['output_port'].split(':', 1)[1]}",
+                f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/"
+                f"{current['input_port'].split(':', 1)[1]}",
+            )
+        )
+    links.append(
+        (
+            f"/graph/{processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
+            f"{processors[-1]['output_port'].split(':', 1)[1]}",
+            "/graph/playback_3",
+        )
+    )
+    return tuple(links)
+
+
+def _resolve_host_alias(port):
+    graph_path = port.removeprefix("/graph/")
+    if "/" not in graph_path:
+        if graph_path.startswith("capture_"):
+            channel = int(graph_path.removeprefix("capture_"))
+            if 1 <= channel <= 4:
+                return (
+                    "rigforge.mod-host-input.capture:"
+                    f"capture_AUX{channel - 1}"
+                )
+            return port
+        if graph_path.startswith("playback_"):
+            channel = int(graph_path.removeprefix("playback_"))
+            if 1 <= channel <= 4:
+                return (
+                    "rigforge.mod-host-output.playback:"
+                    f"playback_AUX{channel - 1}"
+                )
+            return port
+        return port
+    instance, symbol = graph_path.split("/", 1)
+    instance_indices = {
+        "rigforge_nam": 0,
+        "rigforge_ir": 1,
+        "rigforge_voice_high_pass": 2,
+        "rigforge_voice_compressor": 3,
+        "rigforge_voice_de_esser": 4,
+        "rigforge_voice_reverb": 5,
+    }
+    effect_ports = {
+        "rigforge_nam": {"input": "input", "output": "output"},
+        "rigforge_ir": {"in": "in", "out": "out"},
+        "rigforge_voice_high_pass": {"in": "in", "out": "out"},
+        "rigforge_voice_compressor": {"in": "in", "out": "out"},
+        "rigforge_voice_de_esser": {"in": "in", "out": "out"},
+        "rigforge_voice_reverb": {
+            "input_l": "lv2_audio_in_1",
+            "output_l": "lv2_audio_out_1",
+        },
+    }
+    resolved_symbol = effect_ports.get(instance, {}).get(symbol)
+    if instance in instance_indices and resolved_symbol:
+        port_aliases = {
+            ("rigforge_nam", "input"): "input",
+            ("rigforge_nam", "output"): "output",
+            ("rigforge_ir", "in"): "in",
+            ("rigforge_ir", "out"): "out",
+        }
+        alias = port_aliases.get((instance, symbol), resolved_symbol)
+        return f"effect_{instance_indices[instance]}:{alias}"
+    return port
+
+
+def fetch_pedalboard_info(host, port, bundlepath, timeout=5):
+    query = urlencode({"bundlepath": str(bundlepath)})
+    with urlopen(f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout) as response:
+        return json.loads(response.read().decode("utf-8"))
+
+
+def fetch_active_pedalboard_info(host, port, timeout=5):
+    query = urlencode({"bundlepath": ""})
+    with urlopen(
+        f"http://{host}:{port}/pedalboard/info/?{query}", timeout=timeout
+    ) as response:
+        return json.loads(response.read().decode("utf-8"))
+
+
+def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5):
+    state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
+    mod_ui = state["deployment"]["mod_ui"]
+    data_root = Path.home() / mod_ui["last_state_file"]
+    try:
+        last_state = json.loads(data_root.read_text(encoding="utf-8"))
+    except (OSError, ValueError) as error:
+        return 1, [f"Cannot read mod-ui last-state file {data_root}: {error}"]
+
+    board_path = last_state.get("pedalboard")
+    if not board_path:
+        try:
+            info = fetch_active_pedalboard_info(host, port, timeout=timeout)
+        except Exception as error:
+            return 1, [
+                f"No selected pedalboard in {data_root}",
+                f"Cannot read active pedalboard metadata from mod-ui API: {error}",
+            ]
+        if not info.get("plugins"):
+            return 1, [f"No selected pedalboard in {data_root}; mod-ui API reports no active plugins"]
+        board_path = info.get("bundlepath") or "(active board reported by mod-ui API)"
+        messages = [
+            f"Active pedalboard reported by mod-ui API: {board_path}",
+            f"Bundle metadata: {info.get('title')!r}, "
+            f"{len(info.get('plugins', []))} plugins, "
+            f"{len(info.get('connections', []))} connections",
+        ]
+    else:
+        try:
+            info = fetch_pedalboard_info(host, port, board_path, timeout=timeout)
+        except Exception as error:
+            return 1, [f"Cannot read pedalboard metadata from mod-ui API: {error}"]
+
+        messages = [
+            f"Host-selected bundle: {board_path}",
+            f"Bundle metadata: {info.get('title')!r}, "
+            f"{len(info.get('plugins', []))} plugins, "
+            f"{len(info.get('connections', []))} connections",
+        ]
+    failures = []
+    if not info.get("plugins"):
+        failures.append("The selected bundle contains no plugins according to the mod-ui API")
+
+
+    expected_links = load_mod_ui_board_links(state_path)
+    pipewire = runner(
+        ["pw-link", "-l"],
+        check=False,
+        capture_output=True,
+        text=True,
+    )
+    if pipewire.returncode != 0:
+        failures.append(f"pw-link -l exited with status {pipewire.returncode}")
+    else:
+        observed = parse_pw_link_output(pipewire.stdout)
+        missing = [
+            (source, target)
+            for source, target in expected_links
+            if (
+                _resolve_host_alias(source),
+                _resolve_host_alias(target),
+            )
+            not in observed
+        ]
+        if missing:
+            failures.append(
+                "Missing declared pedalboard PipeWire links: "
+                + ", ".join(f"{src} -> {dst}" for src, dst in missing)
+            )
+        else:
+            messages.append(f"All {len(expected_links)} declared voice-chain links are present")
+
+    return (1 if failures else 0), messages + [
+        f"ERROR: {failure}" for failure in failures
+    ]
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument(
+        "--state",
+        type=Path,
+        default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
+    )
+    parser.add_argument("--host", default="127.0.0.1")
+    parser.add_argument("--port", type=int, default=8888)
+    args = parser.parse_args(argv)
+    try:
+        status, messages = inspect_runtime(args.state, args.host, args.port)
+    except (OSError, KeyError, TypeError, ValueError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    for message in messages:
+        print(message)
+    return status
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 9 - 4
scripts/mod_ui_websocket.py

@@ -144,16 +144,21 @@ class ModUiWebSocketClient:
     def serve_once(self, timeout=1):
         if self.connection is None:
             self.connect()
-        self.connection.settimeout(timeout)
+        connection = self.connection
+        connection.settimeout(timeout)
         try:
             opcode, payload = self.receive_frame()
         except socket.timeout:
             return
         finally:
-            if self.connection is not None:
-                self.connection.settimeout(self.timeout)
+            if self.connection is connection:
+                connection.settimeout(self.timeout)
         if opcode == 0x8:
-            raise RuntimeError("mod-ui closed the session WebSocket")
+            connection, self.connection = self.connection, None
+            self.buffer.clear()
+            if connection is not None:
+                connection.close()
+            raise ConnectionError("mod-ui closed the session WebSocket")
         if opcode == 0x9:
             self._send_frame(0xA, payload)
             return None

+ 53 - 238
scripts/run_mod_ui_service.py

@@ -2,191 +2,15 @@
 """Run mod-ui under pw-jack and keep its mod-host session active."""
 
 import argparse
-import os
+import http.client
 import signal
 import subprocess
 import sys
 import time
 from pathlib import Path
-
-import yaml
+from urllib.request import urlopen
 
 from mod_ui_websocket import ModUiWebSocketClient
-from observe_pipewire import parse_pw_link_output
-
-
-PIPEWIRE_BOUNDARY_TIMEOUT = 35
-
-
-def load_mod_ui_board_links(state_path):
-    state = yaml.safe_load(Path(state_path).read_text(encoding="utf-8"))
-    processors = state["routing"]["mod_host_chains"]["voice"]["processors"]
-    links = []
-    for index in range(1, len(processors)):
-        previous = processors[index - 1]
-        current = processors[index]
-        links.append(
-            (
-                f"/graph/{previous['mod_ui_instance'].removeprefix('/graph/')}/"
-                f"{previous['output_port'].split(':', 1)[1]}",
-                f"/graph/{current['mod_ui_instance'].removeprefix('/graph/')}/"
-                f"{current['input_port'].split(':', 1)[1]}",
-            )
-        )
-    links.append(
-        (
-            f"/graph/{processors[-1]['mod_ui_instance'].removeprefix('/graph/')}/"
-            f"{processors[-1]['output_port'].split(':', 1)[1]}",
-            "/graph/playback_3",
-        )
-    )
-    return tuple(links)
-
-
-def _resolve_host_alias(port):
-    graph_path = port.removeprefix("/graph/")
-    if "/" not in graph_path:
-        if graph_path.startswith("playback_"):
-            channel = int(graph_path.removeprefix("playback_"))
-            if 1 <= channel <= 4:
-                return (
-                    "rigforge.mod-host-output.playback:"
-                    f"playback_AUX{channel - 1}"
-                )
-            return port
-        if graph_path.startswith("capture_"):
-            channel = int(graph_path.removeprefix("capture_"))
-            if 1 <= channel <= 4:
-                return f"rigforge.mod-host-input.capture:capture_AUX{channel - 1}"
-            return port
-        return port
-    instance, symbol = graph_path.split("/", 1)
-    instance_indices = {
-        "rigforge_voice_high_pass": 2,
-        "rigforge_voice_compressor": 3,
-        "rigforge_voice_de_esser": 4,
-        "rigforge_voice_reverb": 5,
-    }
-    if instance in instance_indices:
-        effect_ports = {
-            "rigforge_voice_high_pass": {"in": "in", "out": "out"},
-            "rigforge_voice_compressor": {"in": "in", "out": "out"},
-            "rigforge_voice_de_esser": {"in": "in", "out": "out"},
-            "rigforge_voice_reverb": {
-                "input_l": "lv2_audio_in_1",
-                "output_l": "lv2_audio_out_1",
-            },
-        }
-        resolved_symbol = effect_ports.get(instance, {}).get(symbol)
-        return (
-            f"effect_{instance_indices[instance]}:{resolved_symbol}"
-            if resolved_symbol
-            else port
-        )
-    return port
-
-
-def guitar_boundary_links(capture_ports, playback_ports):
-    captures = [port.strip() for port in capture_ports if port.strip()]
-    playbacks = [port.strip() for port in playback_ports if port.strip()]
-    if not captures or not playbacks:
-        raise RuntimeError("Rigforge guitar PipeWire boundary ports are not configured")
-    return (
-        (captures[0], "effect_0:input"),
-        ("effect_1:out", playbacks[0]),
-    )
-
-
-def wait_for_guitar_boundary_links(
-    capture_ports,
-    playback_ports,
-    runner=subprocess.run,
-    timeout=10,
-    interval=0.2,
-    clock=time.monotonic,
-    sleep=time.sleep,
-):
-    expected = guitar_boundary_links(capture_ports, playback_ports)
-    deadline = clock() + timeout
-    missing = list(expected)
-    last_error = None
-    while True:
-        try:
-            result = runner(
-                ["pw-link", "-l"],
-                check=False,
-                capture_output=True,
-                text=True,
-            )
-            if result.returncode == 0:
-                observed = parse_pw_link_output(result.stdout)
-                missing = [edge for edge in expected if edge not in observed]
-                if not missing:
-                    return
-                last_error = None
-            else:
-                last_error = f"pw-link exited with status {result.returncode}"
-        except (OSError, ValueError) as error:
-            last_error = str(error)
-
-        remaining = deadline - clock()
-        if remaining <= 0:
-            details = ", ".join(f"{source} -> {destination}" for source, destination in missing)
-            message = f"mod-ui did not restore guitar PipeWire boundary links: {details}"
-            if last_error:
-                message += f" ({last_error})"
-            raise RuntimeError(message)
-        sleep(min(interval, remaining))
-
-
-def wait_for_graph_links(
-    expected,
-    resolve_host_port=lambda port: port,
-    runner=subprocess.run,
-    timeout=10,
-    interval=0.2,
-    clock=time.monotonic,
-    sleep=time.sleep,
-):
-    expected = tuple(
-        (
-            resolve_host_port(source),
-            resolve_host_port(destination),
-        )
-        for source, destination in expected
-    )
-    deadline = clock() + timeout
-    missing = list(expected)
-    last_error = None
-    while True:
-        try:
-            result = runner(
-                ["pw-link", "-l"],
-                check=False,
-                capture_output=True,
-                text=True,
-            )
-            if result.returncode == 0:
-                observed = parse_pw_link_output(result.stdout)
-                missing = [edge for edge in expected if edge not in observed]
-                if not missing:
-                    return
-                last_error = None
-            else:
-                last_error = f"pw-link exited with status {result.returncode}"
-        except (OSError, ValueError) as error:
-            last_error = str(error)
-
-        remaining = deadline - clock()
-        if remaining <= 0:
-            details = ", ".join(
-                f"{source} -> {destination}" for source, destination in missing
-            )
-            message = f"mod-ui did not restore declared pedalboard links: {details}"
-            if last_error:
-                message += f" ({last_error})"
-            raise RuntimeError(message)
-        sleep(min(interval, remaining))
 
 
 def run_service(
@@ -197,11 +21,14 @@ def run_service(
     websocket_path,
     timeout,
     popen=subprocess.Popen,
-    capture_ports=(),
-    playback_ports=(),
-    pw_link_runner=subprocess.run,
-    state_path=None,
+    healthcheck=None,
 ):
+    """Launch mod-ui and retain the WebSocket session needed by mod-host.
+
+    This process supervises mod-ui and owns its session connection only. It
+    deliberately does not decide whether the pedalboard loaded or whether
+    PipeWire links are present; those are separate diagnostics.
+    """
     process = popen([str(pw_jack), str(launcher)])
     stopping = [False]
 
@@ -211,62 +38,53 @@ def run_service(
     old_term = signal.signal(signal.SIGTERM, request_stop)
     old_int = signal.signal(signal.SIGINT, request_stop)
     client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
+    check_health = healthcheck or (lambda: check_http_health(host, port, timeout=2))
     deadline = time.monotonic() + timeout
     try:
-        while not stopping[0]:
-            if process.poll() is not None:
-                raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
-            try:
-                client.connect()
-                break
-            except OSError:
-                if time.monotonic() >= deadline:
+        if not stopping[0]:
+            deadline = time.monotonic() + timeout
+            while not stopping[0] and time.monotonic() < deadline:
+                if process.poll() is not None:
                     raise RuntimeError(
-                        f"mod-ui WebSocket did not become ready on {host}:{port}{websocket_path}"
+                        f"mod-ui launcher exited with status {process.returncode}"
                     )
+                try:
+                    if check_health():
+                        break
+                except (OSError, TimeoutError, http.client.HTTPException):
+                    pass
                 time.sleep(0.25)
+            else:
+                if not stopping[0]:
+                    raise RuntimeError("mod-ui HTTP endpoint did not become ready")
+            print("mod-ui HTTP endpoint ready")
 
-        loading = False
-        loaded_board = False
-        if not stopping[0]:
-            print("Waiting for mod-ui to finish loading the current pedalboard")
-            while not stopping[0]:
-                if process.poll() is not None:
-                    raise RuntimeError(f"mod-ui launcher exited with status {process.returncode}")
-                message = client.serve_once(timeout=0.5)
-                if message and message.startswith("loading_start "):
-                    loading = True
-                    loaded_board = False
-                elif message and message.startswith("loading_end ") and loading:
-                    loaded_board = True
-                    loading = False
-                if loaded_board:
-                    break
-                if time.monotonic() >= deadline:
-                    raise RuntimeError("mod-ui did not finish loading a pedalboard before timeout")
-            if not loaded_board and not stopping[0]:
-                raise RuntimeError("mod-ui did not load its prepared Rigforge default pedalboard")
-            if not stopping[0]:
-                print("Verifying mod-ui guitar PipeWire boundary links")
-                wait_for_guitar_boundary_links(
-                    capture_ports,
-                    playback_ports,
-                    runner=pw_link_runner,
-                    timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
-                )
-                if state_path is not None:
-                    print("Verifying mod-ui voice chain links")
-                    wait_for_graph_links(
-                        load_mod_ui_board_links(state_path),
-                        resolve_host_port=_resolve_host_alias,
-                        runner=pw_link_runner,
-                        timeout=PIPEWIRE_BOUNDARY_TIMEOUT,
-                    )
-            print("mod-ui pedalboard loaded; keeping its mod-host session active")
+        next_connect_attempt = 0.0
         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)
+                raise RuntimeError(
+                    f"mod-ui launcher exited with status {process.returncode}"
+                )
+            try:
+                if client.connection is None:
+                    if time.monotonic() < next_connect_attempt:
+                        time.sleep(min(0.25, next_connect_attempt - time.monotonic()))
+                        continue
+                    try:
+                        client.connect()
+                        print("mod-ui WebSocket session active; keeping mod-host connected")
+                    except (OSError, TimeoutError):
+                        client.close()
+                        client = ModUiWebSocketClient(
+                            host, port, websocket_path, timeout=2
+                        )
+                        next_connect_attempt = time.monotonic() + 0.25
+                        continue
+                client.serve_once(timeout=0.5)
+            except (OSError, TimeoutError, ConnectionError):
+                client.close()
+                client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
+                next_connect_attempt = time.monotonic() + 0.25
     finally:
         signal.signal(signal.SIGTERM, old_term)
         signal.signal(signal.SIGINT, old_int)
@@ -280,6 +98,11 @@ def run_service(
                 process.wait()
 
 
+def check_http_health(host, port, timeout=2):
+    with urlopen(f"http://{host}:{port}/ping/", timeout=timeout) as response:
+        return 200 <= response.status < 400
+
+
 def main(argv=None):
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument("--launcher", type=Path, required=True)
@@ -288,11 +111,6 @@ def main(argv=None):
     parser.add_argument("--port", type=int, default=8888)
     parser.add_argument("--websocket-path", default="/websocket")
     parser.add_argument("--timeout", type=float, default=60)
-    parser.add_argument(
-        "--state",
-        type=Path,
-        default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
-    )
     args = parser.parse_args(argv)
     if not args.launcher.is_file():
         print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
@@ -308,9 +126,6 @@ def main(argv=None):
             args.port,
             args.websocket_path,
             args.timeout,
-            capture_ports=os.environ.get("MOD_RIGFORGE_CAPTURE_PORTS", "").split(","),
-            playback_ports=os.environ.get("MOD_RIGFORGE_PLAYBACK_PORTS", "").split(","),
-            state_path=args.state,
         )
     except (OSError, RuntimeError, ValueError) as error:
         print(f"ERROR: {error}", file=sys.stderr)

+ 8 - 7
tests/test_deploy.py

@@ -850,20 +850,21 @@ class DeploymentTests(unittest.TestCase):
         self.assertIn("ExecStartPre=", content)
         self.assertIn("--runtime-dir %t/rigforge-mod-ui", content)
         self.assertIn("MOD_DEFAULT_PEDALBOARD=", content)
-        self.assertIn("MOD_RIGFORGE_CAPTURE_PORTS=", content)
-        self.assertIn("MOD_RIGFORGE_PLAYBACK_PORTS=", content)
         self.assertIn(
-            f'MOD_USER_FILES_DIR="{self.home / config["user_files_directory"]}"',
+            "MOD_RIGFORGE_CAPTURE_PORTS="
+            '"rigforge.mod-host-input.capture:capture_AUX0,'
+            "rigforge.mod-host-input.capture:capture_AUX1,",
             content,
         )
         self.assertIn(
-            "rigforge.mod-host-input.capture:capture_AUX0,rigforge.mod-host-input.capture:capture_AUX1,"
-            "rigforge.mod-host-input.capture:capture_AUX2,rigforge.mod-host-input.capture:capture_AUX3",
+            "MOD_RIGFORGE_PLAYBACK_PORTS="
+            '"rigforge.mod-host-output.playback:playback_AUX0,'
+            "rigforge.mod-host-output.playback:playback_AUX1,",
             content,
         )
+        self.assertNotIn("--state", content.split("ExecStart=", 1)[1].splitlines()[0])
         self.assertIn(
-            "rigforge.mod-host-output.playback:playback_AUX0,rigforge.mod-host-output.playback:playback_AUX1,"
-            "rigforge.mod-host-output.playback:playback_AUX2,rigforge.mod-host-output.playback:playback_AUX3",
+            f'MOD_USER_FILES_DIR="{self.home / config["user_files_directory"]}"',
             content,
         )
         self.assertIn("Requires=rigforge-mod-host.service rigforge-mod-host-ports.service", content)

+ 143 - 0
tests/test_diagnose_mod_ui.py

@@ -0,0 +1,143 @@
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+import diagnose_mod_ui
+
+
+class DiagnoseModUiTests(unittest.TestCase):
+    def setUp(self):
+        self.temp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temp.cleanup)
+        self.root = Path(self.temp.name)
+        self.state_path = self.root / "state.yaml"
+        self.last_state = self.root / ".local" / "share" / "rigforge" / "mod-ui" / "last.json"
+        self.last_state.parent.mkdir(parents=True)
+        self.last_state.write_text(
+            json.dumps({"pedalboard": "/tmp/rigforge.pedalboard"}),
+            encoding="utf-8",
+        )
+        self.state_path.write_text(
+            "deployment:\n"
+            "  mod_ui:\n"
+            "    last_state_file: .local/share/rigforge/mod-ui/last.json\n",
+            encoding="utf-8",
+        )
+
+    def test_reports_bundle_metadata_and_link_failure_without_websocket(self):
+        info = {
+            "title": "Rigforge",
+            "plugins": [{"uri": "urn:test"}],
+            "connections": [{"source": "a", "target": "b"}],
+        }
+        with (
+            patch.object(diagnose_mod_ui.Path, "home", return_value=self.root),
+            patch.object(diagnose_mod_ui, "fetch_pedalboard_info", return_value=info),
+            patch.object(
+                diagnose_mod_ui,
+                "load_mod_ui_board_links",
+                return_value=(("/graph/a/out", "/graph/b/in"),),
+            ),
+            patch.object(
+                diagnose_mod_ui,
+                "_resolve_host_alias",
+                side_effect=lambda port: port,
+            ),
+        ):
+            status, messages = diagnose_mod_ui.inspect_runtime(
+                self.state_path,
+                "127.0.0.1",
+                8888,
+                runner=lambda *_args, **_kwargs: SimpleNamespace(
+                    returncode=0,
+                    stdout="",
+                ),
+            )
+
+        self.assertEqual(status, 1)
+        self.assertTrue(any("1 plugins, 1 connections" in message for message in messages))
+        self.assertTrue(any("ERROR: Missing declared pedalboard PipeWire links" in message for message in messages))
+
+    def test_succeeds_when_bundle_and_all_declared_links_are_present(self):
+        info = {
+            "title": "Rigforge",
+            "plugins": [{"uri": "urn:test"}],
+            "connections": [{"source": "a", "target": "b"}],
+        }
+        with (
+            patch.object(diagnose_mod_ui.Path, "home", return_value=self.root),
+            patch.object(diagnose_mod_ui, "fetch_pedalboard_info", return_value=info),
+            patch.object(
+                diagnose_mod_ui,
+                "load_mod_ui_board_links",
+                return_value=(("source:out", "sink:in"),),
+            ),
+            patch.object(
+                diagnose_mod_ui,
+                "_resolve_host_alias",
+                side_effect=lambda port: port,
+            ),
+        ):
+            status, messages = diagnose_mod_ui.inspect_runtime(
+                self.state_path,
+                "127.0.0.1",
+                8888,
+                runner=lambda *_args, **_kwargs: SimpleNamespace(
+                    returncode=0,
+                    stdout="source:out\n  |-> sink:in\n",
+                ),
+            )
+
+        self.assertEqual(status, 0)
+        self.assertTrue(any("All 1 declared voice-chain links" in message for message in messages))
+
+    def test_empty_last_state_falls_back_to_active_mod_ui_api(self):
+        self.last_state.write_text(json.dumps({"pedalboard": ""}), encoding="utf-8")
+        info = {
+            "title": "Rigforge",
+            "plugins": [{"uri": "urn:test"}],
+            "connections": [{"source": "a", "target": "b"}],
+        }
+        with (
+            patch.object(diagnose_mod_ui.Path, "home", return_value=self.root),
+            patch.object(diagnose_mod_ui, "fetch_active_pedalboard_info", return_value=info),
+            patch.object(
+                diagnose_mod_ui,
+                "load_mod_ui_board_links",
+                return_value=(("source:out", "sink:in"),),
+            ),
+            patch.object(diagnose_mod_ui, "_resolve_host_alias", side_effect=lambda port: port),
+        ):
+            status, messages = diagnose_mod_ui.inspect_runtime(
+                self.state_path,
+                "127.0.0.1",
+                8888,
+                runner=lambda *_args, **_kwargs: SimpleNamespace(
+                    returncode=0,
+                    stdout="source:out\n  |-> sink:in\n",
+                ),
+            )
+
+        self.assertEqual(status, 0)
+        self.assertTrue(any("Active pedalboard reported by mod-ui API" in m for m in messages))
+
+    def test_resolves_guitar_capture_to_nam_audio_port(self):
+        self.assertEqual(
+            diagnose_mod_ui._resolve_host_alias("/graph/capture_1"),
+            "rigforge.mod-host-input.capture:capture_AUX0",
+        )
+        self.assertEqual(
+            diagnose_mod_ui._resolve_host_alias("/graph/rigforge_nam/input"),
+            "effect_0:input",
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 109 - 1
tests/test_mod_ui_pipewire.py

@@ -86,6 +86,16 @@ class ModUiPipeWireTests(unittest.TestCase):
             ),
             (captures["capture_1"], "effect_0:input"),
         )
+        self.assertEqual(
+            boundary_connection(
+                "capture_1",
+                "/graph/rigforge_nam/input",
+                captures,
+                playbacks,
+                self.resolve,
+            ),
+            (captures["capture_1"], "effect_0:input"),
+        )
         self.assertEqual(
             boundary_connection(
                 "/graph/rigforge_ir/out",
@@ -157,7 +167,11 @@ class ModUiPipeWireTests(unittest.TestCase):
             self.assertEqual(resolve_pedalboard_port(graph_port, resolver), expected)
         self.assertEqual(
             resolve_pedalboard_port("/graph/rigforge_ir/out", resolver),
-            "/graph/rigforge_ir/out",
+            "effect_1:out",
+        )
+        self.assertEqual(
+            resolve_pedalboard_port("capture_1", resolver),
+            "/graph/capture_1",
         )
 
     def test_resolves_plugin_edges_and_voice_playback_boundary(self):
@@ -194,6 +208,81 @@ class ModUiPipeWireTests(unittest.TestCase):
             ),
         )
 
+    def test_resolves_guitar_nam_and_ir_ports_without_jack_alias_guessing(self):
+        def fail_if_called(_port):
+            raise AssertionError("known Rigforge plugin port should resolve explicitly")
+
+        self.assertEqual(
+            resolve_pedalboard_port("/graph/rigforge_nam/input", fail_if_called),
+            "effect_0:input",
+        )
+        self.assertEqual(
+            resolve_pedalboard_port("/graph/rigforge_nam/output", fail_if_called),
+            "effect_0:output",
+        )
+        self.assertEqual(
+            resolve_pedalboard_port("/graph/rigforge_ir/in", fail_if_called),
+            "effect_1:in",
+        )
+        self.assertEqual(
+            resolve_pedalboard_port("/graph/rigforge_ir/out", fail_if_called),
+            "effect_1:out",
+        )
+        self.assertEqual(
+            pedalboard_connection(
+                "/graph/capture_1",
+                "/graph/rigforge_nam/input",
+                {"capture_1": "rigforge.mod-host-input.capture:capture_AUX0"},
+                {},
+                fail_if_called,
+            ),
+            (
+                "pipewire",
+                ("rigforge.mod-host-input.capture:capture_AUX0", "effect_0:input"),
+            ),
+        )
+        # mod-ui's HTTP connect handler strips "/graph/" from capture_1,
+        # so restoration can call the host bridge with this bare symbol.
+        self.assertEqual(
+            pedalboard_connection(
+                "capture_1",
+                "/graph/rigforge_nam/input",
+                {"capture_1": "rigforge.mod-host-input.capture:capture_AUX0"},
+                {},
+                fail_if_called,
+            ),
+            (
+                "pipewire",
+                ("rigforge.mod-host-input.capture:capture_AUX0", "effect_0:input"),
+            ),
+        )
+        self.assertEqual(
+            pedalboard_connection(
+                "/graph/rigforge_ir/out",
+                "/graph/playback_1",
+                {},
+                {"playback_1": "rigforge.mod-host-output.playback:playback_AUX0"},
+                fail_if_called,
+            ),
+            (
+                "pipewire",
+                ("effect_1:out", "rigforge.mod-host-output.playback:playback_AUX0"),
+            ),
+        )
+        self.assertEqual(
+            pedalboard_connection(
+                "/graph/rigforge_ir/out",
+                "playback_1",
+                {},
+                {"playback_1": "rigforge.mod-host-output.playback:playback_AUX0"},
+                fail_if_called,
+            ),
+            (
+                "pipewire",
+                ("effect_1:out", "rigforge.mod-host-output.playback:playback_AUX0"),
+            ),
+        )
+
     def test_connect_retries_transient_startup_port_registration_failure(self):
         edge = (
             "rigforge.mod-host-input.capture:capture_AUX0",
@@ -263,6 +352,25 @@ class ModUiPipeWireTests(unittest.TestCase):
             once = host.read_bytes()
             patched_text = once.decode("utf-8")
             self.assertIn("def _rigforge_restore_pipewire_boundary(", patched_text)
+            fix_start = patched_text.index("    def _fix_host_connection_port(")
+            fix_end = patched_text.index("\n    def ", fix_start + 8)
+            resolver_method = patched_text[fix_start:fix_end]
+            self.assertIn(
+                'if len(data) == 2 and data[0] == ""',
+                resolver_method,
+            )
+            self.assertNotIn(
+                "Rigforge bare boundary port alias",
+                patched_text[:fix_start],
+            )
+            restore_start = patched_text.index(
+                "    def _rigforge_restore_pipewire_boundary("
+            )
+            restore_end = patched_text.index(
+                "\n    def load_pb_connections(", restore_start
+            )
+            restore_method = patched_text[restore_start:restore_end]
+            self.assertIn("if connect_link(*pipewire_link):", restore_method)
             self.assertNotIn(
                 "pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)",
                 patched_text,

+ 18 - 0
tests/test_mod_ui_websocket.py

@@ -48,6 +48,24 @@ def send_server_text(connection, text):
 
 
 class ModUiWebSocketTests(unittest.TestCase):
+    def test_server_close_is_reported_as_reconnectable_connection_error(self):
+        class FakeConnection:
+            def settimeout(self, _timeout):
+                pass
+
+            def close(self):
+                pass
+
+            def sendall(self, _data):
+                pass
+
+        client = ModUiWebSocketClient("127.0.0.1", 8888)
+        client.connection = FakeConnection()
+        client.receive_frame = lambda: (0x8, b"")
+        with self.assertRaisesRegex(ConnectionError, "closed the session"):
+            client.serve_once()
+        self.assertIsNone(client.connection)
+
     def test_patch_request_uses_acknowledged_websocket_command(self):
         listener = socket.socket()
         listener.bind(("127.0.0.1", 0))

+ 162 - 168
tests/test_run_mod_ui_service.py

@@ -7,176 +7,170 @@ from unittest.mock import patch
 ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(ROOT / "scripts"))
 
-from run_mod_ui_service import (
-    _resolve_host_alias,
-    guitar_boundary_links,
-    load_mod_ui_board_links,
-    wait_for_guitar_boundary_links,
-    wait_for_graph_links,
-)
-
-
-class ModUiStartupPipeWireTests(unittest.TestCase):
-    def setUp(self):
-        self.captures = [
-            "rigforge.mod-host-input.capture:capture_AUX0",
-            "rigforge.mod-host-input.capture:capture_AUX1",
-            "rigforge.mod-host-input.capture:capture_AUX2",
-            "rigforge.mod-host-input.capture:capture_AUX3",
-        ]
-        self.playbacks = [
-            "rigforge.mod-host-output.playback:playback_AUX0",
-            "rigforge.mod-host-output.playback:playback_AUX1",
-            "rigforge.mod-host-output.playback:playback_AUX2",
-            "rigforge.mod-host-output.playback:playback_AUX3",
-        ]
-
-    def test_checks_only_the_guitar_cable_boundaries(self):
-        self.assertEqual(
-            guitar_boundary_links(self.captures, self.playbacks),
-            (
-                (self.captures[0], "effect_0:input"),
-                ("effect_1:out", self.playbacks[0]),
-            ),
-        )
-
-    def test_waits_for_both_saved_guitar_boundary_links(self):
-        outputs = [
-            SimpleNamespace(
-                returncode=0,
-                stdout="effect_0:output\n  |-> effect_1:in\n",
-            ),
-            SimpleNamespace(
-                returncode=0,
-                stdout=(
-                    f"{self.captures[0]}\n  |-> effect_0:input\n"
-                    f"effect_1:out\n  |-> {self.playbacks[0]}\n"
-                ),
-            ),
-        ]
-        elapsed = [0.0]
-        commands = []
-
-        def runner(command, **_kwargs):
-            commands.append(command)
-            return outputs.pop(0)
-
-        def sleep(seconds):
-            elapsed[0] += seconds
-
-        wait_for_guitar_boundary_links(
-            self.captures,
-            self.playbacks,
-            runner=runner,
-            timeout=1,
-            interval=0.1,
-            clock=lambda: elapsed[0],
-            sleep=sleep,
-        )
-
-        self.assertEqual(len(commands), 2)
-        self.assertGreater(elapsed[0], 0)
-
-    def test_missing_boundary_link_fails_readiness_check(self):
-        runner = lambda *_args, **_kwargs: SimpleNamespace(
-            returncode=0,
-            stdout=f"{self.captures[0]}\n  |-> effect_0:input\n",
-        )
-
-        with self.assertRaisesRegex(
-            RuntimeError, "effect_1:out -> " + self.playbacks[0]
+import run_mod_ui_service
+
+
+class FakeProcess:
+    def __init__(self):
+        self.returncode = None
+        self.terminated = False
+
+    def poll(self):
+        return self.returncode
+
+    def terminate(self):
+        self.terminated = True
+        self.returncode = 0
+
+    def wait(self, timeout=None):
+        return self.returncode
+
+
+class FakeWebSocket:
+    def __init__(self, *_args, **_kwargs):
+        self.connected = False
+        self.served = 0
+        self.closed = False
+        self.connection = None
+
+    def connect(self):
+        self.connected = True
+        self.connection = object()
+
+    def serve_once(self, timeout=1):
+        self.served += 1
+
+    def close(self):
+        self.closed = True
+        self.connection = None
+
+
+class FakeWebSocketFactory:
+    def __init__(self):
+        self.instances = []
+
+    def __call__(self, *_args, **_kwargs):
+        client = FakeWebSocket()
+        self.instances.append(client)
+        return client
+
+
+class ModUiServiceRunnerTests(unittest.TestCase):
+    def test_runner_supervises_process_and_keeps_websocket_session(self):
+        process = FakeProcess()
+        factory = FakeWebSocketFactory()
+
+        def serve_once(self, timeout=1):
+            self.served += 1
+            process.returncode = 7
+
+        with (
+            patch.object(run_mod_ui_service.signal, "signal", side_effect=lambda *_: None),
+            patch.object(run_mod_ui_service, "ModUiWebSocketClient", side_effect=factory),
+            patch.object(FakeWebSocket, "serve_once", serve_once),
+        ):
+            with self.assertRaisesRegex(RuntimeError, "exited with status 7"):
+                run_mod_ui_service.run_service(
+                    "/mod-ui",
+                    "/pw-jack",
+                    "127.0.0.1",
+                    8888,
+                    "/websocket",
+                    10,
+                    popen=lambda _args: process,
+                )
+
+        websocket = factory.instances[0]
+        self.assertTrue(websocket.connected)
+        self.assertTrue(websocket.closed)
+        self.assertGreaterEqual(websocket.served, 1)
+        self.assertFalse(process.terminated)
+
+    def test_http_health_does_not_open_a_websocket(self):
+        class Response:
+            status = 200
+
+            def __enter__(self):
+                return self
+
+            def __exit__(self, *_args):
+                return False
+
+        response = Response()
+        with patch.object(run_mod_ui_service, "urlopen", return_value=response) as urlopen:
+            self.assertTrue(run_mod_ui_service.check_http_health("127.0.0.1", 8888))
+        urlopen.assert_called_once_with("http://127.0.0.1:8888/ping/", timeout=2)
+
+    def test_runner_retries_transient_http_health_failure(self):
+        process = FakeProcess()
+        factory = FakeWebSocketFactory()
+
+        with (
+            patch.object(run_mod_ui_service.signal, "signal", side_effect=lambda *_: None),
+            patch.object(run_mod_ui_service, "ModUiWebSocketClient", side_effect=factory),
+            patch.object(run_mod_ui_service.time, "sleep", return_value=None),
         ):
-            wait_for_guitar_boundary_links(
-                self.captures,
-                self.playbacks,
-                runner=runner,
-                timeout=0,
-            )
-
-    def test_missing_port_configuration_is_rejected(self):
-        with self.assertRaisesRegex(RuntimeError, "not configured"):
-            guitar_boundary_links([], self.playbacks)
-
-    def test_voice_chain_links_resolve_to_actual_mod_host_ports(self):
-        links = load_mod_ui_board_links(
-            ROOT / "config" / "desired-state.yaml"
-        )
-        self.assertEqual(
-            links,
-            (
-                (
-                    "/graph/rigforge_voice_high_pass/out",
-                    "/graph/rigforge_voice_compressor/in",
-                ),
-                (
-                    "/graph/rigforge_voice_compressor/out",
-                    "/graph/rigforge_voice_de_esser/in",
-                ),
-                (
-                    "/graph/rigforge_voice_de_esser/out",
-                    "/graph/rigforge_voice_reverb/input_l",
-                ),
-                (
-                    "/graph/rigforge_voice_reverb/output_l",
-                    "/graph/playback_3",
-                ),
-            ),
-        )
-        self.assertEqual(
-            tuple(_resolve_host_alias(port) for edge in links for port in edge),
-            (
-                "effect_2:out",
-                "effect_3:in",
-                "effect_3:out",
-                "effect_4:in",
-                "effect_4:out",
-                "effect_5:lv2_audio_in_1",
-                "effect_5:lv2_audio_out_1",
-                "rigforge.mod-host-output.playback:playback_AUX2",
-            ),
-        )
-        wait_for_graph_links(
-            links,
-            _resolve_host_alias,
-            runner=lambda *_args, **_kwargs: SimpleNamespace(
-                returncode=0,
-                stdout=(
-                    "effect_2:out\n  |-> effect_3:in\n"
-                    "effect_3:out\n  |-> effect_4:in\n"
-                    "effect_4:out\n  |-> effect_5:lv2_audio_in_1\n"
-                    f"effect_5:lv2_audio_out_1\n  |-> {self.playbacks[2]}\n"
-                ),
-            ),
-            timeout=0,
-        )
-
-    def test_wait_for_voice_graph_links_reports_missing_edge(self):
-        runner = lambda *_args, **_kwargs: SimpleNamespace(
-            returncode=0,
-            stdout=(
-                f"effect_4:out\n  |-> effect_5:lv2_audio_in_1\n"
-                f"effect_5:output_r\n  |-> {self.playbacks[2]}\n"
-            ),
-        )
-        with self.assertRaisesRegex(
-            RuntimeError,
-            "effect_5:lv2_audio_out_1 -> " + self.playbacks[2],
+            health_calls = [0]
+
+            def healthcheck():
+                health_calls[0] += 1
+                if health_calls[0] == 1:
+                    raise TimeoutError("not listening yet")
+                return health_calls[0] > 1
+
+            def serve_once(self, timeout=1):
+                self.served += 1
+                process.returncode = 9
+
+            with patch.object(FakeWebSocket, "serve_once", serve_once):
+                with self.assertRaisesRegex(RuntimeError, "exited with status 9"):
+                    run_mod_ui_service.run_service(
+                        "/mod-ui",
+                        "/pw-jack",
+                        "127.0.0.1",
+                        8888,
+                        "/websocket",
+                        10,
+                        popen=lambda _args: process,
+                        healthcheck=healthcheck,
+                    )
+
+        self.assertEqual(health_calls[0], 2)
+        self.assertTrue(factory.instances[-1].closed)
+
+    def test_closed_websocket_is_reconnected_without_exiting_service(self):
+        process = FakeProcess()
+        factory = FakeWebSocketFactory()
+        received = [0]
+
+        def serve_once(self, timeout=1):
+            received[0] += 1
+            self.served += 1
+            if received[0] == 1:
+                self.connection = None
+                raise ConnectionError("mod-ui closed the session WebSocket")
+            process.returncode = 11
+
+        with (
+            patch.object(run_mod_ui_service.signal, "signal", side_effect=lambda *_: None),
+            patch.object(run_mod_ui_service, "ModUiWebSocketClient", side_effect=factory),
+            patch.object(run_mod_ui_service.time, "sleep", return_value=None),
+            patch.object(FakeWebSocket, "serve_once", serve_once),
         ):
-            wait_for_graph_links(
-                (
-                    (
-                        "/graph/rigforge_voice_de_esser/out",
-                        "/graph/rigforge_voice_reverb/input_l",
-                    ),
-                    (
-                        "/graph/rigforge_voice_reverb/output_l",
-                        "/graph/playback_3",
-                    ),
-                ),
-                resolve_host_port=_resolve_host_alias,
-                runner=runner,
-                timeout=0,
-            )
+            with self.assertRaisesRegex(RuntimeError, "exited with status 11"):
+                run_mod_ui_service.run_service(
+                    "/mod-ui",
+                    "/pw-jack",
+                    "127.0.0.1",
+                    8888,
+                    "/websocket",
+                    10,
+                    popen=lambda _args: process,
+                    healthcheck=lambda: True,
+                )
+
+        self.assertGreaterEqual(len(factory.instances), 2)
+        self.assertTrue(factory.instances[0].closed)
 
 
 if __name__ == "__main__":