Skip to content

Commit 2d462fb

Browse files
committed
fix(web): defensive session-start parse + e2e harness wiring
- startSession() reads res.text() then JSON.parse in try/catch so a 500 with a non-JSON body surfaces the real HTTP status instead of masking as 'Network error' (audit finding class). - e2e/conftest.py puts tests/ on sys.path so shared _playwright_helpers imports from the e2e subpackage. - Mark both e2e journey tests with pytest.mark.e2e so the default marker filter deselects them (they were erroring at collection in the full run). - gitignore test-results/ (Playwright failure artifacts).
1 parent 5a0dd08 commit 2d462fb

5 files changed

Lines changed: 728 additions & 6 deletions

File tree

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,3 +544,6 @@ graphify-out/
544544
# MemPalace per-project files (issue #185)
545545
mempalace.yaml
546546
entities.json
547+
548+
# Playwright/e2e failure artifacts
549+
test-results/

‎packages/studyloop/src/studyloop/web/static/index.html‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2445,18 +2445,29 @@ <h3>LLM Providers</h3>
24452445
transport: this.transport,
24462446
}),
24472447
});
2448-
const data = await res.json();
2448+
/* Parse defensively: a 500 with an HTML/plain body must NOT masquerade
2449+
as a network error. Read text, then try JSON — a non-JSON body on a
2450+
failed response is a real server error, surfaced with its status. */
2451+
const raw = await res.text();
2452+
let data = {};
2453+
try { data = raw ? JSON.parse(raw) : {}; } catch { data = {}; }
24492454
if (!res.ok) {
2450-
/* §1.5b returns structured 503 with install_hint; surface it verbatim. */
2451-
this.startError = data.install_hint
2452-
? `${data.error} · ${data.install_hint}`
2453-
: (data.error || 'Failed to start session');
2455+
/* §1.5b returns structured 503 with install_hint; surface it verbatim.
2456+
For a non-JSON error body, fall back to the HTTP status + snippet. */
2457+
if (data.install_hint) {
2458+
this.startError = `${data.error} · ${data.install_hint}`;
2459+
} else if (data.error) {
2460+
this.startError = data.error;
2461+
} else {
2462+
const snippet = raw.trim().slice(0, 200);
2463+
this.startError = `Server error (HTTP ${res.status})` + (snippet ? `: ${snippet}` : '');
2464+
}
24542465
this.starting = false;
24552466
return;
24562467
}
24572468
startedSession = data;
24582469
} catch {
2459-
this.startError = 'Network error — could not start session';
2470+
this.startError = 'Network error — could not reach the server';
24602471
this.starting = false;
24612472
return;
24622473
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"""Make shared test helpers in ``tests/`` importable from the e2e package."""
2+
3+
import sys
4+
from pathlib import Path
5+
6+
_TESTS_DIR = str(Path(__file__).resolve().parent.parent)
7+
if _TESTS_DIR not in sys.path:
8+
sys.path.insert(0, _TESTS_DIR)
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
"""Minimal smoke test for fast content index loading and real-time left pane status.
2+
3+
DEPRECATED as a standalone test. The authoritative end-to-end test is now
4+
`test_representative_user_journey.py`, which has been expanded to cover the
5+
complete representative user flow:
6+
7+
Body Double → Socratic study session → Flashcards (≥5 + support) →
8+
Quizzes (≥5 + support) → Mastery tab with real-time RHS/index updates.
9+
10+
This narrow smoke test is retained only for rapid iteration while the
11+
index/UI sync bug (provider dropdown never appears) is being fixed.
12+
Once that bug is resolved, `test_representative_user_journey.py` becomes
13+
the single canonical gate for the full product.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import os
19+
import subprocess
20+
import time
21+
from pathlib import Path
22+
from typing import Any
23+
24+
import pytest
25+
26+
pytest.importorskip("playwright")
27+
pytest.importorskip("requests")
28+
29+
from playwright.sync_api import ConsoleMessage, Page, expect, TimeoutError as PlaywrightTimeout
30+
31+
from _playwright_helpers import start_web_server
32+
33+
pytestmark = [pytest.mark.e2e]
34+
35+
WEB_PORT = 18592
36+
DEBUG = bool(os.getenv("STUDYLOOP_E2E_DEBUG"))
37+
38+
39+
def _capture_diagnostics(
40+
page: Page | None,
41+
test_name: str,
42+
console_messages: list[dict[str, Any]] | None = None,
43+
extra_note: str = "",
44+
) -> None:
45+
"""Capture rich failure diagnostics (best practice for E2E tests)."""
46+
ts = int(time.time())
47+
results_dir = Path("test-results")
48+
results_dir.mkdir(exist_ok=True)
49+
50+
artifacts: list[str] = []
51+
52+
if page:
53+
try:
54+
png_path = results_dir / f"{test_name}-{ts}.png"
55+
page.screenshot(path=str(png_path), full_page=True)
56+
artifacts.append(str(png_path))
57+
58+
html_path = results_dir / f"{test_name}-{ts}.html"
59+
html_path.write_text(page.content())
60+
artifacts.append(str(html_path))
61+
except Exception as exc:
62+
print(f"[diagnostics] Screenshot/HTML failed: {exc}")
63+
64+
if console_messages:
65+
errors = [m for m in console_messages if m["type"] in ("error", "warning")]
66+
if errors:
67+
log_path = results_dir / f"{test_name}-{ts}-console.txt"
68+
with open(log_path, "w") as f:
69+
for m in errors:
70+
f.write(f"[{m['type'].upper()}] {m['text']}\n")
71+
artifacts.append(str(log_path))
72+
73+
if artifacts:
74+
print("\n[diagnostics] Failure artifacts saved:")
75+
for a in artifacts:
76+
print(f" - {a}")
77+
if extra_note:
78+
print(f"[diagnostics] Note: {extra_note}")
79+
80+
if DEBUG:
81+
print("[diagnostics] DEBUG mode active.")
82+
83+
84+
@pytest.fixture(scope="module")
85+
def running_server():
86+
proc = start_web_server(WEB_PORT)
87+
try:
88+
yield f"http://127.0.0.1:{WEB_PORT}"
89+
finally:
90+
proc.terminate()
91+
try:
92+
proc.wait(timeout=5)
93+
except Exception:
94+
proc.kill()
95+
96+
97+
def test_index_loads_fast_and_left_pane_updates(browser, running_server: str) -> None:
98+
"""Iteration 1: Force index via CLI, then validate UI + session status."""
99+
base_url = running_server
100+
context = browser.new_context()
101+
page: Page = context.new_page()
102+
103+
console_messages: list[dict[str, Any]] = []
104+
105+
def on_console(msg: ConsoleMessage) -> None:
106+
console_messages.append({"type": msg.type, "text": msg.text})
107+
108+
page.on("console", on_console)
109+
110+
try:
111+
# === Data-driven fix: Force fresh index using the working CLI ===
112+
print("[iteration-1] Forcing content index refresh via CLI...")
113+
result = subprocess.run(
114+
["uv", "run", "studyloop", "content", "index", "--force"],
115+
capture_output=True,
116+
text=True,
117+
timeout=120,
118+
)
119+
if result.returncode != 0:
120+
print(result.stderr)
121+
pytest.fail("Content index refresh failed. See output above.")
122+
123+
print("[iteration-1] Index refresh complete. Loading Generate tab...")
124+
125+
page.goto(f"{base_url}/#generate")
126+
page.wait_for_load_state("domcontentloaded")
127+
128+
# Early diagnostic for provider dropdown
129+
try:
130+
page.wait_for_selector("select[name='provider']", timeout=6000)
131+
page.select_option("select[name='provider']", label="ArjanCodes")
132+
except PlaywrightTimeout:
133+
_capture_diagnostics(
134+
page,
135+
"content_index_fast_load",
136+
console_messages,
137+
extra_note="Provider dropdown still missing after CLI index refresh.",
138+
)
139+
pytest.fail("Provider dropdown did not appear. Check diagnostics in test-results/.")
140+
141+
expect(page.locator("select[name='course'] option")).not_to_have_text(
142+
"— pick a publisher first —", timeout=8000
143+
)
144+
145+
# Session start + left pane checks
146+
import requests
147+
148+
topic = "Software Design Mastery 1/3 | CORE DESIGNER - Abstraction and Coupling"
149+
resp = requests.post(
150+
f"{base_url}/api/session/start",
151+
json={
152+
"topic": topic,
153+
"energy": 7,
154+
"agent": "Claude Code",
155+
"transport": "Browser terminal (xterm.js)",
156+
},
157+
timeout=10,
158+
)
159+
160+
if not resp.ok:
161+
_capture_diagnostics(page, "content_index_fast_load", console_messages)
162+
pytest.fail(f"Session start failed: {resp.status_code} {resp.text[:300]}")
163+
164+
expect(page.locator("#activity-feed")).to_contain_text(
165+
"Session live — wins and parked questions appear here", timeout=8000
166+
)
167+
expect(page.locator("#session-meta")).to_contain_text("Abstraction", timeout=5000)
168+
169+
print("\n✅ Iteration 1 passed — provider dropdown and session status working.")
170+
171+
except Exception:
172+
_capture_diagnostics(page, "content_index_fast_load", console_messages)
173+
raise
174+
finally:
175+
page.remove_listener("console", on_console)
176+
context.close()

0 commit comments

Comments
 (0)