#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_memory graph browser. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: * no console error and no page error at any viewport * scrollWidth <= innerWidth (no horizontal overflow) * the entity list renders from a graph seeded through the plugin's own API * the search box filters, the type chips filter, the inspector opens * adding an observation and a relation round-trips into the JSONL store * deleting cascades, and the list shrinks * screenshots land in docs/ for the README Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays dependency-free. python3 tests/e2e.py # run if Playwright is available python3 tests/e2e.py --strict # exit 2 when Playwright is missing """ import argparse import http.server import json import os import socketserver import subprocess import sys import tempfile import threading from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_memory") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] def cgi_call(store, query, method="GET", payload=None): """Run the binary once as a CGI process and return the parsed JSON body.""" env = dict(os.environ) env["MEMORY_FILE_PATH"] = store env["MEMORY_CONNECTOR_DIR"] = os.path.dirname(store) env["QUERY_STRING"] = query env["REQUEST_METHOD"] = method env.pop("BOT_PASSWORD", None) data = json.dumps(payload).encode() if payload is not None else b"" env["CONTENT_LENGTH"] = str(len(data)) out = subprocess.run([BIN], input=data, capture_output=True, env=env, timeout=60).stdout return json.loads(out.split(b"\r\n\r\n", 1)[-1]) class Handler(http.server.BaseHTTPRequestHandler): store = "" def _run(self, method): u = urlparse(self.path) length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env["MEMORY_FILE_PATH"] = self.store env["MEMORY_CONNECTOR_DIR"] = os.path.dirname(self.store) env.pop("BOT_PASSWORD", None) env["CONTENT_LENGTH"] = str(len(body)) out = subprocess.run( [BIN], input=body, capture_output=True, env=env, timeout=60 ).stdout sep = out.find(b"\r\n\r\n") headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" payload = out[sep + 4:] if sep >= 0 else out status = 200 ctype = "application/json; charset=utf-8" for line in headers.splitlines(): low = line.lower() if low.startswith("content-type:"): ctype = line.split(":", 1)[1].strip() elif low.startswith("status:"): try: status = int(line.split(":", 1)[1].strip().split()[0]) except (IndexError, ValueError): status = 200 self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def do_GET(self): # noqa: N802 self._run("GET") def do_POST(self): # noqa: N802 self._run("POST") def log_message(self, *_a): pass def seed(store): """A small connected graph, written through the plugin itself so the JSONL on disk is exactly what a real session would leave behind.""" for name, etype, obs in [ ("Earl Grey", "tea", ["black tea", "bergamot", "ceramic pot at 95C"]), ("Cup", "object", ["stoneware", "handed down from grandad"]), ("Zebra", "animal", ["striped", "lives on the savanna"]), ]: cgi_call(store, "action=add_entity", "POST", {"name": name, "entityType": etype, "observations": obs}) cgi_call(store, "action=add_relation", "POST", {"from": "Earl Grey", "to": "Cup", "relationType": "is served in"}) cgi_call(store, "action=add_relation", "POST", {"from": "Zebra", "to": "Earl Grey", "relationType": "shares a stripe with"}) def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true", help="exit 2 when Playwright is not installed") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except Exception: print("playwright not installed - skipping e2e (offline suite is unaffected)") return 2 if args.strict else 0 if not os.path.exists(BIN): print("plugin_memory not built - run make first") return 1 work = tempfile.mkdtemp(prefix="memory-e2e-") store = os.path.join(work, "memory.jsonl") seed(store) Handler.store = store httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/" % port os.makedirs(DOCS, exist_ok=True) failures = [] checks = 0 def ok(cond, label): nonlocal checks checks += 1 if not cond: failures.append(label) print(" FAIL %s" % label) try: with sync_playwright() as pw: browser = pw.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: page = browser.new_page(viewport={"width": w, "height": h}, color_scheme=theme) errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) # deleting an entity asks for confirmation; auto-accept so # the delete assertion below reaches the server instead of # hanging on a dialog Playwright dismisses silently. page.on("dialog", lambda dialog: dialog.accept()) # each viewport/theme pair gets a fresh graph: the checks # below mutate it (add observation, add relation, delete # entity), so a shared store would leave the next pair with # two entities and fail a count that is really correct. for junk in os.listdir(work): os.unlink(os.path.join(work, junk)) seed(store) page.goto(base + "?theme=%s" % theme, wait_until="load") page.wait_for_selector(".item", timeout=8000) # list rendered from the three seeded entities ok(page.locator(".item").count() == 3, "list has 3 entities @%dx%d %s" % (w, h, theme)) ok("3 entities" in page.inner_text("#tally"), "tally label @%dx%d %s" % (w, h, theme)) # type chips: all + the three distinct types ok(page.locator("#chips .chip").count() == 4, "four type chips @%dx%d %s" % (w, h, theme)) # no horizontal overflow sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" % (sw, iw, w, h, theme)) # the page never reached out beyond the shim ok(page.evaluate( "performance.getEntriesByType('resource')" ".filter(r=>!r.name.startsWith(location.origin)).length" ) == 0, "zero external requests @%dx%d %s" % (w, h, theme)) # search filters the list down to one page.fill("#q", "bergamot") page.wait_for_function( "document.querySelectorAll('.item').length===1", timeout=8000) ok("Earl Grey" in page.inner_text("#list"), "search by observation @%dx%d %s" % (w, h, theme)) # a type chip filters to its own type page.fill("#q", "") page.locator("#chips .chip", has_text="animal").first.click() page.wait_for_function( "document.querySelectorAll('.item').length===1", timeout=8000) ok("Zebra" in page.inner_text("#list"), "chip filter @%dx%d %s" % (w, h, theme)) page.locator("#chips .chip", has_text="all").first.click() page.wait_for_function( "document.querySelectorAll('.item').length===3", timeout=8000) # open the inspector and read both relation directions page.locator(".item", has_text="Earl Grey").first.click() page.wait_for_selector("#detail .card", timeout=8000) # card headers are uppercased by the stylesheet, so compare # lower-cased rendered text rather than the source case. detail = page.inner_text("#detail").lower() ok("observations" in detail, "inspector shows observations @%dx%d %s" % (w, h, theme)) ok("relations out" in detail and "relations in" in detail, "inspector shows both relation directions @%dx%d %s" % (w, h, theme)) ok(page.locator("#detail .obs li").count() == 3, "three observation rows @%dx%d %s" % (w, h, theme)) ok(page.locator("#detail .rel").count() == 2, "two relation rows @%dx%d %s" % (w, h, theme)) # add an observation, it lands in the graph and on disk page.fill("#newObs", "best poured at 4 minutes") page.click("#addObs") page.wait_for_function( "document.querySelectorAll('#detail .obs li').length===4", timeout=8000) ok("best poured at 4 minutes" in open(store, encoding="utf-8").read(), "observation persisted to JSONL @%dx%d %s" % (w, h, theme)) # link to another entity through the select + type box page.select_option("#relTo", "Zebra") page.fill("#relType", "tastes like") page.click("#addRel") page.wait_for_function( "document.querySelectorAll('#detail .rel').length===3", timeout=8000) ok("tastes like" in open(store, encoding="utf-8").read(), "relation persisted to JSONL @%dx%d %s" % (w, h, theme)) # status line reports something on every interaction ok(page.inner_text("#status").strip() != "", "status line not blank @%dx%d %s" % (w, h, theme)) # delete the entity, the list shrinks to two page.click("#detail [data-dele]") page.wait_for_function( "document.querySelectorAll('.item').length===2", timeout=8000) rest = open(store, encoding="utf-8").read() ok("Earl Grey" not in rest, "delete removed the entity @%dx%d %s" % (w, h, theme)) ok("Cup" in rest, "delete kept the untouched entity @%dx%d %s" % (w, h, theme)) ok(not errors, "no console errors @%dx%d %s (%s)" % (w, h, theme, "; ".join(errors[:3]))) # The README shots show a graph at full strength, so put a # fresh one back after the destructive checks above. The # narrow shot is the list (its own pane at 390 px), the wide # shots are the inspector with observations and relations. for junk in os.listdir(work): os.unlink(os.path.join(work, junk)) seed(store) page.goto(base + "?theme=%s" % theme, wait_until="load") page.wait_for_selector(".item", timeout=8000) if w >= 1024: page.locator(".item", has_text="Earl Grey").first.click() page.wait_for_selector("#detail .obs li", timeout=8000) page.screenshot(path=os.path.join( DOCS, "ui-%d-%s.png" % (w, theme)), full_page=True) page.close() browser.close() finally: httpd.shutdown() print("\ne2e: %d checks, %d failed" % (checks, len(failures))) if failures: for f in failures: print(" - %s" % f) return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())