overhaul: single-session deployment + redesigned frontend

Backend simplification:
- The server now loads ONE pool JSON from $QUIZ_POOL_PATH at startup and
  upserts a single canonical session. The session id comes from the pool
  JSON's optional "session_id" field, falling back to $QUIZ_SESSION_ID.
- The multi-quiz / multi-session CRUD API is gone:
    DELETED  GET/POST /admin/api/quizzes
    DELETED  POST    /admin/api/quizzes/upload
    DELETED  GET/POST /admin/api/sessions
    DELETED  GET     /admin/login (HTML stub)
    DELETED  GET     /admin/api/sessions/{sid}/csv (replaced by /admin/api/csv)
  Replaced with a single-session control surface:
    GET  /admin/                — serves admin.html unconditionally
    GET  /admin/api/state       — admin-gated; pool meta + state + QR + join URL
    POST /admin/api/reset       — admin-gated; wipe submissions + back to lobby
    POST /admin/logout          — clear admin cookie
    GET  /admin/api/csv         — single-session results
    WS   /ws/instructor/{sid}   — kept; new commands "next" + "reset"
- Instructor "Next" button is now a single state-driving command
  (RoomManager.advance_to_next): from lobby it opens Q0; from question_open
  it closes the current Q and opens the next; from question_closed it
  opens the next; if past the last question it ends the session.
- New RoomManager.reset wipes submissions, participants, and per-question
  state, then broadcasts a clean lobby.
- Student GET / now redirects to /?sid=<canonical> when no sid is given,
  so the QR / share URL is fully deterministic.

Frontend rewrite (functional baseline; visual polish to follow):
- /admin/ is now a single SPA: GET /admin/api/state decides login form
  vs dashboard. No separate /admin/login URL bar.
- Admin dashboard is state-driven with one primary action per state.
  QR code, join URL, and live participant list are always visible on the
  left so the operator can leave the page on a projector.
- Student answer buttons are big and tappable; reveal screen highlights
  correct/wrong choice + shows score, total, and rank.
- Static admin/student SPAs share a CSS palette with light/dark support.

Tests rewritten around the single canonical session id.
The auto-bootstrapped session lets each test fixture skip the old
quiz/session creation dance. 39/39 tests pass.

Cleanup:
- Deleted CODEX_PROMPT.md, IMPLEMENTATION_REPORT.md, NOTES.md, SPEC.md,
  static/observer.html (obsolete codex-build artifacts and the unused
  observer view).
- .gitignore now blocks /pool.json (the runtime file the operator drops
  on the server) and the leftover .codex_done / codex_run.log / etc.
- bootstrap.sh seeds /opt/quiz/pool.json from examples/pool_example.json
  on first deploy so a fresh box reaches a usable state without manual
  intervention; .env now includes QUIZ_POOL_PATH.
This commit is contained in:
ameer
2026-05-02 21:13:54 +08:00
parent 32c531247d
commit e7a2f0387b
29 changed files with 1696 additions and 1533 deletions

View File

@@ -44,6 +44,100 @@ class RoomManager:
self.instructor_clients: dict[str, set[WebSocket]] = defaultdict(set)
self.autoclose_tasks: dict[tuple[str, int], asyncio.Task] = {}
self.locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
# The single canonical session id, set during startup once the pool
# has been loaded. Routes use this rather than settings.default_session_id
# so that a session_id field in the pool JSON can override the env default.
self.canonical_sid: str | None = None
async def ensure_single_session(self, sid: str, pool: dict[str, Any]) -> None:
"""Idempotently upsert the canonical single-session row + its quiz row.
Called on startup with the operator-supplied pool JSON. Creates the
quiz + session if they don't exist, otherwise updates the pool blob
on the existing quiz so a fresh restart picks up edits to the pool
file without losing prior submissions for the same session.
"""
title = pool["title"]
pool_blob = json.dumps(pool)
async with connect(self.settings.db_path) as db:
cursor = await db.execute(
"SELECT quiz_id FROM quiz_sessions WHERE sid = ?",
(sid,),
)
row = await cursor.fetchone()
if row is None:
cursor = await db.execute(
"INSERT INTO quizzes (title, pool_json, time_limit_default, score_fn_name) VALUES (?, ?, ?, ?)",
(title, pool_blob, pool["time_limit_default"], pool["score_fn"]),
)
quiz_id = cursor.lastrowid
await db.execute(
"INSERT INTO quiz_sessions (sid, quiz_id, title) VALUES (?, ?, ?)",
(sid, quiz_id, title),
)
else:
quiz_id = row["quiz_id"]
await db.execute(
"UPDATE quizzes SET title = ?, pool_json = ?, time_limit_default = ?, score_fn_name = ? WHERE id = ?",
(title, pool_blob, pool["time_limit_default"], pool["score_fn"], quiz_id),
)
await db.execute(
"UPDATE quiz_sessions SET title = ? WHERE sid = ?",
(title, sid),
)
await db.commit()
async def advance_to_next(self, sid: str) -> None:
"""Instructor 'Next' button: a single button that drives the whole
lifecycle. From lobby it opens Q0; from a question_open state it
closes the current Q and opens the next; from question_closed it
opens the next Q. If there is no next question, the session ends.
"""
async with self.locks[sid]:
session = await self.get_session(sid)
if session["state"] == "finished":
return
current_idx = session["current_question_idx"]
close_current = session["state"] == "question_open"
if close_current:
await self._close_question_locked(sid, int(current_idx))
if close_current:
await self.broadcast_question_closed(sid, int(current_idx))
pool = await self.get_pool_for_session(sid)
total = question_count(pool)
next_idx = 0 if current_idx is None else int(current_idx) + 1
if next_idx >= total:
await self.end_session(sid)
return
await self.open_question(sid, next_idx)
async def reset(self, sid: str) -> None:
"""Wipe submissions, participants, and per-question state, then return
the session to lobby. Useful for re-running the same quiz across
classes without redeploying."""
async with self.locks[sid]:
task_keys = [key for key in self.autoclose_tasks if key[0] == sid]
for key in task_keys:
task = self.autoclose_tasks.pop(key, None)
if task:
task.cancel()
async with connect(self.settings.db_path) as db:
await db.execute("DELETE FROM submissions WHERE sid = ?", (sid,))
await db.execute("DELETE FROM question_events WHERE sid = ?", (sid,))
await db.execute("DELETE FROM participants WHERE sid = ?", (sid,))
await db.execute(
"UPDATE quiz_sessions SET state = 'lobby', current_question_idx = NULL, finished_at = NULL WHERE sid = ?",
(sid,),
)
await db.commit()
for ws in list(self.student_clients.get(sid, {}).keys()):
try:
await ws.close(code=4002)
except Exception:
pass
self.student_clients.pop(sid, None)
await self.broadcast_instructors(sid, {"type": "state", "state": "lobby", "current_question_idx": None, "title": (await self.get_session(sid))["title"]})
await self.broadcast_lobby(sid)
async def sessions_active(self) -> int:
async with connect(self.settings.db_path) as db:
@@ -139,9 +233,11 @@ class RoomManager:
elif msg_type == "close_question":
await self.close_question(sid)
elif msg_type == "next":
await self.next_question(sid)
await self.advance_to_next(sid)
elif msg_type == "end_session":
await self.end_session(sid)
elif msg_type == "reset":
await self.reset(sid)
else:
await websocket.send_json({"type": "error", "code": "bad_message", "message": "Unknown message type"})
except (WebSocketDisconnect, RuntimeError):