test: playwright viewport suite + fix post-2038 expiry overflow
expires_in_sec was an int, so any session expiry past 2038 came out as -1987015054s while expired stayed false - the UI showed a valid session as having a negative remaining life. Now long long end to end, with a pinned regression. tests/e2e.py drives the real page at 1440/1024/390 dark+light (50 checks): pill, session card, project card, the start/cancel flow, the invalid-code error, embed mode, overflow and console errors. docs/ gets the screenshots.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-12 14:10:48
Commit205cef62
Parents2260b881
Changed files
src/plugin_antigravity_login.c+6−3■■■■■
src/ui.html+3−2■■■■■
src/ui_html.h+3−2■■■■■
tests/e2e.py+264−0■■■■■
tests/run.sh+10−0■■■■■
12 files+286−7
Diff
docs/ui-1024-dark.png+0−0■
11new file mode 100644
index 0000000..068944a
binary image
Binary image file
docs/ui-1024-light.png+0−0■
11new file mode 100644
index 0000000..e6f599c
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
11new file mode 100644
index 0000000..bb05bb9
binary image
Binary image file
docs/ui-1440-light.png+0−0■
11new file mode 100644
index 0000000..b5a97d7
binary image
Binary image file
docs/ui-390-dark.png+0−0■
11new file mode 100644
index 0000000..b75dba0
binary image
Binary image file
docs/ui-390-light.png+0−0■
11new file mode 100644
index 0000000..35677d5
binary image
Binary image file
docs/ui-flow-dark.png+0−0■
11new file mode 100644
index 0000000..21dc79d
binary image
Binary image file
src/plugin_antigravity_login.c+6−3■■■■■
index d1ebea0..81668fb 100644
--- a/src/plugin_antigravity_login.c
+++ b/src/plugin_antigravity_login.c
@@ -728,7 +728,10 @@ typedef struct {
728728 char path[PATH_SZ];
729729 char profile[PROJ_SZ];
730730 long long expires_at; /* unix seconds, 0 = unknown */
731- int expires_in_sec; /* negative when expired, 0 when unknown */
731+ /* long long, not int: expires_at - now overflows a 32-bit int for any
732+ * expiry past 2038, which turned a valid session into "expires in
733+ * -1987015054s" in the UI while expired stayed false. */
734+ long long expires_in_sec; /* negative when expired, 0 when unknown */
732735 } status_t;
733736
734737 /* Pull email / refresh_token presence out of the accounts array.
@@ -904,7 +907,7 @@ static void collect_status(status_t *st)
904907 }
905908
906909 if (st->expires_at > 0) {
907- st->expires_in_sec = (int)(st->expires_at - now);
910+ st->expires_in_sec = st->expires_at - now;
908911 st->expired = st->expires_at <= now;
909912 }
910913 if (!st->logged_in) {
@@ -927,7 +930,7 @@ static void emit_status(buf_t *b, const status_t *st)
927930 buf_addf(b, ",\"profile\":");
928931 buf_json(b, st->profile);
929932 buf_addf(b, ",\"expires_at\":%lld", st->expires_at);
930- buf_addf(b, ",\"expires_in_sec\":%d", st->expires_in_sec);
933+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
931934 buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
932935 buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
933936 buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
src/ui.html+3−2■■■■■
index d310cf7..7d115ae 100644
--- a/src/ui.html
+++ b/src/ui.html
@@ -186,12 +186,13 @@ function kv(el,rows){
186186 });
187187 }
188188 function fmtExpiry(sec){
189- if(!sec&&sec!==0)return '-';
189+ if(typeof sec!=='number')return '-';
190190 if(sec<=0)return 'expired';
191191 if(sec<90)return sec+'s';
192192 if(sec<5400)return Math.round(sec/60)+' min';
193193 if(sec<172800)return Math.round(sec/3600)+' h';
194- return Math.round(sec/86400)+' d';
194+ if(sec<63072000)return Math.round(sec/86400)+' d';
195+ return Math.round(sec/31536000)+' yr';
195196 }
196197 function setPill(st){
197198 var p=$('pill'),t=$('pillText');
src/ui_html.h+3−2■■■■■
index 1b55812..3adb348 100644
--- a/src/ui_html.h
+++ b/src/ui_html.h
@@ -191,12 +191,13 @@ static const char *UI_HTML =
191191 " });\n"
192192 "}\n"
193193 "function fmtExpiry(sec){\n"
194- " if(!sec&&sec!==0)return '-';\n"
194+ " if(typeof sec!=='number')return '-';\n"
195195 " if(sec<=0)return 'expired';\n"
196196 " if(sec<90)return sec+'s';\n"
197197 " if(sec<5400)return Math.round(sec/60)+' min';\n"
198198 " if(sec<172800)return Math.round(sec/3600)+' h';\n"
199- " return Math.round(sec/86400)+' d';\n"
199+ " if(sec<63072000)return Math.round(sec/86400)+' d';\n"
200+ " return Math.round(sec/31536000)+' yr';\n"
200201 "}\n"
201202 "function setPill(st){\n"
202203 " var p=$('pill'),t=$('pillText');\n"
tests/e2e.py+264−0■■■■■
11new file mode 100644
index 0000000..9513246
--- /dev/null
+++ b/tests/e2e.py
@@ -0,0 +1,264 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport checks for the plugin_antigravity_login page.
3+
4+Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it
5+with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6+
7+ * no console error and no page error at any viewport
8+ * scrollWidth <= innerWidth (no horizontal overflow)
9+ * the status pill, the session card and the project card render
10+ * "Start Google Login" drives the flow: the auth link appears, the paste box
11+ is shown, and Cancel returns to step one
12+ * a bad code shows the inline error instead of a silent nothing
13+ * embed mode hides the theme toggle
14+ * screenshots land in docs/ for the README
15+
16+The login and token CLIs are replaced by tests/mock_login.sh and
17+tests/mock_token.sh, so nothing here touches Google and no network is used.
18+
19+Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
20+dependency-free.
21+
22+ python3 tests/e2e.py # run if Playwright is available
23+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
24+"""
25+
26+import argparse
27+import http.server
28+import json
29+import os
30+import shutil
31+import socketserver
32+import subprocess
33+import sys
34+import tempfile
35+import threading
36+from urllib.parse import urlparse
37+
38+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39+BIN = os.path.join(ROOT, "plugin_antigravity_login")
40+DOCS = os.path.join(ROOT, "docs")
41+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
42+THEMES = ["dark", "light"]
43+
44+
45+class Handler(http.server.BaseHTTPRequestHandler):
46+ env_extra = {}
47+
48+ def _run(self, method):
49+ u = urlparse(self.path)
50+ length = int(self.headers.get("Content-Length") or 0)
51+ body = self.rfile.read(length) if length else b""
52+ env = dict(os.environ)
53+ env["QUERY_STRING"] = u.query
54+ env["REQUEST_METHOD"] = method
55+ env.pop("BOT_PASSWORD", None)
56+ env["CONTENT_LENGTH"] = str(len(body))
57+ env.update(self.env_extra)
58+ out = subprocess.run([BIN], input=body, capture_output=True,
59+ env=env, timeout=60).stdout
60+ sep = out.find(b"\r\n\r\n")
61+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
62+ payload = out[sep + 4:] if sep >= 0 else out
63+ status = 200
64+ ctype = "application/json; charset=utf-8"
65+ for line in headers.splitlines():
66+ low = line.lower()
67+ if low.startswith("content-type:"):
68+ ctype = line.split(":", 1)[1].strip()
69+ elif low.startswith("status:"):
70+ try:
71+ status = int(line.split(":", 1)[1].strip().split()[0])
72+ except (IndexError, ValueError):
73+ status = 200
74+ self.send_response(status)
75+ self.send_header("Content-Type", ctype)
76+ self.send_header("Cache-Control", "no-store")
77+ self.send_header("Content-Length", str(len(payload)))
78+ self.end_headers()
79+ self.wfile.write(payload)
80+
81+ def do_GET(self): # noqa: N802
82+ self._run("GET")
83+
84+ def do_POST(self): # noqa: N802
85+ self._run("POST")
86+
87+ def log_message(self, *_a):
88+ pass
89+
90+
91+def seed(work):
92+ """A signed-in fixture written the way the login CLI writes it."""
93+ acct = os.path.join(work, "antigravity_accounts.json")
94+ with open(acct, "w", encoding="utf-8") as f:
95+ f.write('[{"email":"pico@example.com","refresh_token":"1//mock-refresh"}]\n')
96+ with open(os.path.join(work, "selected_account.txt"), "w", encoding="utf-8") as f:
97+ f.write("pico@example.com\n")
98+ envdir = os.path.join(work, "scorpiox-env")
99+ os.makedirs(envdir, exist_ok=True)
100+ with open(os.path.join(envdir, "antigravity.txt"), "w", encoding="utf-8") as f:
101+ f.write("PROVIDER=google_gemini\n"
102+ "GOOGLE_ACCOUNT=pico@example.com\n"
103+ "GOOGLE_PROJECT_ID=proj-mock-42\n")
104+ return acct
105+
106+
107+def main():
108+ ap = argparse.ArgumentParser()
109+ ap.add_argument("--strict", action="store_true",
110+ help="exit 2 when Playwright is not installed")
111+ args = ap.parse_args()
112+
113+ try:
114+ from playwright.sync_api import sync_playwright
115+ except Exception:
116+ print("playwright not installed - skipping e2e (offline suite is unaffected)")
117+ return 2 if args.strict else 0
118+
119+ if not os.path.exists(BIN):
120+ print("plugin_antigravity_login not built - run make first")
121+ return 1
122+
123+ work = tempfile.mkdtemp(prefix="agylogin-e2e-")
124+ acct = seed(work)
125+ Handler.env_extra = {
126+ "ANTIGRAVITY_CREDS_PATH": acct,
127+ "ANTIGRAVITY_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"),
128+ "ANTIGRAVITY_TOKEN_BIN": os.path.join(ROOT, "tests", "mock_token.sh"),
129+ "ANTIGRAVITY_PENDING_PATH": os.path.join(work, "pending.json"),
130+ "MOCK_WRITE_DIR": work,
131+ "MOCK_STATUS_JSON":
132+ '{"ok":true,"provider":"antigravity","logged_in":true,'
133+ '"has_refresh":true,"pending":false,"identity":"pico@example.com",'
134+ '"expires_at":4102444800000,"expired":false}',
135+ }
136+
137+ httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
138+ port = httpd.server_address[1]
139+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
140+ base = "http://127.0.0.1:%d/" % port
141+
142+ os.makedirs(DOCS, exist_ok=True)
143+ failures = []
144+ checks = 0
145+
146+ def ok(cond, label):
147+ nonlocal checks
148+ checks += 1
149+ if not cond:
150+ failures.append(label)
151+ print(" FAIL %s" % label)
152+
153+ try:
154+ with sync_playwright() as pw:
155+ browser = pw.chromium.launch()
156+ for w, h in VIEWPORTS:
157+ for theme in THEMES:
158+ page = browser.new_page(viewport={"width": w, "height": h},
159+ color_scheme=theme)
160+ errors = []
161+ page.on("console", lambda m: errors.append(m.text)
162+ if m.type == "error" else None)
163+ page.on("pageerror", lambda e: errors.append(str(e)))
164+
165+ page.goto(base + "?theme=%s" % theme, wait_until="load")
166+ page.wait_for_function(
167+ "document.getElementById('pillText').textContent"
168+ " !== 'Checking'", timeout=8000)
169+
170+ ok(page.text_content("#pillText") == "Connected",
171+ "status pill says Connected @%dx%d %s" % (w, h, theme))
172+ ok("pico@example.com" in page.text_content("#sub"),
173+ "account shown in the header @%dx%d %s" % (w, h, theme))
174+ ok("pico@example.com" in page.text_content("#session"),
175+ "session card lists the account @%dx%d %s" % (w, h, theme))
176+ ok("proj-mock-42" in page.text_content("#project"),
177+ "companion project card @%dx%d %s" % (w, h, theme))
178+
179+ sw = page.evaluate("document.documentElement.scrollWidth")
180+ iw = page.evaluate("window.innerWidth")
181+ ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
182+ % (sw, iw, w, h, theme))
183+
184+ # the theme actually applied (the CSS variables resolved)
185+ bg = page.evaluate(
186+ "getComputedStyle(document.body).backgroundColor")
187+ if theme == "light":
188+ ok(bg.startswith("rgb(245") or bg.startswith("rgb(255"),
189+ "light theme background @%dx%d" % (w, h))
190+ else:
191+ ok(bg.startswith("rgb(0"), "dark theme background @%dx%d"
192+ % (w, h))
193+
194+ ok(not errors, "no console error @%dx%d %s (%s)"
195+ % (w, h, theme, "; ".join(errors[:2])))
196+
197+ shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
198+ page.screenshot(path=shot)
199+ page.close()
200+
201+ # the login flow, at one viewport
202+ page = browser.new_page(viewport={"width": 1024, "height": 768})
203+ errors = []
204+ page.on("pageerror", lambda e: errors.append(str(e)))
205+ page.goto(base + "?theme=dark", wait_until="load")
206+ page.wait_for_function(
207+ "document.getElementById('pillText').textContent !== 'Checking'",
208+ timeout=8000)
209+
210+ page.click("#btnStart")
211+ page.wait_for_selector("#step2.on", timeout=8000)
212+ url = page.text_content("#authUrl")
213+ ok(url.startswith("https://accounts.google.com/"),
214+ "start produced an authorization URL")
215+ ok("code_challenge=" in url, "the URL carries the PKCE challenge")
216+ ok(page.get_attribute("#linkOpen", "href").startswith(
217+ "https://accounts.google.com/"), "the open link is wired")
218+
219+ page.click("#btnCancel")
220+ page.wait_for_selector("#step1.on", timeout=8000)
221+ ok(not page.is_visible("#step2.on"), "cancel returns to step one")
222+
223+ # a rejected exchange shows the inline error, not silence
224+ page.click("#btnStart")
225+ page.wait_for_selector("#step2.on", timeout=8000)
226+ page.fill("#codeInput", "not a code ' with quote")
227+ page.click("#btnFinish")
228+ page.wait_for_function(
229+ "document.getElementById('loginNote').classList.contains('show')",
230+ timeout=8000)
231+ note = page.text_content("#loginNote")
232+ ok("code" in note.lower(), "an invalid code explains itself (%r)" % note[:60])
233+ ok(not errors, "no page error during the flow (%s)"
234+ % "; ".join(errors[:2]))
235+ page.screenshot(path=os.path.join(DOCS, "ui-flow-dark.png"))
236+ page.close()
237+
238+ # embed mode hides the theme toggle
239+ page = browser.new_page(viewport={"width": 1024, "height": 768})
240+ page.goto(base + "?embed=1&theme=dark", wait_until="load")
241+ page.wait_for_function(
242+ "document.getElementById('pillText').textContent !== 'Checking'",
243+ timeout=8000)
244+ ok(not page.is_visible("#themeToggle"), "embed hides the theme toggle")
245+ ok(page.evaluate(
246+ "document.documentElement.classList.contains('embedded')"),
247+ "embed marks html.embedded")
248+ page.close()
249+ browser.close()
250+ finally:
251+ httpd.shutdown()
252+ shutil.rmtree(work, ignore_errors=True)
253+
254+ print("\n%d checks, %d failure(s)" % (checks, len(failures)))
255+ if failures:
256+ for f in failures:
257+ print(" - %s" % f)
258+ return 1
259+ print("RESULT: OK")
260+ return 0
261+
262+
263+if __name__ == "__main__":
264+ sys.exit(main())
tests/run.sh+10−0■■■■■
index e31a831..cae01d5 100755
--- a/tests/run.sh
+++ b/tests/run.sh
@@ -195,6 +195,16 @@ EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
195195 json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \
196196 "d['expired'] is True and d['expires_in_sec'] < 0"
197197
198+# a far-future expiry must not overflow: expires_in_sec used to be an int, so
199+# any expiry past 2038 came out as -1987015054 while expired stayed false.
200+FAR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
201+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true}' \
202+ api "action=status")
203+json_ok "a post-2038 expiry reports a positive remaining time" "$FAR" \
204+ "d['expires_in_sec'] > 0 and d['expired'] is False"
205+json_ok "a post-2038 expiry normalises ms to seconds" "$FAR" \
206+ "d['expires_at'] == 4102444800"
207+
198208 # pending marker file present -> pending true even without CLI help
199209 : > "$FIX/pending/antigravity-default.json"
200210 PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
201211
docs/ui-1024-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..068944aindex 0000000..068944a
binary image
Binary image file
docs/ui-1024-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..e6f599cindex 0000000..e6f599c
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..bb05bb9index 0000000..bb05bb9
binary image
Binary image file
docs/ui-1440-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..b5a97d7index 0000000..b5a97d7
binary image
Binary image file
docs/ui-390-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..b75dba0index 0000000..b75dba0
binary image
Binary image file
docs/ui-390-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..35677d5index 0000000..35677d5
binary image
Binary image file
docs/ui-flow-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..21dc79dindex 0000000..21dc79d
binary image
Binary image file
src/plugin_antigravity_login.c+6−3■■■■■
index d1ebea0..81668fb 100644index d1ebea0..81668fb 100644
--- a/src/plugin_antigravity_login.c--- a/src/plugin_antigravity_login.c
+++ b/src/plugin_antigravity_login.c+++ b/src/plugin_antigravity_login.c
@@ -728,7 +728,10 @@ typedef struct {@@ -728,7 +728,10 @@ typedef struct {
728 char path[PATH_SZ];728 char path[PATH_SZ];
729 char profile[PROJ_SZ];729 char profile[PROJ_SZ];
730 long long expires_at; /* unix seconds, 0 = unknown */730 long long expires_at; /* unix seconds, 0 = unknown */
731- int expires_in_sec; /* negative when expired, 0 when unknown */731+ /* long long, not int: expires_at - now overflows a 32-bit int for any
732+ * expiry past 2038, which turned a valid session into "expires in
733+ * -1987015054s" in the UI while expired stayed false. */
734+ long long expires_in_sec; /* negative when expired, 0 when unknown */
732 } status_t;735 } status_t;
733 736
734 /* Pull email / refresh_token presence out of the accounts array.737 /* Pull email / refresh_token presence out of the accounts array.
@@ -904,7 +907,7 @@ static void collect_status(status_t *st)@@ -904,7 +907,7 @@ static void collect_status(status_t *st)
904 }907 }
905 908
906 if (st->expires_at > 0) {909 if (st->expires_at > 0) {
907- st->expires_in_sec = (int)(st->expires_at - now);910+ st->expires_in_sec = st->expires_at - now;
908 st->expired = st->expires_at <= now;911 st->expired = st->expires_at <= now;
909 }912 }
910 if (!st->logged_in) {913 if (!st->logged_in) {
@@ -927,7 +930,7 @@ static void emit_status(buf_t *b, const status_t *st)@@ -927,7 +930,7 @@ static void emit_status(buf_t *b, const status_t *st)
927 buf_addf(b, ",\"profile\":");930 buf_addf(b, ",\"profile\":");
928 buf_json(b, st->profile);931 buf_json(b, st->profile);
929 buf_addf(b, ",\"expires_at\":%lld", st->expires_at);932 buf_addf(b, ",\"expires_at\":%lld", st->expires_at);
930- buf_addf(b, ",\"expires_in_sec\":%d", st->expires_in_sec);933+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
931 buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");934 buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
932 buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");935 buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
933 buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");936 buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
src/ui.html+3−2■■■■■
index d310cf7..7d115ae 100644index d310cf7..7d115ae 100644
--- a/src/ui.html--- a/src/ui.html
+++ b/src/ui.html+++ b/src/ui.html
@@ -186,12 +186,13 @@ function kv(el,rows){@@ -186,12 +186,13 @@ function kv(el,rows){
186 });186 });
187 }187 }
188 function fmtExpiry(sec){188 function fmtExpiry(sec){
189- if(!sec&&sec!==0)return '-';189+ if(typeof sec!=='number')return '-';
190 if(sec<=0)return 'expired';190 if(sec<=0)return 'expired';
191 if(sec<90)return sec+'s';191 if(sec<90)return sec+'s';
192 if(sec<5400)return Math.round(sec/60)+' min';192 if(sec<5400)return Math.round(sec/60)+' min';
193 if(sec<172800)return Math.round(sec/3600)+' h';193 if(sec<172800)return Math.round(sec/3600)+' h';
194- return Math.round(sec/86400)+' d';194+ if(sec<63072000)return Math.round(sec/86400)+' d';
195+ return Math.round(sec/31536000)+' yr';
195 }196 }
196 function setPill(st){197 function setPill(st){
197 var p=$('pill'),t=$('pillText');198 var p=$('pill'),t=$('pillText');
src/ui_html.h+3−2■■■■■
index 1b55812..3adb348 100644index 1b55812..3adb348 100644
--- a/src/ui_html.h--- a/src/ui_html.h
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -191,12 +191,13 @@ static const char *UI_HTML =@@ -191,12 +191,13 @@ static const char *UI_HTML =
191 " });\n"191 " });\n"
192 "}\n"192 "}\n"
193 "function fmtExpiry(sec){\n"193 "function fmtExpiry(sec){\n"
194- " if(!sec&&sec!==0)return '-';\n"194+ " if(typeof sec!=='number')return '-';\n"
195 " if(sec<=0)return 'expired';\n"195 " if(sec<=0)return 'expired';\n"
196 " if(sec<90)return sec+'s';\n"196 " if(sec<90)return sec+'s';\n"
197 " if(sec<5400)return Math.round(sec/60)+' min';\n"197 " if(sec<5400)return Math.round(sec/60)+' min';\n"
198 " if(sec<172800)return Math.round(sec/3600)+' h';\n"198 " if(sec<172800)return Math.round(sec/3600)+' h';\n"
199- " return Math.round(sec/86400)+' d';\n"199+ " if(sec<63072000)return Math.round(sec/86400)+' d';\n"
200+ " return Math.round(sec/31536000)+' yr';\n"
200 "}\n"201 "}\n"
201 "function setPill(st){\n"202 "function setPill(st){\n"
202 " var p=$('pill'),t=$('pillText');\n"203 " var p=$('pill'),t=$('pillText');\n"
tests/e2e.py+264−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..9513246index 0000000..9513246
--- /dev/null--- /dev/null
+++ b/tests/e2e.py+++ b/tests/e2e.py
@@ -0,0 +1,264 @@@@ -0,0 +1,264 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport checks for the plugin_antigravity_login page.
3+
4+Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it
5+with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6+
7+ * no console error and no page error at any viewport
8+ * scrollWidth <= innerWidth (no horizontal overflow)
9+ * the status pill, the session card and the project card render
10+ * "Start Google Login" drives the flow: the auth link appears, the paste box
11+ is shown, and Cancel returns to step one
12+ * a bad code shows the inline error instead of a silent nothing
13+ * embed mode hides the theme toggle
14+ * screenshots land in docs/ for the README
15+
16+The login and token CLIs are replaced by tests/mock_login.sh and
17+tests/mock_token.sh, so nothing here touches Google and no network is used.
18+
19+Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
20+dependency-free.
21+
22+ python3 tests/e2e.py # run if Playwright is available
23+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
24+"""
25+
26+import argparse
27+import http.server
28+import json
29+import os
30+import shutil
31+import socketserver
32+import subprocess
33+import sys
34+import tempfile
35+import threading
36+from urllib.parse import urlparse
37+
38+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39+BIN = os.path.join(ROOT, "plugin_antigravity_login")
40+DOCS = os.path.join(ROOT, "docs")
41+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
42+THEMES = ["dark", "light"]
43+
44+
45+class Handler(http.server.BaseHTTPRequestHandler):
46+ env_extra = {}
47+
48+ def _run(self, method):
49+ u = urlparse(self.path)
50+ length = int(self.headers.get("Content-Length") or 0)
51+ body = self.rfile.read(length) if length else b""
52+ env = dict(os.environ)
53+ env["QUERY_STRING"] = u.query
54+ env["REQUEST_METHOD"] = method
55+ env.pop("BOT_PASSWORD", None)
56+ env["CONTENT_LENGTH"] = str(len(body))
57+ env.update(self.env_extra)
58+ out = subprocess.run([BIN], input=body, capture_output=True,
59+ env=env, timeout=60).stdout
60+ sep = out.find(b"\r\n\r\n")
61+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
62+ payload = out[sep + 4:] if sep >= 0 else out
63+ status = 200
64+ ctype = "application/json; charset=utf-8"
65+ for line in headers.splitlines():
66+ low = line.lower()
67+ if low.startswith("content-type:"):
68+ ctype = line.split(":", 1)[1].strip()
69+ elif low.startswith("status:"):
70+ try:
71+ status = int(line.split(":", 1)[1].strip().split()[0])
72+ except (IndexError, ValueError):
73+ status = 200
74+ self.send_response(status)
75+ self.send_header("Content-Type", ctype)
76+ self.send_header("Cache-Control", "no-store")
77+ self.send_header("Content-Length", str(len(payload)))
78+ self.end_headers()
79+ self.wfile.write(payload)
80+
81+ def do_GET(self): # noqa: N802
82+ self._run("GET")
83+
84+ def do_POST(self): # noqa: N802
85+ self._run("POST")
86+
87+ def log_message(self, *_a):
88+ pass
89+
90+
91+def seed(work):
92+ """A signed-in fixture written the way the login CLI writes it."""
93+ acct = os.path.join(work, "antigravity_accounts.json")
94+ with open(acct, "w", encoding="utf-8") as f:
95+ f.write('[{"email":"pico@example.com","refresh_token":"1//mock-refresh"}]\n')
96+ with open(os.path.join(work, "selected_account.txt"), "w", encoding="utf-8") as f:
97+ f.write("pico@example.com\n")
98+ envdir = os.path.join(work, "scorpiox-env")
99+ os.makedirs(envdir, exist_ok=True)
100+ with open(os.path.join(envdir, "antigravity.txt"), "w", encoding="utf-8") as f:
101+ f.write("PROVIDER=google_gemini\n"
102+ "GOOGLE_ACCOUNT=pico@example.com\n"
103+ "GOOGLE_PROJECT_ID=proj-mock-42\n")
104+ return acct
105+
106+
107+def main():
108+ ap = argparse.ArgumentParser()
109+ ap.add_argument("--strict", action="store_true",
110+ help="exit 2 when Playwright is not installed")
111+ args = ap.parse_args()
112+
113+ try:
114+ from playwright.sync_api import sync_playwright
115+ except Exception:
116+ print("playwright not installed - skipping e2e (offline suite is unaffected)")
117+ return 2 if args.strict else 0
118+
119+ if not os.path.exists(BIN):
120+ print("plugin_antigravity_login not built - run make first")
121+ return 1
122+
123+ work = tempfile.mkdtemp(prefix="agylogin-e2e-")
124+ acct = seed(work)
125+ Handler.env_extra = {
126+ "ANTIGRAVITY_CREDS_PATH": acct,
127+ "ANTIGRAVITY_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"),
128+ "ANTIGRAVITY_TOKEN_BIN": os.path.join(ROOT, "tests", "mock_token.sh"),
129+ "ANTIGRAVITY_PENDING_PATH": os.path.join(work, "pending.json"),
130+ "MOCK_WRITE_DIR": work,
131+ "MOCK_STATUS_JSON":
132+ '{"ok":true,"provider":"antigravity","logged_in":true,'
133+ '"has_refresh":true,"pending":false,"identity":"pico@example.com",'
134+ '"expires_at":4102444800000,"expired":false}',
135+ }
136+
137+ httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
138+ port = httpd.server_address[1]
139+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
140+ base = "http://127.0.0.1:%d/" % port
141+
142+ os.makedirs(DOCS, exist_ok=True)
143+ failures = []
144+ checks = 0
145+
146+ def ok(cond, label):
147+ nonlocal checks
148+ checks += 1
149+ if not cond:
150+ failures.append(label)
151+ print(" FAIL %s" % label)
152+
153+ try:
154+ with sync_playwright() as pw:
155+ browser = pw.chromium.launch()
156+ for w, h in VIEWPORTS:
157+ for theme in THEMES:
158+ page = browser.new_page(viewport={"width": w, "height": h},
159+ color_scheme=theme)
160+ errors = []
161+ page.on("console", lambda m: errors.append(m.text)
162+ if m.type == "error" else None)
163+ page.on("pageerror", lambda e: errors.append(str(e)))
164+
165+ page.goto(base + "?theme=%s" % theme, wait_until="load")
166+ page.wait_for_function(
167+ "document.getElementById('pillText').textContent"
168+ " !== 'Checking'", timeout=8000)
169+
170+ ok(page.text_content("#pillText") == "Connected",
171+ "status pill says Connected @%dx%d %s" % (w, h, theme))
172+ ok("pico@example.com" in page.text_content("#sub"),
173+ "account shown in the header @%dx%d %s" % (w, h, theme))
174+ ok("pico@example.com" in page.text_content("#session"),
175+ "session card lists the account @%dx%d %s" % (w, h, theme))
176+ ok("proj-mock-42" in page.text_content("#project"),
177+ "companion project card @%dx%d %s" % (w, h, theme))
178+
179+ sw = page.evaluate("document.documentElement.scrollWidth")
180+ iw = page.evaluate("window.innerWidth")
181+ ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
182+ % (sw, iw, w, h, theme))
183+
184+ # the theme actually applied (the CSS variables resolved)
185+ bg = page.evaluate(
186+ "getComputedStyle(document.body).backgroundColor")
187+ if theme == "light":
188+ ok(bg.startswith("rgb(245") or bg.startswith("rgb(255"),
189+ "light theme background @%dx%d" % (w, h))
190+ else:
191+ ok(bg.startswith("rgb(0"), "dark theme background @%dx%d"
192+ % (w, h))
193+
194+ ok(not errors, "no console error @%dx%d %s (%s)"
195+ % (w, h, theme, "; ".join(errors[:2])))
196+
197+ shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
198+ page.screenshot(path=shot)
199+ page.close()
200+
201+ # the login flow, at one viewport
202+ page = browser.new_page(viewport={"width": 1024, "height": 768})
203+ errors = []
204+ page.on("pageerror", lambda e: errors.append(str(e)))
205+ page.goto(base + "?theme=dark", wait_until="load")
206+ page.wait_for_function(
207+ "document.getElementById('pillText').textContent !== 'Checking'",
208+ timeout=8000)
209+
210+ page.click("#btnStart")
211+ page.wait_for_selector("#step2.on", timeout=8000)
212+ url = page.text_content("#authUrl")
213+ ok(url.startswith("https://accounts.google.com/"),
214+ "start produced an authorization URL")
215+ ok("code_challenge=" in url, "the URL carries the PKCE challenge")
216+ ok(page.get_attribute("#linkOpen", "href").startswith(
217+ "https://accounts.google.com/"), "the open link is wired")
218+
219+ page.click("#btnCancel")
220+ page.wait_for_selector("#step1.on", timeout=8000)
221+ ok(not page.is_visible("#step2.on"), "cancel returns to step one")
222+
223+ # a rejected exchange shows the inline error, not silence
224+ page.click("#btnStart")
225+ page.wait_for_selector("#step2.on", timeout=8000)
226+ page.fill("#codeInput", "not a code ' with quote")
227+ page.click("#btnFinish")
228+ page.wait_for_function(
229+ "document.getElementById('loginNote').classList.contains('show')",
230+ timeout=8000)
231+ note = page.text_content("#loginNote")
232+ ok("code" in note.lower(), "an invalid code explains itself (%r)" % note[:60])
233+ ok(not errors, "no page error during the flow (%s)"
234+ % "; ".join(errors[:2]))
235+ page.screenshot(path=os.path.join(DOCS, "ui-flow-dark.png"))
236+ page.close()
237+
238+ # embed mode hides the theme toggle
239+ page = browser.new_page(viewport={"width": 1024, "height": 768})
240+ page.goto(base + "?embed=1&theme=dark", wait_until="load")
241+ page.wait_for_function(
242+ "document.getElementById('pillText').textContent !== 'Checking'",
243+ timeout=8000)
244+ ok(not page.is_visible("#themeToggle"), "embed hides the theme toggle")
245+ ok(page.evaluate(
246+ "document.documentElement.classList.contains('embedded')"),
247+ "embed marks html.embedded")
248+ page.close()
249+ browser.close()
250+ finally:
251+ httpd.shutdown()
252+ shutil.rmtree(work, ignore_errors=True)
253+
254+ print("\n%d checks, %d failure(s)" % (checks, len(failures)))
255+ if failures:
256+ for f in failures:
257+ print(" - %s" % f)
258+ return 1
259+ print("RESULT: OK")
260+ return 0
261+
262+
263+if __name__ == "__main__":
264+ sys.exit(main())
tests/run.sh+10−0■■■■■
index e31a831..cae01d5 100755index e31a831..cae01d5 100755
--- a/tests/run.sh--- a/tests/run.sh
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -195,6 +195,16 @@ EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \@@ -195,6 +195,16 @@ EXPIRED=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
195 json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \195 json_ok "an expired session reports expired true and a negative remaining time" "$EXPIRED" \
196 "d['expired'] is True and d['expires_in_sec'] < 0"196 "d['expired'] is True and d['expires_in_sec'] < 0"
197 197
198+# a far-future expiry must not overflow: expires_in_sec used to be an int, so
199+# any expiry past 2038 came out as -1987015054 while expired stayed false.
200+FAR=$(ANTIGRAVITY_CREDS_PATH="$FIX/full/antigravity_accounts.json" \
201+ MOCK_STATUS_JSON='{"ok":true,"provider":"antigravity","logged_in":true,"expires_at":4102444800000,"expired":false,"has_refresh":true}' \
202+ api "action=status")
203+json_ok "a post-2038 expiry reports a positive remaining time" "$FAR" \
204+ "d['expires_in_sec'] > 0 and d['expired'] is False"
205+json_ok "a post-2038 expiry normalises ms to seconds" "$FAR" \
206+ "d['expires_at'] == 4102444800"
207+
198 # pending marker file present -> pending true even without CLI help208 # pending marker file present -> pending true even without CLI help
199 : > "$FIX/pending/antigravity-default.json"209 : > "$FIX/pending/antigravity-default.json"
200 PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \210 PEND=$(ANTIGRAVITY_CREDS_PATH="$FIX/none/antigravity_accounts.json" \
201211