4
0

ui_monkey.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #!/usr/bin/env python3
  2. """Seeded UI monkey test of the real LYNX window (round 190rb, the 0.1.32 quality release).
  3. Starts `LYNX --demo [project]` on an X display (a private Xvfb), then drives it for a while with a seeded random mix of
  4. real X input (xdotool: clicks, right-clicks, drags, wheel, keys) and structured Remote Control / --demo operations
  5. (docs/DEMO_MODE.md: click a random showing control, run a random key-map action, switch layouts, open panels and
  6. editors, undo / redo, save and reload). Every action is written to <out>/actions.jsonl *before* it runs, fully resolved
  7. (coordinates, control IDs), so `--replay <actions.jsonl>` repeats a run without the random generator.
  8. It stops at the first crash (the process died: its exit code and the sanitizer reports in <out>/san.*), a hang (the
  9. API stopped answering for --hang-seconds: SIGABRT, so ASan prints the main thread's stack) or the time limit.
  10. <out>/result.json says which. Run it inside a sandbox where the files that matter are read-only
  11. (scripts/ui-monkey.sh does): random clicks reach Save as..., the file browser and every other menu item.
  12. ui_monkey.py --app LYNX --display :190 --seed 7 --minutes 5 --layout pattern --project song.flp --out runs/s7
  13. ui_monkey.py --app LYNX --display :190 --replay runs/s7/actions.jsonl --out runs/s7-replay
  14. Windows (round 190rf): `--windows` (with the embeddable Python for Windows; --display is then unused) starts LYNX.exe on
  15. a desktop of its own that is never shown, as a low-integrity process that can write only to the run folder
  16. (tools/winsandbox.py), and drives it with the Remote Control / --demo operations only (no operating-system input at
  17. all: --api-only, which Linux runs may use too). A hang is ended by the harness after LYNX's own hang watch has written
  18. the main thread's stack to <out>/profile/.../autosave/hang *.txt.
  19. """
  20. import argparse
  21. import json
  22. import os
  23. from pathlib import Path
  24. import random
  25. import signal
  26. import subprocess
  27. import sys
  28. import time
  29. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "examples"))
  30. sys.path.insert(0, str(Path(__file__).resolve().parent)) # (tools/winsandbox.py; the embeddable Python adds no script folder)
  31. from remote_control import Client # noqa: E402 (the repo's standard-library client)
  32. LAYOUTS = ["pattern", "clipLaunch", "simple"]
  33. PANELS = ["channelRack", "pianoRoll", "playlist", "mixer", "browser", "loops", "dock", "pluginManager", "versions"]
  34. # keys a user presses (FL's and LYNX's shortcuts among them); no Alt+F4 (it would only end the run early)
  35. KEYS = ["Escape", "Escape", "Return", "space", "Tab", "Delete", "BackSpace", "Left", "Right", "Up", "Down", "Home", "End",
  36. "Prior", "Next", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
  37. "ctrl+z", "ctrl+y", "ctrl+shift+z", "alt+z", "ctrl+c", "ctrl+v", "ctrl+x", "ctrl+a", "ctrl+d", "ctrl+b",
  38. "ctrl+l", "ctrl+n", "ctrl+o", "ctrl+s", "ctrl+shift+s", "ctrl+t", "ctrl+f", "ctrl+e", "ctrl+r", "ctrl+i",
  39. "shift+Delete", "shift+Left", "shift+Right", "ctrl+Left", "ctrl+Right", "ctrl+Up", "ctrl+Down", "ctrl+Insert",
  40. "ctrl+alt+Insert", "shift+Insert", "Insert", "plus", "minus", "ctrl+plus", "ctrl+minus", "Menu",
  41. "a", "b", "c", "d", "e", "g", "l", "m", "n", "p", "q", "r", "s", "t", "u", "w", "x", "y", "z",
  42. "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "alt+1", "alt+2", "alt+3", "ctrl+1", "ctrl+2", "shift+1"]
  43. WEIGHTS = {
  44. "api_click": 22, "x_click": 16, "x_drag": 8, "x_wheel": 7, "x_key": 13, "action": 10, "escape": 6, "show": 5,
  45. "undo_redo": 5, "editor": 3, "api_drag": 3, "layout": 2, "save_reload": 1, "open": 1, "repaint": 1,
  46. }
  47. class Monkey:
  48. def __init__(self, a):
  49. self.a = a
  50. self.out = Path(a.out).resolve()
  51. self.out.mkdir(parents=True, exist_ok=True)
  52. self.profile = self.out / "profile"
  53. self.profile.mkdir(exist_ok=True)
  54. if not a.windows: # (Windows: LYNX makes it with its private, protected access list itself)
  55. (self.profile / "control").mkdir(mode=0o700, exist_ok=True) # (the discovery folder must be private)
  56. os.chmod(self.profile / "control", 0o700)
  57. self.log = open(self.out / "actions.jsonl", "a", buffering=1)
  58. self.proc = None
  59. self.client = None
  60. self.controls = []
  61. self.controls_at = -99
  62. self.window = None
  63. self.actions = self.load_actions()
  64. self.saves = 0
  65. self.count = 0
  66. # --- process ---------------------------------------------------------------------------------------------------
  67. def env(self):
  68. e = dict(os.environ)
  69. e["LYNX_OFFLINE"] = "1" # (no update check, no crash report upload, no live session: nothing leaves the machine)
  70. if self.a.windows:
  71. tmp = self.out / "tmp"
  72. tmp.mkdir(exist_ok=True)
  73. # no audio device (the real one would sound on the user's speakers): a saved setup that names none
  74. dev = self.profile / "LYNX/audio-device.xml"
  75. dev.parent.mkdir(parents=True, exist_ok=True)
  76. if not dev.exists():
  77. dev.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<DEVICESETUP deviceType="Windows Audio" audioOutputDeviceName=""'
  78. ' audioInputDeviceName="" audioDeviceRate="48000.0" audioDeviceBufferSize="512"/>\n')
  79. # the plugin scan looks in an empty folder: no installed plugin is loaded (licence windows on a desktop nobody sees)
  80. empty = self.out / "no-plugins"
  81. empty.mkdir(exist_ok=True)
  82. folders = dev.parent / "plugin-folders.txt"
  83. if not folders.exists():
  84. folders.write_text(str(empty) + "\n")
  85. e.update({"LYNX_PROFILE_DIR": str(self.profile), "LYNX_CONTROL_ENABLED": "1",
  86. "LYNX_CONTROL_DISCOVERY": str(self.profile / "control/connection.json"), "TEMP": str(tmp), "TMP": str(tmp)})
  87. return e
  88. san = str(self.out / "san")
  89. e.update({
  90. "DISPLAY": self.a.display, "LYNX_PROFILE_DIR": str(self.profile), "XDG_CONFIG_HOME": str(self.profile / "config"),
  91. "XDG_DATA_HOME": str(self.profile / "data"), "XDG_CACHE_HOME": str(self.profile / "cache"),
  92. "LYNX_CONTROL_ENABLED": "1", "LYNX_CONTROL_DISCOVERY": str(self.profile / "control/connection.json"),
  93. "ASAN_OPTIONS": e.get("ASAN_OPTIONS", "") + f":log_path={san}.asan:handle_abort=1:detect_leaks=0",
  94. "UBSAN_OPTIONS": e.get("UBSAN_OPTIONS", "print_stacktrace=1:halt_on_error=0") + f":log_path={san}.ubsan",
  95. })
  96. e.pop("WAYLAND_DISPLAY", None)
  97. return e
  98. def start(self, project):
  99. args = [self.a.app, "--demo"] + ([project] if project else [])
  100. if self.a.windows:
  101. import winsandbox
  102. winsandbox.label_low(self.out)
  103. self.proc = winsandbox.start_sandboxed(args, self.env(), self.out, f"lynx-monkey-{os.getpid()}", self.out / "lynx.out")
  104. else:
  105. self.stdout = open(self.out / "lynx.out", "ab")
  106. self.proc = subprocess.Popen(args, env=self.env(), stdin=subprocess.DEVNULL, stdout=self.stdout, stderr=subprocess.STDOUT,
  107. cwd=str(self.out))
  108. disc = self.profile / "control/connection.json"
  109. deadline = time.time() + self.a.start_seconds
  110. while time.time() < deadline:
  111. if self.proc.poll() is not None:
  112. return False
  113. if disc.exists():
  114. try:
  115. self.client = Client(disc)
  116. self.call("ui.window", timeout_ok=True)
  117. return True
  118. except Exception:
  119. pass
  120. time.sleep(0.5)
  121. return False
  122. def alive(self):
  123. return self.proc is not None and self.proc.poll() is None
  124. def call(self, op, args=None, timeout_ok=False):
  125. try:
  126. return self.client.call(op, args or {})
  127. except RuntimeError as e: # an error answer: a refused operation is fine for a monkey
  128. return {"error": str(e)[:200]}
  129. except OSError as e:
  130. if timeout_ok:
  131. raise
  132. return {"oserror": str(e)[:200]}
  133. # --- helpers ---------------------------------------------------------------------------------------------------
  134. def load_actions(self):
  135. f = Path(__file__).resolve().parent.parent / "src/core/KeyMap.cpp"
  136. import re
  137. ids = sorted(set(re.findall(r'\{\s*"([a-z]+\.[A-Za-z0-9.]+)"', f.read_text(errors="replace")))) if f.exists() else []
  138. return ids or ["edit.undo", "edit.redo"]
  139. def xdo(self, *args):
  140. subprocess.run([self.a.xdotool] + [str(x) for x in args], env={**os.environ, "DISPLAY": self.a.display},
  141. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)
  142. def win(self, rng):
  143. if self.window is None or rng.random() < 0.05:
  144. r = self.call("ui.window")
  145. s = r.get("screen") if isinstance(r, dict) else None
  146. if isinstance(s, dict):
  147. self.window = (s.get("x", 0), s.get("y", 0), max(200, s.get("width", 1600)), max(200, s.get("height", 900)))
  148. elif isinstance(s, list) and len(s) == 4:
  149. self.window = tuple(s)
  150. return self.window or (0, 0, 1600, 900)
  151. def point(self, rng):
  152. x, y, w, h = self.win(rng)
  153. return int(x + rng.random() * w), int(y + rng.random() * h)
  154. def control(self, rng):
  155. if self.count - self.controls_at > 8 or not self.controls:
  156. r = self.call("ui.list", {"limit": 2000})
  157. self.controls = [c for c in (r.get("controls") or []) if isinstance(c, dict) and c.get("id")] if isinstance(r, dict) else []
  158. self.controls_at = self.count
  159. return rng.choice(self.controls) if self.controls else None
  160. # --- one random action, resolved to a replayable record --------------------------------------------------------
  161. def plan(self, rng):
  162. weights = {k: (0 if self.a.api_only and (k.startswith("x_") or k == "escape") else v) for k, v in WEIGHTS.items()}
  163. kind = rng.choices(list(weights), weights=list(weights.values()))[0]
  164. if kind == "api_click":
  165. c = self.control(rng)
  166. if c is None:
  167. return {"k": "escape"}
  168. return {"k": kind, "target": c["id"], "right": rng.random() < 0.2, "double": rng.random() < 0.1,
  169. "at": {"x": round(rng.random(), 3), "y": round(rng.random(), 3)}}
  170. if kind == "api_drag":
  171. c1, c2 = self.control(rng), self.control(rng)
  172. if c1 is None or c2 is None:
  173. return {"k": "escape"}
  174. return {"k": kind, "from": c1["id"], "to": c2["id"], "dx": rng.randint(-80, 80), "dy": rng.randint(-40, 40),
  175. "mods": rng.choice([[], [], ["ctrl"], ["shift"], ["alt"]])}
  176. if kind == "x_click":
  177. x, y = self.point(rng)
  178. return {"k": kind, "x": x, "y": y, "button": rng.choice([1, 1, 1, 3]), "repeat": rng.choice([1, 1, 1, 2]),
  179. "mod": rng.choice(["", "", "", "ctrl", "shift", "alt"])}
  180. if kind == "x_drag":
  181. x, y = self.point(rng)
  182. return {"k": kind, "x": x, "y": y, "x2": x + rng.randint(-400, 400), "y2": y + rng.randint(-250, 250),
  183. "button": rng.choice([1, 1, 3]), "mod": rng.choice(["", "", "ctrl", "shift", "alt"]), "steps": rng.randint(2, 12)}
  184. if kind == "x_wheel":
  185. x, y = self.point(rng)
  186. return {"k": kind, "x": x, "y": y, "button": rng.choice([4, 5, 6, 7]), "n": rng.randint(1, 8),
  187. "mod": rng.choice(["", "", "ctrl", "shift", "alt"])}
  188. if kind == "x_key":
  189. return {"k": kind, "key": rng.choice(KEYS)}
  190. if kind == "action":
  191. return {"k": kind, "id": rng.choice(self.actions)}
  192. if kind == "show":
  193. return {"k": kind, "panel": rng.choice(PANELS)}
  194. if kind == "undo_redo":
  195. return {"k": kind, "seq": [rng.choice(["edit.undo", "edit.undo", "edit.redo"]) for _ in range(rng.randint(1, 6))]}
  196. if kind == "editor":
  197. return {"k": kind, "channel": rng.randint(0, 20)}
  198. if kind == "layout":
  199. return {"k": kind, "style": rng.choice(LAYOUTS)}
  200. if kind == "save_reload":
  201. self.saves += 1
  202. return {"k": kind, "path": str(self.out / f"save{self.saves}.lynx")}
  203. if kind == "open":
  204. return {"k": kind, "file": rng.choice(self.a.projects)} if self.a.projects else {"k": "escape"}
  205. return {"k": kind}
  206. def run_action(self, act):
  207. k = act["k"]
  208. if k == "api_click":
  209. self.call("ui.click", {"target": act["target"], "right": act["right"], "double": act["double"], "at": act["at"]})
  210. elif k == "api_drag":
  211. self.call("ui.drag", {"from": {"target": act["from"]}, "to": {"target": act["to"], "dx": act["dx"], "dy": act["dy"]},
  212. "mods": act["mods"], "seconds": 0.3})
  213. time.sleep(0.35)
  214. elif k == "x_click":
  215. self.xdo("mousemove", act["x"], act["y"])
  216. if act["mod"]:
  217. self.xdo("keydown", act["mod"])
  218. self.xdo("click", "--repeat", act["repeat"], "--delay", 60, act["button"])
  219. if act["mod"]:
  220. self.xdo("keyup", act["mod"])
  221. elif k == "x_drag":
  222. self.xdo("mousemove", act["x"], act["y"])
  223. if act["mod"]:
  224. self.xdo("keydown", act["mod"])
  225. self.xdo("mousedown", act["button"])
  226. for i in range(1, act["steps"] + 1):
  227. t = i / act["steps"]
  228. self.xdo("mousemove", int(act["x"] + (act["x2"] - act["x"]) * t), int(act["y"] + (act["y2"] - act["y"]) * t))
  229. self.xdo("mouseup", act["button"])
  230. if act["mod"]:
  231. self.xdo("keyup", act["mod"])
  232. elif k == "x_wheel":
  233. self.xdo("mousemove", act["x"], act["y"])
  234. if act["mod"]:
  235. self.xdo("keydown", act["mod"])
  236. self.xdo("click", "--repeat", act["n"], "--delay", 30, act["button"])
  237. if act["mod"]:
  238. self.xdo("keyup", act["mod"])
  239. elif k == "x_key":
  240. self.xdo("key", "--clearmodifiers", act["key"])
  241. elif k == "escape":
  242. if self.a.api_only:
  243. self.call("ui.window") # (no operating-system input in an API-only run)
  244. else:
  245. self.xdo("key", "Escape")
  246. elif k == "action":
  247. self.call("ui.action", {"id": act["id"]})
  248. elif k == "show":
  249. self.call("ui.show", {"panel": act["panel"]})
  250. elif k == "undo_redo":
  251. for a in act["seq"]:
  252. self.call("ui.action", {"id": a})
  253. elif k == "editor":
  254. self.call("ui.editor", {"channel": act["channel"]})
  255. elif k == "layout":
  256. self.call("ui.layout", {"style": act["style"]})
  257. self.controls = []
  258. elif k == "save_reload":
  259. r = self.call("file.save", {"path": act["path"]})
  260. if Path(act["path"]).exists():
  261. self.call("ui.open", {"file": act["path"]})
  262. elif k == "open":
  263. self.call("ui.open", {"file": act["file"]})
  264. self.controls = []
  265. elif k == "repaint":
  266. self.call("ui.repaint")
  267. elif k == "welcome":
  268. self.call("ui.welcome", {"choice": act["choice"]})
  269. elif k == "start_layout":
  270. self.call("ui.layout", {"style": act["style"]})
  271. # --- the run ---------------------------------------------------------------------------------------------------
  272. def responsive(self):
  273. t0 = time.time()
  274. while time.time() - t0 < self.a.hang_seconds:
  275. if not self.alive():
  276. return True # (dead, not hung: the caller sees it)
  277. try:
  278. self.client.call("ui.window", {})
  279. return True
  280. except RuntimeError:
  281. return True
  282. except OSError:
  283. time.sleep(1)
  284. return False
  285. def finish(self, status, detail=""):
  286. rc = self.proc.poll() if self.proc else None
  287. if status == "hang" and self.alive() and self.a.windows:
  288. time.sleep(15) # (LYNX's hang watch writes the main thread's stack to its autosave folder)
  289. self.proc.kill()
  290. rc = self.proc.poll()
  291. elif status == "hang" and self.alive():
  292. os.kill(self.proc.pid, signal.SIGABRT) # ASan (handle_abort=1) prints where the main thread is
  293. try:
  294. self.proc.wait(30)
  295. except subprocess.TimeoutExpired:
  296. self.proc.kill()
  297. rc = self.proc.poll()
  298. elif status == "timeout" and not self.alive():
  299. status, detail = "crash", "died before quitting (after the last action)"
  300. elif status == "timeout" and self.alive():
  301. # the app's own shutdown (engine, plugins, windows torn down in order) is part of the test
  302. self.log.write(json.dumps({"k": "quit", "n": self.count, "t": round(time.time() - self.t0, 2)}) + "\n")
  303. answer = self.call("app.quit", {"discard": True})
  304. terminated = not (isinstance(answer, dict) and answer.get("quitting"))
  305. if terminated and isinstance(answer, dict) and "oserror" in answer:
  306. try:
  307. self.proc.wait(10) # (a crash closes the connection a moment before the process is gone)
  308. status, detail = "crash", "died while asked to quit"
  309. except subprocess.TimeoutExpired:
  310. pass
  311. if terminated:
  312. self.proc.terminate() # (an older build without app.quit)
  313. try:
  314. rc = self.proc.wait(self.a.quit_seconds)
  315. if rc != 0 and not terminated:
  316. status, detail = "quit-crash", f"exit code {rc} on quit"
  317. except subprocess.TimeoutExpired:
  318. status, detail = "exit-hang", f"did not quit within {self.a.quit_seconds} s of app.quit"
  319. if self.a.windows:
  320. self.proc.kill()
  321. else:
  322. os.kill(self.proc.pid, signal.SIGABRT)
  323. try:
  324. self.proc.wait(30)
  325. except subprocess.TimeoutExpired:
  326. self.proc.kill()
  327. rc = self.proc.poll()
  328. reports = sorted(p.name for p in self.out.glob("san.*"))
  329. if self.a.windows: # LYNX's own crash and hang files (its crash guard; no sanitizer there)
  330. reports += sorted(str(p.relative_to(self.out)) for p in self.profile.rglob("crash *.txt"))
  331. if hasattr(self.proc, "close"):
  332. self.proc.close()
  333. result = {"status": status, "detail": detail, "actions": self.count, "rc": rc, "seed": self.a.seed,
  334. "layout": self.a.layout, "project": self.a.project, "sanitizer_reports": reports,
  335. "seconds": round(time.time() - self.t0, 1)}
  336. (self.out / "result.json").write_text(json.dumps(result, indent=1))
  337. if self.a.windows: # (the run's caches, hundreds of MB on the system drive: the logs and crash files stay)
  338. import shutil
  339. shutil.rmtree(self.profile / "cache", ignore_errors=True)
  340. print(json.dumps(result))
  341. return 0 if status == "timeout" and not reports else 1 # (a quit that crashed or hung is a failure too)
  342. def main(self):
  343. self.t0 = time.time()
  344. if not self.start(self.a.project):
  345. if self.alive():
  346. self.proc.kill() # (a start that never answered: ended, its files kept)
  347. return self.finish("start-failed", "no API answer after start")
  348. return self.finish("crash", "no API answer after start")
  349. replay = None
  350. if self.a.replay:
  351. replay = [json.loads(l) for l in open(self.a.replay) if l.strip()]
  352. else:
  353. first = [{"k": "welcome", "choice": "skip"}, {"k": "start_layout", "style": self.a.layout}]
  354. replay_head = first
  355. rng = random.Random(self.a.seed)
  356. end = self.t0 + self.a.minutes * 60
  357. queue = list(replay) if replay is not None else list(replay_head)
  358. while True:
  359. if replay is not None and (not queue or queue[0].get("k") == "quit"):
  360. return self.finish("timeout", "replay finished")
  361. if replay is None and time.time() > end:
  362. return self.finish("timeout")
  363. act = queue.pop(0) if queue else self.plan(rng)
  364. act.setdefault("n", self.count)
  365. act["t"] = round(time.time() - self.t0, 2)
  366. self.log.write(json.dumps(act) + "\n")
  367. self.count += 1
  368. try:
  369. self.run_action(act)
  370. except subprocess.TimeoutExpired:
  371. pass
  372. time.sleep(self.a.delay)
  373. if not self.alive():
  374. return self.finish("crash", f"died after action {act['n']} ({act['k']})")
  375. if self.count % 10 == 0 and not self.responsive():
  376. return self.finish("hang", f"no API answer for {self.a.hang_seconds} s after action {act['n']}")
  377. def parse():
  378. p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  379. p.add_argument("--app", required=True)
  380. p.add_argument("--display", default="")
  381. p.add_argument("--windows", action="store_true", help="LYNX.exe on a hidden desktop, low integrity (tools/winsandbox.py)")
  382. p.add_argument("--api-only", action="store_true", help="Remote Control / --demo operations only, no OS input")
  383. p.add_argument("--out", required=True)
  384. p.add_argument("--seed", type=int, default=1)
  385. p.add_argument("--minutes", type=float, default=5)
  386. p.add_argument("--layout", default="pattern", choices=LAYOUTS)
  387. p.add_argument("--project", default="")
  388. p.add_argument("--projects", nargs="*", default=[], help="files the 'open' action picks from")
  389. p.add_argument("--replay", default="")
  390. p.add_argument("--delay", type=float, default=0.08, help="seconds after each action")
  391. p.add_argument("--hang-seconds", type=float, default=45)
  392. p.add_argument("--start-seconds", type=float, default=240)
  393. p.add_argument("--quit-seconds", type=float, default=120)
  394. p.add_argument("--xdotool", default="xdotool")
  395. a = p.parse_args()
  396. a.api_only = a.api_only or a.windows
  397. if not a.windows and not a.display:
  398. p.error("--display is needed (or --windows)")
  399. return a
  400. if __name__ == "__main__":
  401. sys.exit(Monkey(parse()).main())