Quellcode durchsuchen

try fix modui pedalboard not all links

Johan Le Baut vor 4 Tagen
Ursprung
Commit
be51d8d816

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

@@ -4425,8 +4425,7 @@ class Host(object):
                 )
             )
 
-        connections_now = self.connections
-        if edge in connections_now:
+        if edge in self.connections:
             self._rigforge_restore_attempts.pop(edge, None)
             return
 
@@ -4470,7 +4469,6 @@ class Host(object):
             pipewire_link,
             port_from,
             port_to,
-            connections_now,
             attempts_left - 1
         )
 

+ 1 - 4
build/arm64/patch_mod_ui_rigforge.py

@@ -291,8 +291,7 @@ def patch_load_connections(host):
                 )
             )
 
-        connections_now = self.connections
-        if edge in connections_now:
+        if edge in self.connections:
             self._rigforge_restore_attempts.pop(edge, None)
             return
 
@@ -336,7 +335,6 @@ def patch_load_connections(host):
             pipewire_link,
             port_from,
             port_to,
-            connections_now,
             attempts_left - 1
         )
 
@@ -354,7 +352,6 @@ def patch_load_connections(host):
         if position < 0:
             raise RuntimeError(f"could not insert PipeWire restore method in {host}")
         updated = updated[:position] + restore_method + updated[position:]
-
     if updated != original_text:
         host.write_text(updated, encoding="utf-8")
 

+ 27 - 0
scripts/diagnose_mod_ui.py

@@ -12,6 +12,10 @@ from urllib.request import urlopen
 import yaml
 
 from observe_pipewire import parse_pw_link_output
+from load_mod_ui_pedalboard import (
+    request_load_through_ui,
+    wait_http,
+)
 
 
 def load_mod_ui_board_links(state_path):
@@ -181,6 +185,14 @@ def inspect_runtime(state_path, host, port, runner=subprocess.run, timeout=5):
     ]
 
 
+def load_active_pedalboard(board_path, host, port, timeout=20):
+    """Load through mod-ui's browser path and observe its real load lifecycle."""
+    wait_http(host, port, timeout)
+    message = request_load_through_ui(host, port, Path(board_path), timeout)
+    if not message.startswith("loading_start "):
+        raise RuntimeError(f"unexpected pedalboard load response: {message}")
+
+
 def main(argv=None):
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument(
@@ -190,8 +202,23 @@ def main(argv=None):
     )
     parser.add_argument("--host", default="127.0.0.1")
     parser.add_argument("--port", type=int, default=8888)
+    parser.add_argument(
+        "--load",
+        action="store_true",
+        help="load the last selected pedalboard through mod-ui's active session before checking",
+    )
     args = parser.parse_args(argv)
     try:
+        if args.load:
+            state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
+            last_state = (
+                Path.home() / state["deployment"]["mod_ui"]["last_state_file"]
+            )
+            last_data = json.loads(last_state.read_text(encoding="utf-8"))
+            board_path = last_data.get("pedalboard")
+            if not board_path:
+                raise ValueError("mod-ui last-state file has no selected pedalboard")
+            load_active_pedalboard(board_path, args.host, args.port, timeout=20)
         status, messages = inspect_runtime(args.state, args.host, args.port)
     except (OSError, KeyError, TypeError, ValueError) as error:
         print(f"ERROR: {error}", file=sys.stderr)

+ 203 - 0
scripts/load_mod_ui_pedalboard.py

@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""Load the selected mod-ui pedalboard through its active session WebSocket."""
+
+import argparse
+import base64
+import hashlib
+import json
+import os
+import socket
+import struct
+import sys
+import time
+from pathlib import Path
+from urllib.error import URLError
+from urllib.parse import urlencode
+from urllib.request import urlopen
+from urllib.request import Request
+
+
+def encode_control_frame(opcode, payload=b""):
+    payload = payload if isinstance(payload, bytes) else payload.encode("utf-8")
+    mask = os.urandom(4)
+    size = len(payload)
+    if size < 126:
+        header = bytes((0x80 | opcode, 0x80 | size))
+    elif size < 65536:
+        header = bytes((0x80 | opcode, 0x80 | 126)) + struct.pack("!H", size)
+    else:
+        header = bytes((0x80 | opcode, 0x80 | 127)) + struct.pack("!Q", size)
+    masked = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
+    return header + mask + masked
+
+
+def request_load_through_ui(host, port, bundle, timeout):
+    """Open the normal pedalboard page and load through its browser-owned session."""
+    websocket_path = "/websocket"
+    with socket.create_connection((host, port), timeout=timeout) as connection:
+        connection.settimeout(timeout)
+        key = base64.b64encode(os.urandom(16)).decode("ascii")
+        request = (
+            f"GET {websocket_path} HTTP/1.1\r\n"
+            f"Host: {host}:{port}\r\n"
+            "Upgrade: websocket\r\n"
+            "Connection: Upgrade\r\n"
+            f"Origin: http://{host}:{port}\r\n"
+            f"Sec-WebSocket-Key: {key}\r\n"
+            "Sec-WebSocket-Version: 13\r\n\r\n"
+        )
+        connection.sendall(request.encode("ascii"))
+        response = bytearray()
+        while not response.endswith(b"\r\n\r\n"):
+            chunk = connection.recv(1)
+            if not chunk:
+                raise RuntimeError("mod-ui closed the WebSocket handshake")
+            response.extend(chunk)
+        if b" 101 " not in response.split(b"\r\n", 1)[0]:
+            raise RuntimeError("mod-ui rejected the WebSocket handshake")
+        expected = base64.b64encode(
+            hashlib.sha1(
+                (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode("ascii")
+            ).digest()
+        )
+        headers = response.decode("latin-1").split("\r\n")
+        accept_header = next(
+            (
+                value.strip()
+                for line in headers
+                if line.casefold().startswith("sec-websocket-accept:")
+                for value in (line.split(":", 1)[1],)
+            ),
+            None,
+        )
+        if accept_header != expected.decode("ascii"):
+            raise RuntimeError("mod-ui returned an invalid WebSocket accept key")
+
+        # Register as the browser's active session and wait for its initial state.
+        receive_initial_state(connection)
+
+        from urllib.parse import quote
+        page_url = (
+            f"http://{host}:{port}/pedalboard.html?v=rigforge&bundlepath="
+            f"{quote(str(bundle), safe='')}"
+        )
+        with urlopen(page_url, timeout=timeout) as page:
+            html = page.read().decode("utf-8", errors="replace")
+        if "fakeLoadFromServerData" not in html:
+            raise RuntimeError("mod-ui pedalboard page did not contain its board data")
+        wait_for_message_prefix(connection, "loading_end ")
+
+        reset_request = Request(f"http://{host}:{port}/reset")
+        with urlopen(reset_request, timeout=timeout) as response:
+            if not json.loads(response.read().decode("utf-8", errors="replace")):
+                raise RuntimeError("mod-ui refused to reset the current pedalboard")
+
+        # Match the active browser's acknowledgement that its reset is complete.
+        # Desktop.loadPedalboard uses POST after reset. The HTTP response only
+        # confirms Host.load(), while browser host.js must consume loading_start
+        # and then its own data_ready round trip before drawing cables.
+        body = urlencode({"bundlepath": str(bundle)}).encode()
+        request = Request(
+            f"http://{host}:{port}/pedalboard/load_bundle/",
+            data=body,
+            method="POST",
+        )
+        with urlopen(request, timeout=timeout) as response:
+            data = response.read().decode("utf-8", errors="replace")
+        if not json.loads(data).get("ok"):
+            raise RuntimeError(f"mod-ui rejected bundle load: {data}")
+        connection.sendall(encode_control_frame(0x1, "data_ready 1"))
+        message = wait_for_message_prefix(connection, "loading_end ")
+        return message
+
+
+def receive_frame(connection):
+    header = receive_exact(connection, 2)
+    first, second = header
+    opcode = first & 0x0F
+    size = second & 0x7F
+    if size == 126:
+        size = struct.unpack("!H", receive_exact(connection, 2))[0]
+    elif size == 127:
+        size = struct.unpack("!Q", receive_exact(connection, 8))[0]
+    mask = receive_exact(connection, 4) if second & 0x80 else b""
+    payload = receive_exact(connection, size)
+    if mask:
+        payload = bytes(value ^ mask[index % 4] for index, value in enumerate(payload))
+    return opcode, payload
+
+
+def receive_exact(connection, size):
+    payload = bytearray()
+    while len(payload) < size:
+        chunk = connection.recv(size - len(payload))
+        if not chunk:
+            raise RuntimeError("mod-ui closed its WebSocket")
+        payload.extend(chunk)
+    return bytes(payload)
+
+
+def receive_initial_state(connection):
+    while True:
+        opcode, payload = receive_frame(connection)
+        if opcode == 0x8:
+            raise RuntimeError("mod-ui closed WebSocket before initial state")
+        if opcode == 0x9:
+            connection.sendall(encode_control_frame(0xA, payload))
+            continue
+        if opcode == 0x1:
+            message = payload.decode("utf-8", errors="replace")
+            if message.startswith("loading_end "):
+                return
+
+
+def wait_for_message_prefix(connection, prefix):
+    while True:
+        opcode, payload = receive_frame(connection)
+        if opcode == 0x8:
+            raise RuntimeError("mod-ui closed WebSocket during pedalboard load")
+        if opcode == 0x9:
+            connection.sendall(encode_control_frame(0xA, payload))
+            continue
+        if opcode == 0x1:
+            message = payload.decode("utf-8", errors="replace")
+            if message.startswith(prefix):
+                return message
+
+
+def wait_http(host, port, timeout):
+    deadline = time.monotonic() + timeout
+    while time.monotonic() < deadline:
+        try:
+            with urlopen(f"http://{host}:{port}/ping/", timeout=1) as response:
+                if 200 <= response.status < 400:
+                    return
+        except (OSError, TimeoutError, URLError):
+            time.sleep(0.2)
+    raise TimeoutError(f"mod-ui HTTP endpoint did not become ready at {host}:{port}")
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("bundle", type=Path)
+    parser.add_argument("--host", default="127.0.0.1")
+    parser.add_argument("--port", type=int, default=8888)
+    parser.add_argument("--timeout", type=float, default=20)
+    args = parser.parse_args(argv)
+    bundle = args.bundle.resolve()
+    if not bundle.is_dir():
+        parser.error(f"pedalboard bundle directory does not exist: {bundle}")
+    try:
+        wait_http(args.host, args.port, args.timeout)
+        message = request_load_through_ui(
+            args.host, args.port, bundle, args.timeout
+        )
+        print(f"mod-ui session accepted pedalboard load: {message}")
+    except (OSError, RuntimeError, TimeoutError, ValueError) as error:
+        print(f"ERROR: {error}", file=sys.stderr)
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 20 - 0
scripts/mod_ui_websocket.py

@@ -116,6 +116,26 @@ class ModUiWebSocketClient:
             return message
         return None
 
+    def wait_for_loading_start(self):
+        """Wait until backend starts loading a pedalboard on this session."""
+        self.connect()
+        while True:
+            opcode, payload = self.receive_frame()
+            if opcode == 0x8:
+                raise RuntimeError("mod-ui closed the WebSocket while loading pedalboard")
+            if opcode == 0x9:
+                self._send_frame(0xA, payload)
+                continue
+            if opcode != 0x1:
+                continue
+            message = payload.decode("utf-8", errors="replace")
+            if message == "ping" or message.startswith("data_ready "):
+                self.process_control_message(message)
+                continue
+            if message.startswith("loading_start "):
+                return message
+
+
     def set_patch(self, instance, property_uri, value):
         self.connect()
         request_id = uuid.uuid4().hex

+ 22 - 3
tests/test_mod_ui_pipewire.py

@@ -381,13 +381,32 @@ class ModUiPipeWireTests(unittest.TestCase):
             self.assertIn("if ready and connect_link(*pipewire_link):", restore_method)
             self.assertIn('["pw-link", "-o"]', restore_method)
             self.assertIn("edge = (port_from, port_to)", restore_method)
-            self.assertIn("connections_now = self.connections", restore_method)
-            self.assertIn("if edge in connections_now:", restore_method)
-            self.assertIn("connections_now,", restore_method)
+            self.assertIn("if edge in self.connections:", restore_method)
+            self.assertNotIn("connections_now", restore_method)
+            self.assertIn(
+                "self._rigforge_restore_pipewire_boundary,\n"
+                "            pipewire_link,\n"
+                "            port_from,\n"
+                "            port_to,\n"
+                "            attempts_left - 1",
+                restore_method,
+            )
+            self.assertNotIn(
+                "            connections_now,\n            attempts_left - 1",
+                restore_method,
+            )
             self.assertIn("if edge not in self.connections:", restore_method)
             self.assertNotIn("self.connections is not connection_list", restore_method)
             self.assertNotIn("len(self.audioportsIn) ==", restore_method)
             self.assertNotIn("len(self.audioportsOut) ==", restore_method)
+            self.assertIn(
+                "            attempts_left - 1\n        )",
+                patched_text[restore_start:restore_end],
+            )
+            self.assertNotIn(
+                "            connections_now,\n            attempts_left - 1",
+                patched_text[restore_start:restore_end],
+            )
             self.assertNotIn(
                 "pipewire_link = self._rigforge_pipewire_boundary(port_from, port_to)",
                 patched_text,

+ 16 - 0
tests/test_mod_ui_websocket.py

@@ -48,6 +48,22 @@ def send_server_text(connection, text):
 
 
 class ModUiWebSocketTests(unittest.TestCase):
+    def test_wait_for_loading_start_ignores_unrelated_messages(self):
+        client = ModUiWebSocketClient("127.0.0.1", 8888)
+        client.connect = lambda: None
+        frames = iter(
+            (
+                (0x1, b"data_ready 4"),
+                (0x1, b"loading_start 0 0"),
+            )
+        )
+        client.receive_frame = lambda: next(frames)
+        client.send_text = lambda _message: None
+
+        message = client.wait_for_loading_start()
+
+        self.assertEqual(message, "loading_start 0 0")
+
     def test_server_close_is_reported_as_reconnectable_connection_error(self):
         class FakeConnection:
             def settimeout(self, _timeout):