scorpiox-bot-plugin-seqthink
←e2e.pypython
374 lines · 15 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport and live-behaviour checks for the plugin_seqthink UI.
3
4Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, with a
5state directory seeded by real --mcp sessions (thoughts, a revision, a branch,
6unicode). Opens the page with Playwright at 1440 / 1024 / 390 CSS pixels in
7BOTH themes and asserts: no console error, no horizontal overflow, the chain
8list is populated from action=chains, selecting a chain renders the timeline
9with revision and branch badges, the progress bar tracks the last thought,
10Show JSON reveals parsable JSON, the bot theme handoff works, and Clear
11(behind confirm) empties the store.
12
13Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays
14offline-only.
15
16 python3 tests/e2e.py # run if Playwright is available
17 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
18"""
19
20import argparse
21import http.server
22import json
23import os
24import subprocess
25import sys
26import tempfile
27import threading
28from urllib.parse import urlparse, parse_qs
29
30ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31BIN = os.path.join(ROOT, "plugin_seqthink")
32VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
33SHOTS = os.path.join(ROOT, "docs")
34
35FAILS = []
36PASSES = []
37
38
39def ok(desc):
40 PASSES.append(desc)
41 print(" ok %s" % desc)
42
43
44def bad(desc, extra=""):
45 FAILS.append(desc)
46 print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else ""))
47
48
49def check(desc, cond, extra=""):
50 ok(desc) if cond else bad(desc, extra)
51
52
53def run_session(state_dir, arg_list):
54 """One --mcp process == one chain (upstream: a server lives as long as its
55 client's connection). Feed every thought of the session on one stdin."""
56 lines = "\n".join(
57 json.dumps({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call",
58 "params": {"name": "sequentialthinking", "arguments": a}})
59 for i, a in enumerate(arg_list)) + "\n"
60 env = dict(os.environ)
61 env["SEQTHINK_STATE_DIR"] = state_dir
62 out = subprocess.run([BIN, "--mcp"], input=lines, capture_output=True,
63 text=True, env=env, timeout=30)
64 return [json.loads(l) for l in out.stdout.splitlines() if l.strip()]
65
66
67def call_tool(state_dir, args):
68 return run_session(state_dir, [args])[0]
69
70
71def click_chain(page, idx):
72 page.evaluate(
73 "(i) => { const li = document.querySelectorAll('#chains li')[i];"
74 " if (li) li.click(); }", idx)
75 page.wait_for_timeout(450)
76
77
78def prepare_fixtures():
79 """Three --mcp sessions: a linear chain with a revision, a branching chain,
80 and a small unicode chain. The viewer reads exactly what the tool wrote."""
81 tmp = tempfile.mkdtemp(prefix="seqthink_e2e_")
82 env = dict(os.environ)
83 env["SEQTHINK_STATE_DIR"] = tmp
84
85 # Session 1: one process, one chain: linear thoughts with a revision.
86 run_session(tmp, [
87 {"thought": "decompose the migration into phases",
88 "nextThoughtNeeded": True, "thoughtNumber": 1, "totalThoughts": 4},
89 {"thought": "phase 2 assumed a shared schema; that was wrong\n"
90 "the two services must keep separate stores",
91 "nextThoughtNeeded": True, "isRevision": True, "revisesThought": 1,
92 "thoughtNumber": 2, "totalThoughts": 4},
93 {"thought": "blue-green it and cut over behind a flag",
94 "nextThoughtNeeded": False, "thoughtNumber": 3, "totalThoughts": 4},
95 ])
96
97 # Session 2: a branch (both thoughts carry branchFromThought + branchId).
98 run_session(tmp, [
99 {"thought": "alternative path: strangler facade",
100 "nextThoughtNeeded": True, "branchFromThought": 1,
101 "branchId": "strangler", "thoughtNumber": 4, "totalThoughts": 5},
102 {"thought": "facade needs a routing layer first",
103 "nextThoughtNeeded": False, "branchFromThought": 1,
104 "branchId": "strangler", "thoughtNumber": 5, "totalThoughts": 5},
105 ])
106
107 # Session 3: a single unicode thought.
108 call_tool(tmp, {"thought": "unicode check: \u00fcn\u00efc\u00f8d\u00e9, \u00e9mojis, "
109 "\u65e5\u672c\u8a9e and \"quotes\"",
110 "nextThoughtNeeded": False, "thoughtNumber": 1,
111 "totalThoughts": 1})
112 return tmp, env
113
114
115class Handler(http.server.BaseHTTPRequestHandler):
116 env = {}
117
118 def _run(self, method):
119 u = urlparse(self.path)
120 qs = u.query
121 env = dict(self.env)
122 env["QUERY_STRING"] = qs
123 env["REQUEST_METHOD"] = method
124 env.pop("BOT_PASSWORD", None)
125 body = b""
126 if method == "POST":
127 n = int(self.headers.get("Content-Length") or 0)
128 body = self.rfile.read(n) if n > 0 else b""
129 env["CONTENT_LENGTH"] = str(n)
130 p = subprocess.Popen([BIN], stdin=subprocess.PIPE,
131 stdout=subprocess.PIPE, env=env)
132 out = p.communicate(body)[0]
133 sep = out.find(b"\r\n\r\n")
134 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
135 payload = out[sep + 4:] if sep >= 0 else out
136 ctype = "text/html; charset=utf-8"
137 status = 200
138 for line in headers.splitlines():
139 low = line.lower()
140 if low.startswith("content-type:"):
141 ctype = line.split(":", 1)[1].strip()
142 elif low.startswith("status:"):
143 try:
144 status = int(line.split(":", 1)[1].strip().split()[0])
145 except Exception:
146 pass
147 self.send_response(status)
148 self.send_header("Content-Type", ctype)
149 self.send_header("Cache-Control", "no-store")
150 self.send_header("Content-Length", str(len(payload)))
151 self.end_headers()
152 self.wfile.write(payload)
153
154 def do_GET(self): # noqa: N802
155 self._run("GET")
156
157 def do_POST(self): # noqa: N802
158 self._run("POST")
159
160 def log_message(self, *_a):
161 pass
162
163
164def serve(env):
165 Handler.env = env
166 httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
167 t = threading.Thread(target=httpd.serve_forever, daemon=True)
168 t.start()
169 return httpd, httpd.server_address[1]
170
171
172def main():
173 ap = argparse.ArgumentParser()
174 ap.add_argument("--strict", action="store_true")
175 ap.add_argument("--no-shots", action="store_true")
176 args = ap.parse_args()
177
178 try:
179 from playwright.sync_api import sync_playwright
180 except Exception:
181 print(" skip e2e (playwright not installed)")
182 return 2 if args.strict else 0
183
184 if not os.path.exists(BIN):
185 print(" FAIL plugin binary missing; run `make` first")
186 return 1
187
188 tmp, env = prepare_fixtures()
189 httpd, port = serve(env)
190 base = "http://127.0.0.1:%d/" % port
191 print("== e2e: %s (state %s) ==" % (base, tmp))
192
193 os.makedirs(SHOTS, exist_ok=True)
194 cleared = False
195 try:
196 with sync_playwright() as p:
197 browser = p.chromium.launch()
198 for w, h in VIEWPORTS:
199 for theme in ("dark", "light"):
200 tag = "%dx%d %s" % (w, h, theme)
201 page = browser.new_page(viewport={"width": w, "height": h},
202 device_scale_factor=1)
203 errors = []
204 page.on("console", lambda m: errors.append(m.text)
205 if m.type == "error" else None)
206 page.on("pageerror", lambda e: errors.append(str(e)))
207 page.goto(base + "?theme=" + theme, wait_until="load")
208 page.wait_for_timeout(700)
209
210 check("%s: no console errors" % tag, not errors, errors[:3])
211
212 attr = page.evaluate(
213 "document.documentElement.getAttribute('data-theme')")
214 check("%s: theme applied" % tag, attr == theme, attr)
215
216 over = page.evaluate(
217 "() => Math.max(document.documentElement.scrollWidth,"
218 " document.body.scrollWidth) - window.innerWidth")
219 check("%s: no horizontal overflow" % tag, over <= 1, over)
220
221 # chain list populated from action=chains
222 n = page.evaluate(
223 "document.querySelectorAll('#chains li').length")
224 check("%s: chain list populated" % tag, n >= 3, n)
225 chips = page.evaluate(
226 "document.getElementById('chipChains').textContent")
227 check("%s: chip counts chains" % tag, "3" in chips, chips)
228
229 # select chain 0 (the linear chain with the revision)
230 click_chain(page, 0)
231 page.wait_for_timeout(500)
232 rows = page.evaluate("document.querySelectorAll('#tl li').length")
233 check("%s: timeline renders the selected chain" % tag,
234 rows == 3, rows)
235 revs = page.evaluate(
236 "document.querySelectorAll('#tl li.rev').length")
237 check("%s: revision row marked" % tag, revs == 1, revs)
238 fin = page.evaluate(
239 "document.querySelectorAll('#tl .badge.fin').length")
240 check("%s: final thought badged" % tag, fin == 1, fin)
241 # the revision (row 2) is the multi-line thought
242 body = page.evaluate(
243 "document.querySelectorAll('#tl .th-body')[1].textContent")
244 check("%s: multi-line thought keeps its newline" % tag,
245 "\n" in body, repr(body[:60]))
246
247 # select the branching chain (index 1)
248 page.evaluate("document.getElementById('backBtn') && "
249 "document.getElementById('backBtn').click()")
250 page.wait_for_timeout(400)
251 click_chain(page, 1)
252 page.wait_for_timeout(500)
253 brs = page.evaluate(
254 "document.querySelectorAll('#tl li.br').length")
255 check("%s: branch rows marked" % tag, brs == 2, brs)
256 btxt = page.evaluate(
257 "document.querySelector('#tl .badge.br').textContent")
258 check("%s: branch badge names the id" % tag,
259 "strangler" in btxt, btxt)
260 prog = page.evaluate(
261 "document.getElementById('dProg').style.width")
262 check("%s: progress bar tracks totalThoughts" % tag,
263 prog in ("80%", "100%"), prog)
264
265 # unicode survives the round trip
266 click_chain(page, 2)
267 page.wait_for_timeout(400)
268 uni = page.evaluate(
269 "document.querySelector('#tl .th-body').textContent")
270 check("%s: unicode thought rendered" % tag,
271 "ünïcødé" in uni and "日本語" in uni, uni[:60])
272
273 # JSON panel
274 page.click("#jsonBtn")
275 page.wait_for_timeout(200)
276 jtxt = page.evaluate("document.getElementById('json').textContent")
277 try:
278 parsed = json.loads(jtxt)
279 good = parsed.get("ok") is True and "thoughts" in parsed
280 except Exception:
281 good = False
282 check("%s: Show JSON reveals parsable chain JSON" % tag, good)
283
284 # theme handoff: the bot posts a new theme, the page follows
285 page.evaluate(
286 "window.postMessage({type:'sx-theme',theme:"
287 "'dark'},'*')")
288 page.wait_for_timeout(200)
289 attr2 = page.evaluate(
290 "document.documentElement.getAttribute('data-theme')")
291 check("%s: sx-theme postMessage followed" % tag,
292 attr2 == "dark", attr2)
293
294 # CSP allows no external scripts
295 nscripts = page.evaluate(
296 "document.querySelectorAll('script[src]').length")
297 check("%s: no external scripts" % tag, nscripts == 0, nscripts)
298
299 if not args.no_shots:
300 # the handoff test above flipped us to dark; restore
301 # the viewport's nominal theme before shooting
302 page.evaluate(
303 "(t) => window.postMessage({type:'sx-theme',"
304 "theme:t},'*')", theme)
305 page.wait_for_timeout(200)
306 # representative state: the revision chain, JSON hidden
307 page.evaluate("document.getElementById('backBtn') && "
308 "document.getElementById('backBtn').click()")
309 page.wait_for_timeout(350)
310 click_chain(page, 0)
311 page.evaluate(
312 """() => { const j =
313 document.getElementById('json');
314 if (j.style.display !== 'none')
315 document.getElementById('jsonBtn').click(); }""")
316 page.wait_for_timeout(350)
317 shot = os.path.join(
318 SHOTS, "ui-%dx%d-%s.png" % (w, h, theme))
319 page.screenshot(path=shot, full_page=False)
320 if os.path.getsize(shot) > 900 * 1024:
321 bad("%s: screenshot under 900 KB" % tag,
322 os.path.getsize(shot))
323 else:
324 ok("%s: screenshot written (%d KB)" %
325 (tag, os.path.getsize(shot) // 1024))
326
327 page.close()
328
329 # Clear empties the store (behind a confirm dialog)
330 page = browser.new_page(viewport={"width": 1440, "height": 900})
331 dialogs = []
332 page.on("dialog", lambda d: (dialogs.append(d.type), d.accept()))
333 page.goto(base, wait_until="load")
334 page.wait_for_timeout(600)
335 page.click("#clearBtn")
336 page.wait_for_timeout(700)
337 check("clear: confirm dialog fired", dialogs == ["confirm"], dialogs)
338 left = page.evaluate("document.querySelectorAll('#chains li').length")
339 check("clear: chains gone", left == 0, left)
340 cleared = True
341 empty = page.evaluate(
342 "document.getElementById('empty').textContent")
343 check("clear: empty state explains the tool",
344 "sequentialthinking" in empty, empty[:80])
345 page.close()
346
347 # a fresh tool call after a clear reappears on Refresh
348 call_tool(tmp, {"thought": "after clear", "nextThoughtNeeded": False,
349 "thoughtNumber": 1, "totalThoughts": 1})
350 page = browser.new_page(viewport={"width": 1440, "height": 900})
351 page.goto(base, wait_until="load")
352 page.wait_for_timeout(600)
353 page.click("#refreshBtn")
354 page.wait_for_timeout(600)
355 n = page.evaluate("document.querySelectorAll('#chains li').length")
356 check("repopulated after clear", n == 1, n)
357 page.close()
358
359 browser.close()
360 finally:
361 httpd.shutdown()
362
363 print("\n== e2e: %d passed, %d failed ==" % (len(PASSES), len(FAILS)))
364 if FAILS:
365 for f in FAILS:
366 print(" - %s" % f)
367 return 1
368 if not cleared:
369 return 1
370 return 0
371
372
373if __name__ == "__main__":
374 sys.exit(main())