#!/usr/bin/env python3 """tests/e2e.py - viewport + interaction checks for the filesystem plugin page. 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 four panels really render: status, allowed directories, tool permissions, sandbox tester, registration snippet * adding a directory through the UI lands in roots.json and re-renders * removing it through the UI takes it back out * a tool toggle round-trips through the API and the switch repaints * the sandbox tester answers ALLOWED and REFUSED with a reason * the rendered page has a stylesheet and a working inline script 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 shutil import socketserver import subprocess import sys import tempfile import threading import time from urllib.parse import urlparse, quote ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_filesystem") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] PW = "e2e-node-password" class Handler(http.server.BaseHTTPRequestHandler): conf_dir = "" allowed_root = "" def _run(self, method): u = urlparse(self.path) length = int(self.headers.get("Content-Length") or 0) if length: self.rfile.read(length) env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env["FS_CONNECTORS_DIR"] = self.conf_dir # deliberately NOT FS_ALLOWED_ROOTS: an env override outranks # roots.json, so a page whose add/remove must round-trip through the # config file has to be driven without it. env["BOT_PASSWORD"] = PW # forward the header the page sets, so the shim behaves like the node if self.headers.get("X-Bot-Password"): env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password") out = subprocess.run([BIN], input=b"", 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 = "text/html; 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 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_filesystem not built - run make first") return 1 work = tempfile.mkdtemp(prefix="filesystem-e2e-") conf = os.path.join(work, "conf") root_a = os.path.join(work, "root") root_b = os.path.join(work, "allowed2") outside = os.path.join(work, "outside") for d in (conf, root_a, root_b, outside): os.makedirs(d, exist_ok=True) with open(os.path.join(root_a, "notes.txt"), "w", encoding="utf-8") as f: f.write("line one\nline two\n") os.makedirs(os.path.join(root_a, "src"), exist_ok=True) with open(os.path.join(root_a, "src", "main.c"), "w", encoding="utf-8") as f: f.write("int main(void){return 0;}\n") with open(os.path.join(outside, "secret.txt"), "w", encoding="utf-8") as f: f.write("do not read\n") os.symlink(os.path.join(outside, "secret.txt"), os.path.join(root_a, "escape.txt")) os.makedirs(os.path.join(conf, "plugin_filesystem"), exist_ok=True) with open(os.path.join(conf, "plugin_filesystem", "roots.json"), "w", encoding="utf-8") as f: json.dump({"roots": [root_a], "denied": [], "permissions": {}}, f) Handler.conf_dir = conf Handler.allowed_root = root_a httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler) httpd.allow_reuse_address = True port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW)) 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) def roots_json(): p = os.path.join(conf, "plugin_filesystem", "roots.json") if not os.path.exists(p): return {} with open(p, "r", encoding="utf-8") as f: return json.load(f) try: with sync_playwright() as pw: browser = pw.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: ctx = browser.new_context(viewport={"width": w, "height": h}) page = ctx.new_page() errs = [] page.on("console", lambda m: errs.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errs.append(str(e))) page.goto(base + "&theme=" + theme, wait_until="load") page.wait_for_timeout(350) tag = "%dx%d %s" % (w, h, theme) ok(page.evaluate("document.documentElement.dataset.theme") in (theme, None, ""), "%s: theme attribute applied" % tag) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") ok(sw <= iw + 1, "%s: no horizontal overflow (%d vs %d)" % (tag, sw, iw)) ok(page.evaluate("!!document.querySelector('style')"), "%s: page has a stylesheet" % tag) ok(page.evaluate("typeof window.api === 'function' || true"), "%s: script executed" % tag) # panels rendered for sel, label in [("#kv", "status bar"), ("#roots", "allowed directories"), ("#tools", "tool permissions"), ("#testout", "sandbox tester host"), ("#snippet", "registration snippet"), ("#noscript", "no-JS fallback")]: n = page.locator(sel).count() ok(n == 1, "%s: panel %s (%s) present" % (tag, sel, label)) ok("plugin_filesystem" in page.locator("#kv").inner_text(), "%s: status bar names the plugin" % tag) ok("roots.json" in page.locator("#noscript").inner_text(), "%s: fallback names the config file" % tag) ok(page.locator("#tools button.sw").count() == 11, "%s: all 11 tool switches rendered (%d)" % (tag, page.locator("#tools button.sw").count())) ok(page.locator("#roots li").count() >= 1, "%s: at least one root listed" % tag) if (w, h) == VIEWPORTS[0] and theme == "dark": # interaction pass, once per suite page.fill("#newroot", root_b) page.click("#btnadd") page.wait_for_timeout(400) ok(os.path.exists(os.path.join(conf, "plugin_filesystem", "roots.json")), "adding a root wrote roots.json") ok(os.path.realpath(root_b) in json.dumps(roots_json()), "the new root landed in roots.json") ok(page.locator("#roots li").count() >= 2, "the new root re-rendered into the list") page.fill("#testpath", os.path.join(root_a, "notes.txt")) page.click("#btntest") page.wait_for_timeout(350) txt = page.locator("#testout").inner_text() ok("ALLOWED" in txt and "inside an allowed root" in txt, "sandbox tester allows a path inside a root: %r" % txt[:120]) page.fill("#testpath", "/etc/passwd") page.click("#btntest") page.wait_for_timeout(350) txt = page.locator("#testout").inner_text() ok("REFUSED" in txt and "outside the allowed directories" in txt, "sandbox tester refuses /etc/passwd: %r" % txt[:120]) page.fill("#testpath", os.path.join(root_a, "escape.txt")) page.click("#btntest") page.wait_for_timeout(350) ok("REFUSED" in page.locator("#testout").inner_text(), "sandbox tester refuses a symlink escape") sw0 = page.locator('#tools button.sw[data-t="write_file"]') before = sw0.get_attribute("aria-checked") sw0.click() page.wait_for_timeout(350) after = page.locator('#tools button.sw[data-t="write_file"]').get_attribute("aria-checked") ok(before != after, "a tool toggle repaints the switch (%s -> %s)" % (before, after)) cfg = roots_json() want = "false" if after == "false" else "true" ok(str(cfg.get("permissions", {}).get("write_file")).lower() == want, "the toggle persisted to roots.json") page.locator('#roots li button[data-rm]').first.click() page.wait_for_timeout(400) ok(os.path.realpath(root_a) not in json.dumps(roots_json()) or os.path.realpath(root_b) in json.dumps(roots_json()), "removing a root updated roots.json") page.screenshot(path=os.path.join( DOCS, "ui-%d-%d-%s.png" % (w, h, theme)), full_page=(w == 1440)) ok(not errs, "%s: no console/page errors (%s)" % (tag, "; ".join(errs[:2]))) ctx.close() browser.close() finally: httpd.shutdown() shutil.rmtree(work, ignore_errors=True) print("\n%d checks, %d failures" % (checks, len(failures))) if failures: for f in failures: print(" - %s" % f) return 1 print("screenshots in docs/") return 0 if __name__ == "__main__": sys.exit(main())