3v324v23 commited on
Commit
291b33d
·
1 Parent(s): 21e1fef

Enhance monitoring features with action logging and recent activity tracking

Browse files
app/answer_routes.py CHANGED
@@ -15,6 +15,8 @@ from .math_photo import PhotoUnavailable
15
  from .math_skills import algebra9, question_version
16
 
17
  log = logging.getLogger("mathly.answer_routes")
 
 
18
 
19
 
20
  def open_ended_locked():
@@ -57,6 +59,13 @@ def install_answer_routes(app, signed_in):
57
  result["grading_available"] = False
58
  return result
59
 
 
 
 
 
 
 
 
60
  def reply(result):
61
  return JSONResponse(public_result(result), headers={"Cache-Control": "no-store"})
62
 
@@ -108,6 +117,7 @@ def install_answer_routes(app, signed_in):
108
  assessment = grader.grade(app.state.answers.read(result["attachment"]["object_key"]),
109
  result["attempt"]["snapshot"])
110
  app.state.answers.grade(user, "complete", attempt_id=aid, lease_id=lease, result=assessment)
 
111
  except Exception as exc:
112
  # Retain both the image and a retryable failure; never award credit on error.
113
  try:
@@ -161,6 +171,7 @@ def install_answer_routes(app, signed_in):
161
  sid, lease = uuid_text(scan_id), uuid_text(lease_id)
162
  data = await photo.read(MAX_IMAGE + 1)
163
  result = await run_in_threadpool(submit, user, sid, lease, data, photo.content_type)
 
164
  if result.get("grading_available") and not result.get("grading"):
165
  background_tasks.add_task(automatic_grade, user, result["attempt"]["id"])
166
  return reply(result)
 
15
  from .math_skills import algebra9, question_version
16
 
17
  log = logging.getLogger("mathly.answer_routes")
18
+ VERDICTS = {"correct": "נכונה", "partial": "נכונה חלקית", "incorrect": "שגויה",
19
+ "unreadable": "לא קריאה", "needs_review": "דורשת בדיקה"}
20
 
21
 
22
  def open_ended_locked():
 
59
  result["grading_available"] = False
60
  return result
61
 
62
+ def note(user, kind, result, extra=""):
63
+ """Adds to Monitoring's recent actions: the question's name, and the verdict of a check."""
64
+ actions = getattr(app.state, "actions", None)
65
+ if actions is not None:
66
+ name = ((result.get("attempt") or {}).get("snapshot") or {}).get("name", "")
67
+ actions.record(user, kind, " · ".join(filter(None, [name, extra])))
68
+
69
  def reply(result):
70
  return JSONResponse(public_result(result), headers={"Cache-Control": "no-store"})
71
 
 
117
  assessment = grader.grade(app.state.answers.read(result["attachment"]["object_key"]),
118
  result["attempt"]["snapshot"])
119
  app.state.answers.grade(user, "complete", attempt_id=aid, lease_id=lease, result=assessment)
120
+ note(user, "answer_graded", result, VERDICTS.get(assessment.get("verdict"), ""))
121
  except Exception as exc:
122
  # Retain both the image and a retryable failure; never award credit on error.
123
  try:
 
171
  sid, lease = uuid_text(scan_id), uuid_text(lease_id)
172
  data = await photo.read(MAX_IMAGE + 1)
173
  result = await run_in_threadpool(submit, user, sid, lease, data, photo.content_type)
174
+ note(user, "answer_upload", result)
175
  if result.get("grading_available") and not result.get("grading"):
176
  background_tasks.add_task(automatic_grade, user, result["attempt"]["id"])
177
  return reply(result)
app/main.py CHANGED
@@ -22,7 +22,7 @@ from .auth import AuthUnavailable, ClassConflict, SupabaseAuth, load_auth
22
  from .math_photo import (DAILY_PHOTOS, MAX_PHOTO, MEDIA_TYPES as PHOTO_TYPES,
23
  PhotoSolver, PhotoUnavailable, math_model, photo_client)
24
  from .math_skills import algebra9, practice_graph
25
- from .monitoring import install_monitoring_routes
26
 
27
  logging.basicConfig(level=logging.INFO)
28
  log = logging.getLogger("mathly")
@@ -58,6 +58,7 @@ def create_app(auth: SupabaseAuth | None = None) -> FastAPI:
58
  app.state.photo = None
59
  app.state.photo_key = None
60
  app.state.seen = {}
 
61
  app.state.photo_counts = {}
62
  app.mount("/static", FreshStatic(directory=STATIC), name="static")
63
 
@@ -76,7 +77,10 @@ def create_app(auth: SupabaseAuth | None = None) -> FastAPI:
76
  raise HTTPException(401, "sign in required")
77
  if user.get("denied"):
78
  raise HTTPException(403, "this account is not in a math class")
79
- app.state.seen[user.get("id") or user.get("email", "")] = time.time() # for Monitoring's "signed in lately"
 
 
 
80
  return user
81
 
82
  async def manager(user: dict | None = Depends(signed_in)) -> dict:
@@ -175,17 +179,23 @@ self.addEventListener("activate", event => event.waitUntil((async () => {
175
  return {"ok": True, "id": class_id, "name": name, "lessons": selected}
176
 
177
  @app.post("/api/classes")
178
- async def create_class(body: dict, _user: dict = Depends(manager)):
179
- return save_class(None, body)
 
 
180
 
181
  @app.put("/api/classes/{class_id}")
182
- async def update_class(class_id: int, body: dict, _user: dict = Depends(manager)):
183
- return save_class(class_id, body)
 
 
184
 
185
  @app.delete("/api/classes/{class_id}")
186
- async def delete_class(class_id: int, _user: dict = Depends(manager)):
187
  try:
 
188
  app.state.auth.delete_class(class_id)
 
189
  except AuthUnavailable as exc:
190
  raise HTTPException(503, str(exc)) from exc
191
  return {"ok": True}
@@ -274,6 +284,8 @@ self.addEventListener("activate", event => event.waitUntil((async () => {
274
  raise
275
  if counter and not result.get("readable"):
276
  photo_counts[counter] -= 1
 
 
277
  return {**result, "left": DAILY_PHOTOS - photo_counts.get(counter, 0) if counter else None}
278
 
279
  @app.post("/api/math/phone-photo")
 
22
  from .math_photo import (DAILY_PHOTOS, MAX_PHOTO, MEDIA_TYPES as PHOTO_TYPES,
23
  PhotoSolver, PhotoUnavailable, math_model, photo_client)
24
  from .math_skills import algebra9, practice_graph
25
+ from .monitoring import ActionLog, RETURN_GAP, install_monitoring_routes
26
 
27
  logging.basicConfig(level=logging.INFO)
28
  log = logging.getLogger("mathly")
 
58
  app.state.photo = None
59
  app.state.photo_key = None
60
  app.state.seen = {}
61
+ app.state.actions = ActionLog()
62
  app.state.photo_counts = {}
63
  app.mount("/static", FreshStatic(directory=STATIC), name="static")
64
 
 
77
  raise HTTPException(401, "sign in required")
78
  if user.get("denied"):
79
  raise HTTPException(403, "this account is not in a math class")
80
+ key, now = user.get("id") or user.get("email", ""), time.time()
81
+ if now - app.state.seen.get(key, 0) > RETURN_GAP:
82
+ app.state.actions.record(user, "visit")
83
+ app.state.seen[key] = now # for Monitoring's "signed in lately"
84
  return user
85
 
86
  async def manager(user: dict | None = Depends(signed_in)) -> dict:
 
179
  return {"ok": True, "id": class_id, "name": name, "lessons": selected}
180
 
181
  @app.post("/api/classes")
182
+ async def create_class(body: dict, user: dict = Depends(manager)):
183
+ result = save_class(None, body)
184
+ app.state.actions.record(user, "class_saved", f"נפתחה: {result['name']}")
185
+ return result
186
 
187
  @app.put("/api/classes/{class_id}")
188
+ async def update_class(class_id: int, body: dict, user: dict = Depends(manager)):
189
+ result = save_class(class_id, body)
190
+ app.state.actions.record(user, "class_saved", f"נערכה: {result['name']}")
191
+ return result
192
 
193
  @app.delete("/api/classes/{class_id}")
194
+ async def delete_class(class_id: int, user: dict = Depends(manager)):
195
  try:
196
+ name = next((row["name"] for row in app.state.auth.classes() if row.get("id") == class_id), f"#{class_id}")
197
  app.state.auth.delete_class(class_id)
198
+ app.state.actions.record(user, "class_deleted", name)
199
  except AuthUnavailable as exc:
200
  raise HTTPException(503, str(exc)) from exc
201
  return {"ok": True}
 
284
  raise
285
  if counter and not result.get("readable"):
286
  photo_counts[counter] -= 1
287
+ skill = next((s["name"] for s in algebra9()["skills"] if s["id"] == result.get("skill")), "")
288
+ app.state.actions.record(user, "photo", skill if result.get("readable") else "התמונה לא נקראה")
289
  return {**result, "left": DAILY_PHOTOS - photo_counts.get(counter, 0) if counter else None}
290
 
291
  @app.post("/api/math/phone-photo")
app/monitoring.py CHANGED
@@ -9,7 +9,7 @@ import hashlib
9
  import os
10
  import subprocess
11
  import time
12
- from collections import Counter
13
  from datetime import date, datetime, timedelta, timezone
14
  from pathlib import Path
15
  from zoneinfo import ZoneInfo
@@ -26,6 +26,29 @@ LOCAL_TZ = ZoneInfo("Asia/Jerusalem")
26
  # period -> (minutes per bar, number of bars)
27
  PERIODS = {"day": (15, 96), "week": (60, 168), "month": (24 * 60, 30)}
28
  SEEN_KEEP = 24 * 3600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def build_metadata() -> dict[str, str]:
@@ -117,13 +140,15 @@ def install_monitoring_routes(app, manager) -> None:
117
  app.state.seen = {}
118
  if not hasattr(app.state, "photo_counts"):
119
  app.state.photo_counts = {}
 
 
120
 
121
  @app.get("/api/monitor/summary")
122
  def monitor_summary(_user: dict = Depends(manager)):
123
  """Everything the Monitoring summary can tell without a network call."""
124
  answers = app.state.answers
125
  return {"build": build_metadata(), "errors": log_errors.COUNTER.summary(),
126
- "seen": seen_summary(app.state.seen), "photos": photo_summary(app.state.photo_counts),
127
  "answers": {"storage": answers.configured, "open_ended_locked": open_ended_locked(),
128
  "grading": bool(grading_key())},
129
  "photo_help": bool(os.environ.get("ANTHROPIC_API_KEY", "").strip()
 
9
  import os
10
  import subprocess
11
  import time
12
+ from collections import Counter, deque
13
  from datetime import date, datetime, timedelta, timezone
14
  from pathlib import Path
15
  from zoneinfo import ZoneInfo
 
26
  # period -> (minutes per bar, number of bars)
27
  PERIODS = {"day": (15, 96), "week": (60, 168), "month": (24 * 60, 30)}
28
  SEEN_KEEP = 24 * 3600
29
+ RETURN_GAP = 30 * 60 # a sign-in after this long away counts as a new visit
30
+ ACTION_KINDS = frozenset({"visit", "photo", "answer_upload", "answer_graded", "class_saved", "class_deleted"})
31
+
32
+
33
+ class ActionLog:
34
+ """The latest actions on the server: what was done, by which account, and when. Kept in memory only,
35
+ so it starts empty after a restart. Labels name the question or class, never a student's answer."""
36
+
37
+ def __init__(self, keep: int = 200):
38
+ self._items: deque[dict] = deque(maxlen=keep)
39
+ self.emails: dict[str, str] = {} # user id -> email, learned at sign-in
40
+
41
+ def record(self, user: dict | str | None, kind: str, label: str = "") -> None:
42
+ if isinstance(user, dict):
43
+ if user.get("id") and user.get("email"):
44
+ self.emails[user["id"]] = user["email"]
45
+ email = user.get("email", "")
46
+ else:
47
+ email = self.emails.get(user or "", "")
48
+ self._items.append({"at": time.time(), "kind": kind, "email": email, "label": str(label or "")[:120]})
49
+
50
+ def recent(self, limit: int = 20) -> list[dict]:
51
+ return list(reversed(self._items))[:limit]
52
 
53
 
54
  def build_metadata() -> dict[str, str]:
 
140
  app.state.seen = {}
141
  if not hasattr(app.state, "photo_counts"):
142
  app.state.photo_counts = {}
143
+ if not hasattr(app.state, "actions"):
144
+ app.state.actions = ActionLog()
145
 
146
  @app.get("/api/monitor/summary")
147
  def monitor_summary(_user: dict = Depends(manager)):
148
  """Everything the Monitoring summary can tell without a network call."""
149
  answers = app.state.answers
150
  return {"build": build_metadata(), "errors": log_errors.COUNTER.summary(),
151
+ "seen": seen_summary(app.state.seen), "actions": app.state.actions.recent(), "photos": photo_summary(app.state.photo_counts),
152
  "answers": {"storage": answers.configured, "open_ended_locked": open_ended_locked(),
153
  "grading": bool(grading_key())},
154
  "photo_help": bool(os.environ.get("ANTHROPIC_API_KEY", "").strip()
static/math.css CHANGED
@@ -235,7 +235,10 @@ html.math-on, html.math-on body{overflow:hidden}
235
  .mx-mon-tile.ready{border-color:var(--ok);background:var(--ok-bg)}.mx-mon-tile.ready b{color:var(--ok)}
236
  .mx-mon-tile.busy{border-color:var(--amber);background:var(--amber-bg)}.mx-mon-tile.busy b,.mx-mon-tile.warn b{color:var(--amber)}
237
  .mx-mon-tile.bad{border-color:var(--sumac);background:var(--sumac-bg)}.mx-mon-tile.bad b{color:var(--sumac)}
238
- .mx-mon-lower{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr);gap:12px}
 
 
 
239
  .mx-mon-panel{padding:12px;border:1px solid var(--line);border-radius:12px;min-width:0;display:flex;flex-direction:column;gap:6px}
240
  .mx-mon-panel h6{margin:0;font:700 15px/1.3 var(--f-body)}
241
  .mx-mon-flags,.mx-mon-verdicts{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:5px;font-size:13px}
 
235
  .mx-mon-tile.ready{border-color:var(--ok);background:var(--ok-bg)}.mx-mon-tile.ready b{color:var(--ok)}
236
  .mx-mon-tile.busy{border-color:var(--amber);background:var(--amber-bg)}.mx-mon-tile.busy b,.mx-mon-tile.warn b{color:var(--amber)}
237
  .mx-mon-tile.bad{border-color:var(--sumac);background:var(--sumac-bg)}.mx-mon-tile.bad b{color:var(--sumac)}
238
+ .mx-mon-lower{display:grid;grid-template-columns:minmax(0,3fr) minmax(0,2fr);gap:12px}.mx-mon-logs{grid-column:1/-1}
239
+ .mx-mon-action{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:8px;align-items:center;padding:6px 0;border-bottom:1px solid var(--line)}.mx-mon-action:last-child{border-bottom:0}
240
+ .mx-mon-action i{font-style:normal}.mx-mon-action b,.mx-mon-action small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mx-mon-action b{font-size:14px}
241
+ .mx-mon-action small,.mx-mon-action time{color:var(--muted);font-size:12px}.mx-mon-action time{white-space:nowrap}
242
  .mx-mon-panel{padding:12px;border:1px solid var(--line);border-radius:12px;min-width:0;display:flex;flex-direction:column;gap:6px}
243
  .mx-mon-panel h6{margin:0;font:700 15px/1.3 var(--f-body)}
244
  .mx-mon-flags,.mx-mon-verdicts{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:5px;font-size:13px}
static/math.js CHANGED
@@ -524,6 +524,7 @@ function showManageMode(mode){
524
  /* Monitoring (ניטור): a snapshot of the system, open-answer activity, and the server's latest warnings.
525
  Each source loads and fails on its own, so a slow Supabase does not hold up the rest. */
526
  const MON_RANGES={day:["יום","24 השעות האחרונות","15 דקות"],week:["שבוע","7 הימים האחרונים","שעה"],month:["חודש","30 הימים האחרונים","יום"]};
 
527
  const VERDICTS={correct:"נכונות",partial:"נכונות חלקית",incorrect:"שגויות",unreadable:"לא קריאות",needs_review:"דורשות בדיקה",grading:"בבדיקה",failed:"הבדיקה נכשלה"};
528
  let MON={}, MON_RANGE=(()=>{try{return localStorage.getItem("mathly.monRange")}catch{return null}})();
529
  if(!MON_RANGES[MON_RANGE]) MON_RANGE="week";
@@ -589,8 +590,12 @@ function drawMonSummary(){
589
  const lines=sum?.errors?.recent;
590
  const logs=loading?'<p class="mx-note">טוען…</p>':err?`<p class="mx-note">לא ניתן לטעון: ${esc(err)}</p>`:!lines?.length?'<p class="mx-note">אין אזהרות או שגיאות מאז הפעלת השרת.</p>':
591
  lines.map(line=>`<div class="mx-mon-log"><div><span class="mx-mon-level ${(line.level||"").toLowerCase()==="warning"?"warn":"bad"}">${esc(line.level)}</span><code dir="ltr">${esc(line.logger)}</code>${monAgo(new Date(line.at*1000).toISOString())}</div><code class="mx-mon-msg" dir="ltr">${esc(line.message)}</code></div>`).join("");
 
 
 
 
592
  box.innerHTML=`<h5>תמונת מצב</h5><div class="mx-mon-tiles">${tiles.join("")}</div>
593
- <div class="mx-mon-lower"><div class="mx-mon-panel"><h6>תשובות פתוחות</h6>${answers}</div><div class="mx-mon-panel mx-mon-logs"><h6>5 שורות הלוג האחרונות (אזהרה ומעלה)</h6>${logs}</div></div>`;
594
  }
595
 
596
  function drawMonActivity(){
 
524
  /* Monitoring (ניטור): a snapshot of the system, open-answer activity, and the server's latest warnings.
525
  Each source loads and fails on its own, so a slow Supabase does not hold up the rest. */
526
  const MON_RANGES={day:["יום","24 השעות האחרונות","15 דקות"],week:["שבוע","7 הימים האחרונים","שעה"],month:["חודש","30 הימים האחרונים","יום"]};
527
+ const MON_ACTIONS={visit:["👋","נכנס/ה לאפליקציה"],photo:["📷","צילם/ה תרגיל לעזרה"],answer_upload:["📝","שלח/ה תשובה פתוחה"],answer_graded:["✔️","תשובה נבדקה"],class_saved:["🏫","שמר/ה כיתה"],class_deleted:["🗑️","מחק/ה כיתה"]};
528
  const VERDICTS={correct:"נכונות",partial:"נכונות חלקית",incorrect:"שגויות",unreadable:"לא קריאות",needs_review:"דורשות בדיקה",grading:"בבדיקה",failed:"הבדיקה נכשלה"};
529
  let MON={}, MON_RANGE=(()=>{try{return localStorage.getItem("mathly.monRange")}catch{return null}})();
530
  if(!MON_RANGES[MON_RANGE]) MON_RANGE="week";
 
590
  const lines=sum?.errors?.recent;
591
  const logs=loading?'<p class="mx-note">טוען…</p>':err?`<p class="mx-note">לא ניתן לטעון: ${esc(err)}</p>`:!lines?.length?'<p class="mx-note">אין אזהרות או שגיאות מאז הפעלת השרת.</p>':
592
  lines.map(line=>`<div class="mx-mon-log"><div><span class="mx-mon-level ${(line.level||"").toLowerCase()==="warning"?"warn":"bad"}">${esc(line.level)}</span><code dir="ltr">${esc(line.logger)}</code>${monAgo(new Date(line.at*1000).toISOString())}</div><code class="mx-mon-msg" dir="ltr">${esc(line.message)}</code></div>`).join("");
593
+ // the latest actions: what, who, when (kept in server memory since its last start)
594
+ const acts=sum?.actions;
595
+ const actions=loading?'<p class="mx-note">טוען…</p>':err?`<p class="mx-note">לא ניתן לטעון: ${esc(err)}</p>`:!acts?.length?'<p class="mx-note">עדיין לא נרשמו פעולות מאז הפעלת השרת.</p>':
596
+ acts.slice(0,10).map(a=>{ const [icon,what]=MON_ACTIONS[a.kind]||["•",a.kind]; return `<div class="mx-mon-action"><i aria-hidden="true">${icon}</i><div><b>${esc(what)}</b><small><span dir="ltr">${esc(a.email||"משתמש לא ידוע")}</span>${a.label?` · ${esc(a.label)}`:""}</small></div>${monAgo(new Date(a.at*1000).toISOString())}</div>`; }).join("");
597
  box.innerHTML=`<h5>תמונת מצב</h5><div class="mx-mon-tiles">${tiles.join("")}</div>
598
+ <div class="mx-mon-lower"><div class="mx-mon-panel"><h6>פעולות אחרונות</h6>${actions}</div><div class="mx-mon-panel"><h6>תשובות פתוחות</h6>${answers}</div><div class="mx-mon-panel mx-mon-logs"><h6>5 שורות הלוג האחרונות (אזהרה ומעלה)</h6>${logs}</div></div>`;
599
  }
600
 
601
  function drawMonActivity(){
tests/test_monitoring.py CHANGED
@@ -91,3 +91,14 @@ def test_small_summaries():
91
  assert photo_summary({("a", "d"): 20, ("b", "d"): 1, ("c", "e"): 3}, today="d") == {
92
  "today": 21, "students": 2, "at_limit": 1, "daily_limit": photo_summary({}, "d")["daily_limit"]}
93
  assert log_errors.COUNTER in logging.getLogger().handlers
 
 
 
 
 
 
 
 
 
 
 
 
91
  assert photo_summary({("a", "d"): 20, ("b", "d"): 1, ("c", "e"): 3}, today="d") == {
92
  "today": 21, "students": 2, "at_limit": 1, "daily_limit": photo_summary({}, "d")["daily_limit"]}
93
  assert log_errors.COUNTER in logging.getLogger().handlers
94
+
95
+
96
+ def test_recent_actions_name_the_action_and_the_user():
97
+ app = create_app(MonitorAuth())
98
+ get(app, "/api/me", STUDENT)
99
+ get(app, "/api/me", STUDENT) # a page reload soon after is the same visit
100
+ app.state.actions.record("s", "answer_upload", "Question 1") # answer routes pass the user id
101
+ actions = get(app, "/api/monitor/summary", TEACHER).json()["actions"]
102
+ assert [(a["kind"], a["email"], a["label"]) for a in actions] == [
103
+ ("visit", "t@test.invalid", ""), ("answer_upload", "s@test.invalid", "Question 1"),
104
+ ("visit", "s@test.invalid", "")]