#!/usr/bin/env python3 """tests/e2e.py - viewport and live-behaviour checks for the plugin_seqthink UI. Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, with a state directory seeded by real --mcp sessions (thoughts, a revision, a branch, unicode). Opens the page with Playwright at 1440 / 1024 / 390 CSS pixels in BOTH themes and asserts: no console error, no horizontal overflow, the chain list is populated from action=chains, selecting a chain renders the timeline with revision and branch badges, the progress bar tracks the last thought, Show JSON reveals parsable JSON, the bot theme handoff works, and Clear (behind confirm) empties the store. Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays offline-only. 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 subprocess import sys import tempfile import threading from urllib.parse import urlparse, parse_qs ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_seqthink") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] SHOTS = os.path.join(ROOT, "docs") FAILS = [] PASSES = [] def ok(desc): PASSES.append(desc) print(" ok %s" % desc) def bad(desc, extra=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) def check(desc, cond, extra=""): ok(desc) if cond else bad(desc, extra) def run_session(state_dir, arg_list): """One --mcp process == one chain (upstream: a server lives as long as its client's connection). Feed every thought of the session on one stdin.""" lines = "\n".join( json.dumps({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": {"name": "sequentialthinking", "arguments": a}}) for i, a in enumerate(arg_list)) + "\n" env = dict(os.environ) env["SEQTHINK_STATE_DIR"] = state_dir out = subprocess.run([BIN, "--mcp"], input=lines, capture_output=True, text=True, env=env, timeout=30) return [json.loads(l) for l in out.stdout.splitlines() if l.strip()] def call_tool(state_dir, args): return run_session(state_dir, [args])[0] def click_chain(page, idx): page.evaluate( "(i) => { const li = document.querySelectorAll('#chains li')[i];" " if (li) li.click(); }", idx) page.wait_for_timeout(450) def prepare_fixtures(): """Three --mcp sessions: a linear chain with a revision, a branching chain, and a small unicode chain. The viewer reads exactly what the tool wrote.""" tmp = tempfile.mkdtemp(prefix="seqthink_e2e_") env = dict(os.environ) env["SEQTHINK_STATE_DIR"] = tmp # Session 1: one process, one chain: linear thoughts with a revision. run_session(tmp, [ {"thought": "decompose the migration into phases", "nextThoughtNeeded": True, "thoughtNumber": 1, "totalThoughts": 4}, {"thought": "phase 2 assumed a shared schema; that was wrong\n" "the two services must keep separate stores", "nextThoughtNeeded": True, "isRevision": True, "revisesThought": 1, "thoughtNumber": 2, "totalThoughts": 4}, {"thought": "blue-green it and cut over behind a flag", "nextThoughtNeeded": False, "thoughtNumber": 3, "totalThoughts": 4}, ]) # Session 2: a branch (both thoughts carry branchFromThought + branchId). run_session(tmp, [ {"thought": "alternative path: strangler facade", "nextThoughtNeeded": True, "branchFromThought": 1, "branchId": "strangler", "thoughtNumber": 4, "totalThoughts": 5}, {"thought": "facade needs a routing layer first", "nextThoughtNeeded": False, "branchFromThought": 1, "branchId": "strangler", "thoughtNumber": 5, "totalThoughts": 5}, ]) # Session 3: a single unicode thought. call_tool(tmp, {"thought": "unicode check: \u00fcn\u00efc\u00f8d\u00e9, \u00e9mojis, " "\u65e5\u672c\u8a9e and \"quotes\"", "nextThoughtNeeded": False, "thoughtNumber": 1, "totalThoughts": 1}) return tmp, env class Handler(http.server.BaseHTTPRequestHandler): env = {} def _run(self, method): u = urlparse(self.path) qs = u.query env = dict(self.env) env["QUERY_STRING"] = qs env["REQUEST_METHOD"] = method env.pop("BOT_PASSWORD", None) body = b"" if method == "POST": n = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(n) if n > 0 else b"" env["CONTENT_LENGTH"] = str(n) p = subprocess.Popen([BIN], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env) out = p.communicate(body)[0] 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 ctype = "text/html; charset=utf-8" status = 200 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 Exception: pass 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 serve(env): Handler.env = env httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) t = threading.Thread(target=httpd.serve_forever, daemon=True) t.start() return httpd, httpd.server_address[1] def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") ap.add_argument("--no-shots", action="store_true") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except Exception: print(" skip e2e (playwright not installed)") return 2 if args.strict else 0 if not os.path.exists(BIN): print(" FAIL plugin binary missing; run `make` first") return 1 tmp, env = prepare_fixtures() httpd, port = serve(env) base = "http://127.0.0.1:%d/" % port print("== e2e: %s (state %s) ==" % (base, tmp)) os.makedirs(SHOTS, exist_ok=True) cleared = False try: with sync_playwright() as p: browser = p.chromium.launch() for w, h in VIEWPORTS: for theme in ("dark", "light"): tag = "%dx%d %s" % (w, h, theme) page = browser.new_page(viewport={"width": w, "height": h}, device_scale_factor=1) 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))) page.goto(base + "?theme=" + theme, wait_until="load") page.wait_for_timeout(700) check("%s: no console errors" % tag, not errors, errors[:3]) attr = page.evaluate( "document.documentElement.getAttribute('data-theme')") check("%s: theme applied" % tag, attr == theme, attr) over = page.evaluate( "() => Math.max(document.documentElement.scrollWidth," " document.body.scrollWidth) - window.innerWidth") check("%s: no horizontal overflow" % tag, over <= 1, over) # chain list populated from action=chains n = page.evaluate( "document.querySelectorAll('#chains li').length") check("%s: chain list populated" % tag, n >= 3, n) chips = page.evaluate( "document.getElementById('chipChains').textContent") check("%s: chip counts chains" % tag, "3" in chips, chips) # select chain 0 (the linear chain with the revision) click_chain(page, 0) page.wait_for_timeout(500) rows = page.evaluate("document.querySelectorAll('#tl li').length") check("%s: timeline renders the selected chain" % tag, rows == 3, rows) revs = page.evaluate( "document.querySelectorAll('#tl li.rev').length") check("%s: revision row marked" % tag, revs == 1, revs) fin = page.evaluate( "document.querySelectorAll('#tl .badge.fin').length") check("%s: final thought badged" % tag, fin == 1, fin) # the revision (row 2) is the multi-line thought body = page.evaluate( "document.querySelectorAll('#tl .th-body')[1].textContent") check("%s: multi-line thought keeps its newline" % tag, "\n" in body, repr(body[:60])) # select the branching chain (index 1) page.evaluate("document.getElementById('backBtn') && " "document.getElementById('backBtn').click()") page.wait_for_timeout(400) click_chain(page, 1) page.wait_for_timeout(500) brs = page.evaluate( "document.querySelectorAll('#tl li.br').length") check("%s: branch rows marked" % tag, brs == 2, brs) btxt = page.evaluate( "document.querySelector('#tl .badge.br').textContent") check("%s: branch badge names the id" % tag, "strangler" in btxt, btxt) prog = page.evaluate( "document.getElementById('dProg').style.width") check("%s: progress bar tracks totalThoughts" % tag, prog in ("80%", "100%"), prog) # unicode survives the round trip click_chain(page, 2) page.wait_for_timeout(400) uni = page.evaluate( "document.querySelector('#tl .th-body').textContent") check("%s: unicode thought rendered" % tag, "ünïcødé" in uni and "日本語" in uni, uni[:60]) # JSON panel page.click("#jsonBtn") page.wait_for_timeout(200) jtxt = page.evaluate("document.getElementById('json').textContent") try: parsed = json.loads(jtxt) good = parsed.get("ok") is True and "thoughts" in parsed except Exception: good = False check("%s: Show JSON reveals parsable chain JSON" % tag, good) # theme handoff: the bot posts a new theme, the page follows page.evaluate( "window.postMessage({type:'sx-theme',theme:" "'dark'},'*')") page.wait_for_timeout(200) attr2 = page.evaluate( "document.documentElement.getAttribute('data-theme')") check("%s: sx-theme postMessage followed" % tag, attr2 == "dark", attr2) # CSP allows no external scripts nscripts = page.evaluate( "document.querySelectorAll('script[src]').length") check("%s: no external scripts" % tag, nscripts == 0, nscripts) if not args.no_shots: # the handoff test above flipped us to dark; restore # the viewport's nominal theme before shooting page.evaluate( "(t) => window.postMessage({type:'sx-theme'," "theme:t},'*')", theme) page.wait_for_timeout(200) # representative state: the revision chain, JSON hidden page.evaluate("document.getElementById('backBtn') && " "document.getElementById('backBtn').click()") page.wait_for_timeout(350) click_chain(page, 0) page.evaluate( """() => { const j = document.getElementById('json'); if (j.style.display !== 'none') document.getElementById('jsonBtn').click(); }""") page.wait_for_timeout(350) shot = os.path.join( SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) page.screenshot(path=shot, full_page=False) if os.path.getsize(shot) > 900 * 1024: bad("%s: screenshot under 900 KB" % tag, os.path.getsize(shot)) else: ok("%s: screenshot written (%d KB)" % (tag, os.path.getsize(shot) // 1024)) page.close() # Clear empties the store (behind a confirm dialog) page = browser.new_page(viewport={"width": 1440, "height": 900}) dialogs = [] page.on("dialog", lambda d: (dialogs.append(d.type), d.accept())) page.goto(base, wait_until="load") page.wait_for_timeout(600) page.click("#clearBtn") page.wait_for_timeout(700) check("clear: confirm dialog fired", dialogs == ["confirm"], dialogs) left = page.evaluate("document.querySelectorAll('#chains li').length") check("clear: chains gone", left == 0, left) cleared = True empty = page.evaluate( "document.getElementById('empty').textContent") check("clear: empty state explains the tool", "sequentialthinking" in empty, empty[:80]) page.close() # a fresh tool call after a clear reappears on Refresh call_tool(tmp, {"thought": "after clear", "nextThoughtNeeded": False, "thoughtNumber": 1, "totalThoughts": 1}) page = browser.new_page(viewport={"width": 1440, "height": 900}) page.goto(base, wait_until="load") page.wait_for_timeout(600) page.click("#refreshBtn") page.wait_for_timeout(600) n = page.evaluate("document.querySelectorAll('#chains li').length") check("repopulated after clear", n == 1, n) page.close() browser.close() finally: httpd.shutdown() print("\n== e2e: %d passed, %d failed ==" % (len(PASSES), len(FAILS))) if FAILS: for f in FAILS: print(" - %s" % f) return 1 if not cleared: return 1 return 0 if __name__ == "__main__": sys.exit(main())