""" admin_stats.py — Admin「裝置」分頁 + 對話篩選(P2-A, docs/11 §8.7; FR-TELE-04/10/12). No device_profiles / inference_log tables: everything is computed from telemetry_events (latest device_caps per device, chat_turn, model_download). Volumes are small (one row per app start / chat turn), so plain Python over the rows is fine. """ from __future__ import annotations import json import math import re from collections import Counter from datetime import datetime, timedelta, timezone from sqlalchemy import func, select from app import db from app.db import cases, devices, messages, telemetry_events from app.generated.prompt_source import RAILS TTFT_BUCKETS = (("<5s", 5_000), ("5–10s", 10_000), ("10–20s", 20_000), ("20–40s", 40_000), ("≥40s", None)) def _str(v) -> str | None: return v[:120] if isinstance(v, str) and v else None LOCAL_KINDS = ("full", "lite", "manual", "none") MAX_RAILS = 10 # FR-TELE-02 / FR-RAIL-07: rails_fired / `rails` hold ≤ 10 (main imports it) _RAIL_SCAN = MAX_RAILS * 3 # look at most 30 entries of a hostile list _KNOWN_RAILS = frozenset(r["id"] for r in RAILS) # only registered ids (rails.yaml) reach the admin aggregate def _rail_ids(v) -> list[str]: """chat_turn.rails_fired [{id, action, detail?}] → the distinct registered ids, in order, ≤ MAX_RAILS (FR-RAIL-07). Telemetry is untrusted: anything that is not a dict whose id is in rails.yaml is skipped, so the summary's `rails_fired_counts` has at most len(RAILS) keys.""" out: list[str] = [] for r in v[:_RAIL_SCAN] if isinstance(v, list) else []: rid = r.get("id") if isinstance(r, dict) else None if isinstance(rid, str) and rid in _KNOWN_RAILS and rid not in out: out.append(rid) return out[:MAX_RAILS] def _props(raw) -> dict: """Telemetry comes from any registered device: keep only the fields we read, with the types we expect (a list reason, an Infinity TTFT or a string tier must not 500 the page — review 2026-10-20 #3).""" try: p = json.loads(raw or "{}") except ValueError: return {} if not isinstance(p, dict): return {} static = p.get("static") if isinstance(p.get("static"), dict) else {} ttft, mem, tier = p.get("ttft_ms"), static.get("total_mem_gb"), p.get("tier") num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) # noqa: E731 return { "route": p.get("route") if p.get("route") in ("LOCAL", "API") else None, "ttft_ms": int(ttft) if num(ttft) and 0 <= ttft < 3_600_000 else None, "tier": tier if isinstance(tier, int) and not isinstance(tier, bool) and 0 <= tier <= 3 else None, "downgrade_reason": _str(p.get("downgrade_reason")), "app_version": _str(p.get("app_version")), "action": _str(p.get("action")), "role": _str(p.get("role")), "model": _str(static.get("model")), "total_mem_gb": float(mem) if num(mem) else None, # P5 (FR-LITE-12): which on-device mode — device_caps carries the phone's, chat_turn the turn's "local_kind": p.get("local_kind") if p.get("local_kind") in LOCAL_KINDS else None, "lite_guard_tripped": isinstance(p.get("lite_guard"), dict) and p["lite_guard"].get("tripped") is True, "last_resort": p.get("last_resort") is True, # openspec today-and-farm-records (2026-11-18): which card / which record kind — never the content "card": p.get("card") if p.get("card") in FEATURE_CARDS else None, "kind": p.get("kind") if p.get("kind") in FEATURE_KINDS else None, # guardrail-registry b3 (FR-RAIL-07): which guardrails answered this turn — ids only, never the detail "rails_fired": _rail_ids(p.get("rails_fired")), } FEATURE_CARDS = ("price", "alert", "reminder_withdrawal", "reminder_followup", "ask") FEATURE_KINDS = ("medication", "mortality") WITHDRAWAL_ACTIONS = ("schedule", "cancel", "denied") UPDATE_ACTIONS = ("shown", "accepted", "later") # openspec app-update-prompt 6.1 (FR-UPD-05) FEATURE_EVENTS = ("today_open", "today_card_tap", "farm_record", "withdrawal_reminder", "update_prompt") def _feature_window(events: list[dict], starts: list[dict], since: str) -> dict: """Counts for one window: per feature event the number of events and of distinct devices (today_card_tap also by card, farm_record by kind), plus the share of devices that started the App in the window and opened 今日 at least once (the retention signal the pilot watches, proposal §對 KPI 的影響).""" rows = [e for e in events if e["at"] >= since and e["device_id"]] out: dict = {} for name in FEATURE_EVENTS: mine = [e for e in rows if e["event"] == name] entry = {"n": len(mine), "devices": len({e["device_id"] for e in mine})} if name == "today_card_tap": entry["by_card"] = {c: sum(1 for e in mine if e["props"].get("card") == c) for c in FEATURE_CARDS} if name == "farm_record": entry["by_kind"] = {k: sum(1 for e in mine if e["props"].get("kind") == k) for k in FEATURE_KINDS} if name == "withdrawal_reminder": entry["by_action"] = {a: sum(1 for e in mine if e["props"].get("action") == a) for a in WITHDRAWAL_ACTIONS} if name == "update_prompt": entry["by_action"] = {a: sum(1 for e in mine if e["props"].get("action") == a) for a in UPDATE_ACTIONS} out[name] = entry app_devices = {e["device_id"] for e in starts if e["at"] >= since and e["device_id"]} today_devices = {e["device_id"] for e in rows if e["event"] == "today_open"} out["app_devices"] = len(app_devices) out["today_open_ratio"] = round(len(app_devices & today_devices) / len(app_devices), 3) if app_devices else None return out def feature_usage(now: datetime | None = None, exclude: set[str] | frozenset = frozenset()) -> dict: """`feature_usage` for /admin/devices/summary: the 今日 / 豬場 events and `update_prompt` over 7 and 30 days.""" with db.read_connection() as conn: events = [e for e in _events(conn, FEATURE_EVENTS, _since(30, now)) if e["device_id"] not in exclude] starts = [e for e in _events(conn, ("app_start",), _since(30, now)) if e["device_id"] not in exclude] return {"7d": _feature_window(events, starts, _since(7, now)), "30d": _feature_window(events, starts, _since(30, now))} def _events(conn, names: tuple[str, ...], since: str | None = None) -> list[dict]: stmt = (select(telemetry_events.c.device_id, telemetry_events.c.event, telemetry_events.c.props, telemetry_events.c.received_at) .where(telemetry_events.c.event.in_(names)).order_by(telemetry_events.c.id)) if since: stmt = stmt.where(telemetry_events.c.received_at >= since) return [{"device_id": r.device_id, "event": r.event, "props": _props(r.props), "at": r.received_at} for r in conn.execute(stmt)] def _since(days: int, now: datetime | None) -> str: now = (now or datetime.now(timezone.utc)).replace(tzinfo=None) return (now - timedelta(days=days)).isoformat() def _pct(sorted_vals: list[int], q: float) -> int | None: if not sorted_vals: return None return sorted_vals[min(len(sorted_vals) - 1, int(q * len(sorted_vals)))] def _latest_caps(conn) -> dict[str, dict]: """device_id → props of its newest device_caps (all time: a device's spec does not expire).""" latest: dict[str, dict] = {} for e in _events(conn, ("device_caps",)): if e["device_id"]: latest[e["device_id"]] = e["props"] | {"_at": e["at"]} return latest def _tier_key(caps: dict | None) -> str: t = (caps or {}).get("tier") return str(t) if isinstance(t, int) else "?" def device_summary(days: int = 30, now: datetime | None = None, exclude_test: bool = False) -> dict: """D-25 five aggregates over the last `days` (tier distribution covers devices seen in the window).""" since = _since(days, now) excl = _excl(exclude_test) with db.read_connection() as conn: caps = _latest_caps(conn) turns = [e for e in _events(conn, ("chat_turn",), since) if e["device_id"] not in excl] downloads = [e for e in _events(conn, ("model_download",), since) if e["device_id"] not in excl] recent_caps = [e for e in _events(conn, ("device_caps",), since) if e["device_id"] not in excl] active = {e["device_id"] for e in recent_caps + turns if e["device_id"]} tiers = Counter(_tier_key(caps.get(d)) for d in active) routes = Counter(e["props"].get("route") for e in turns if e["props"].get("route") in ("LOCAL", "API")) ttft = sorted(e["props"]["ttft_ms"] for e in turns if e["props"]["route"] == "LOCAL" and e["props"]["ttft_ms"] is not None) buckets = {name: 0 for name, _ in TTFT_BUCKETS} for v in ttft: buckets[next(name for name, hi in TTFT_BUCKETS if hi is None or v < hi)] += 1 by_tier: dict[str, list[int]] = {} for e in turns: p = e["props"] if p["route"] == "LOCAL" and p["ttft_ms"] is not None: by_tier.setdefault(_tier_key(caps.get(e["device_id"])), []).append(p["ttft_ms"]) reasons = Counter(e["props"]["downgrade_reason"] for e in turns + recent_caps if e["props"].get("downgrade_reason")) gen = [e for e in downloads if (e["props"]["role"] or "generator") == "generator"] started = {e["device_id"] for e in gen if e["props"].get("action") == "start"} done = {e["device_id"] for e in gen if e["props"].get("action") == "done"} & started n_routes = routes["LOCAL"] + routes["API"] kinds = Counter((caps.get(d) or {}).get("local_kind") or "?" for d in active) local_turns = [e["props"] for e in turns if e["props"].get("route") == "LOCAL"] return { "days": days, "devices": len(active), "tiers": dict(sorted(tiers.items())), "routes": {"LOCAL": routes["LOCAL"], "API": routes["API"]}, "local_ratio": round(routes["LOCAL"] / n_routes, 3) if n_routes else None, # P5 (FR-LITE-12): devices by on-device mode; LOCAL turns by mode; LITE number-guard trips; handbook last layer "local_kinds": dict(sorted(kinds.items())), "local_turns_by_kind": dict(sorted(Counter(p.get("local_kind") or "full" for p in local_turns).items())), "lite_guard_trips": sum(1 for p in local_turns if p.get("lite_guard_tripped")), "last_resort": sum(1 for p in local_turns if p.get("last_resort")), "ttft": {"n": len(ttft), "p50": _pct(ttft, 0.5), "p90": _pct(ttft, 0.9), "buckets": buckets}, "ttft_by_tier": {t: {"n": len(v), "p50": _pct(sorted(v), 0.5)} for t, v in sorted(by_tier.items())}, "downgrade_top": [{"reason": r, "n": n} for r, n in reasons.most_common(5)], "download": {"started": len(started), "done": len(done), "rate": round(len(done) / len(started), 3) if started else None}, # 2026-11-18: is anyone using 今日 / 豬場? (fixed 7 / 30-day windows, independent of `days`) "feature_usage": feature_usage(now, excl), # guardrail-registry b3 (FR-RAIL-07): chat turns per fired rail id (each id once per turn), most frequent first "rails_fired_counts": dict(Counter(rid for e in turns for rid in e["props"].get("rails_fired", [])).most_common()), } def device_list(q: str = "", tier: str = "", exclude_test: bool = False) -> list[dict]: """One row per device that ever sent telemetry or registered (FR-TELE-10).""" with db.read_connection() as conn: caps = _latest_caps(conn) turns = _events(conn, ("chat_turn",)) last_tel = dict(conn.execute(select(telemetry_events.c.device_id, func.max(telemetry_events.c.received_at)) .group_by(telemetry_events.c.device_id)).all()) registered = dict(conn.execute(select(devices.c.device_id, devices.c.last_seen)).all()) n_cases = dict(conn.execute(select(cases.c.device_id, func.count()).where(cases.c.hidden == 0) .group_by(cases.c.device_id)).all()) per: dict[str, dict] = {} for e in turns: d = per.setdefault(e["device_id"], {"turns": 0, "local": 0, "down": None, "down_at": None}) d["turns"] += 1 d["local"] += e["props"].get("route") == "LOCAL" if e["props"].get("downgrade_reason"): d["down"], d["down_at"] = e["props"]["downgrade_reason"], e["at"] from app.account import masked_accounts acc = masked_accounts() flags = test_flags() rows = [] for did in set(caps) | set(registered) | set(last_tel): if not did: continue c = caps.get(did, {}) t = per.get(did, {"turns": 0, "local": 0, "down": None, "down_at": None}) down, down_at = t["down"], t["down_at"] if c.get("downgrade_reason") and (down_at is None or c["_at"] > down_at): down, down_at = c["downgrade_reason"], c["_at"] rows.append({ "device_id": did, "short": did[:8], "model": c.get("model"), "total_mem_gb": c.get("total_mem_gb"), "tier": c.get("tier"), "app_version": c.get("app_version"), "last_seen": max(filter(None, (last_tel.get(did), registered.get(did))), default=None), "cases": n_cases.get(did, 0), "turns": t["turns"], "local_ratio": round(t["local"] / t["turns"], 3) if t["turns"] else None, "last_downgrade": down, "last_downgrade_at": down_at, "account": acc.get(did), # {email_masked, devices} | None (FR-ACC-04: never the full email) # admin-refresh FR-TELE-22: admin flag + a suggestion that is never written automatically "test": bool(flags.get(did, {}).get("test")), "test_note": flags.get(did, {}).get("note"), "test_suggested": suggest_test(c.get("model")), }) ql = q.strip().lower() if ql: rows = [r for r in rows if r["device_id"].lower().startswith(ql) or ql in (r["model"] or "").lower()] if tier != "": rows = [r for r in rows if str(r["tier"]) == tier] if exclude_test: rows = [r for r in rows if not r["test"]] return sorted(rows, key=lambda r: r["last_seen"] or "", reverse=True) def conv_meta() -> dict[tuple, dict]: """(session_id, conv_id) → {origin of the first row, sorted assistant routes} for the sessions filter (FR-TELE-12).""" meta: dict[tuple, dict] = {} with db.read_connection() as conn: for r in conn.execute(select(messages.c.session_id, messages.c.conv_id, messages.c.origin, messages.c.role, messages.c.route).order_by(messages.c.ts)): m = meta.setdefault((r.session_id, r.conv_id), {"origin": r.origin or "web", "routes": set()}) if r.role == "assistant": m["routes"].add(r.route or "API") return {k: {"origin": v["origin"], "routes": sorted(v["routes"])} for k, v in meta.items()} # ── P3-A: case page, last 7 days, 👎 handling (docs/11 §8.7; TEL-05/07/08) ───────────────────────────────────── TPE = timezone(timedelta(hours=8)) def _json_field(v): try: return json.loads(v) if isinstance(v, str) and v else v except ValueError: return v def case_detail(case_id: str) -> dict | None: """Everything about one App case for the admin (TEL-05). Exact GPS never leaves the DB (TEL-01).""" from app.db import feedback, images with db.read_connection() as conn: row = conn.execute(select(cases).where(cases.c.case_id == case_id)).mappings().first() if row is None: return None imgs = conn.execute(select(*[c for c in images.c if c.name not in ("lat", "lon")]) .where(images.c.case_id == case_id).order_by(images.c.ts)).mappings().all() msgs = conn.execute(select(messages).where(messages.c.case_id == case_id).order_by(messages.c.ts)).mappings().all() fbs = conn.execute(select(feedback).where(feedback.c.case_id == case_id)).mappings().all() c = dict(row) for k in ("questionnaire_answers", "rapid_test"): c[k] = _json_field(c.get(k)) dev = next((d for d in device_list() if d["device_id"] == c["device_id"]), None) return {"case": c, "images": [dict(i) for i in imgs], "messages": [dict(m) for m in msgs], "feedback": [dict(f) for f in fbs], "device": dev} def daily_stats(days: int = 7, now: datetime | None = None, exclude_test: bool = False) -> dict: """Per Taipei day, oldest first, missing days as 0 (TEL-07) + the unreviewed 👎 count (TEL-08).""" from app.db import feedback, images now = now or datetime.now(timezone.utc) today = now.astimezone(TPE).replace(hour=0, minute=0, second=0, microsecond=0) start = today - timedelta(days=days - 1) utc = lambda d: d.astimezone(timezone.utc).replace(tzinfo=None).isoformat() # noqa: E731 def bucket(conn, col, *where) -> Counter: out: Counter = Counter() for (ts,) in conn.execute(select(col).where(col >= utc(start), *where)): try: t = datetime.fromisoformat(str(ts).replace("Z", "+00:00")) except ValueError: continue t = t if t.tzinfo else t.replace(tzinfo=timezone.utc) out[t.astimezone(TPE).date().isoformat()] += 1 return out excl = list(_excl(exclude_test)) not_test = lambda col: col.is_(None) | col.notin_(excl) # noqa: E731 xc = [not_test(cases.c.device_id)] if excl else [] xm = [not_test(messages.c.device_id), not_test(messages.c.session_id)] if excl else [] xi = [not_test(images.c.device_id)] if excl else [] xf = [not_test(feedback.c.device_id), not_test(feedback.c.session_id)] if excl else [] with db.read_connection() as conn: n_cases = bucket(conn, cases.c.created_at, cases.c.hidden == 0, *xc) n_msgs = bucket(conn, messages.c.ts, *xm) n_imgs = bucket(conn, images.c.ts, *xi) n_down = bucket(conn, feedback.c.ts, feedback.c.rating == "down", *xf) unreviewed = conn.scalar(select(func.count()).select_from(feedback).where( feedback.c.rating == "down", feedback.c.reviewed_at.is_(None), *xf)) or 0 rows = [] for i in range(days): d = (start + timedelta(days=i)).date().isoformat() rows.append({"day": d, "cases": n_cases[d], "messages": n_msgs[d], "images": n_imgs[d], "down": n_down[d]}) return {"days": rows, "unreviewed_down": unreviewed} def feedback_rows(exclude_test: bool = False) -> list[dict]: """Legacy feedback rows + the rated answer and the question before it (TEL-08).""" from app.db import feedback excl = _excl(exclude_test) with db.read_connection() as conn: fbs = [dict(r) for r in conn.execute(select(feedback).order_by(feedback.c.ts.desc())).mappings()] fbs = [f for f in fbs if f.get("device_id") not in excl and f.get("session_id") not in excl] if excl else fbs ids = [f["msg_id"] for f in fbs if f.get("msg_id")] answers = {r.msg_id: r for r in conn.execute( select(messages.c.msg_id, messages.c.conv_id, messages.c.content, messages.c.ts).where(messages.c.msg_id.in_(ids)))} out = [] for f in fbs: a = answers.get(f.get("msg_id")) q = None if a is not None: q = conn.execute(select(messages.c.content).where( messages.c.conv_id == a.conv_id, messages.c.role == "user", messages.c.ts <= a.ts) .order_by(messages.c.ts.desc()).limit(1)).scalar() out.append(f | {"answer": a.content[:300] if a is not None else None, "question": q[:200] if q else None, "level": reply_level(a.content) if a is not None else None}) return out def review_feedback(fb_id: str, note: str | None, unreview: bool = False) -> bool: from app.db import feedback, now_iso from sqlalchemy import update vals = {"reviewed_at": None, "review_note": None} if unreview else {"reviewed_at": now_iso(), "review_note": (note or "")[:500]} with db.engine().begin() as conn: return conn.execute(update(feedback).where(feedback.c.fb_id == fb_id).values(**vals)).rowcount == 1 # ── admin-refresh (2026-11-19, docs/11 §8.7a; openspec admin-refresh FR-TELE-20~24) ───────────────────────────── from app.generated.prompt_source import FIXED_REPLIES, TRIGGER_MESSAGE # noqa: E402 # reply text → answer level (design D1). Order matters only where one sentence prefixes another (none today). _LEVEL_KEYS: tuple[tuple[str, tuple[str, ...]], ...] = ( ("error", ("error_internal", "error_llm_unavailable", "error_image_service", "daily_cap", "legacy_daily_cap_v1", "rate_limit_line")), # c6: LINE rate limit (sent, never stored today) ("cloud_off", ("cloud_off", "cloud_off_unsupported")), ("blocked", ("jailbreak", "out_of_scope", "identity")), ("L3", ("local_refuse", "legacy_local_refuse_v1", "legacy_local_refuse_v2", "ladder_guide")), ("L2", ("manual_maybe_notice",)), ("chitchat", ("ladder_chitchat",)), ("rule", ("report_notice",) + tuple(k for k in FIXED_REPLIES if k.startswith("local_rule_"))), ("L1", ("manual_only_notice", "lite_guard_notice", "legacy_lite_guard_notice_v1", "legacy_lite_guard_notice_v2", "legacy_manual_only_notice_v1", "legacy_manual_only_notice_v2", "legacy_manual_only_notice_v3")), ) _LEVEL_PREFIXES: list[tuple[str, str]] = sorted( ((FIXED_REPLIES[k].strip(), lvl) for lvl, keys in _LEVEL_KEYS for k in keys if FIXED_REPLIES.get(k, "").strip()), key=lambda x: -len(x[0])) # longest first: cloud_off_unsupported before cloud_off LEVELS = ("answer", "L1", "L2", "L3", "rule", "chitchat", "blocked", "cloud_off", "error") LEVEL_EXEMPT = ("contact_suffix_",) # suffixes appended to an error reply, never a reply on their own ANSWERED = ("answer", "L1", "L2", "rule") def reply_level(content: str | None) -> str: t = (content or "").strip() for prefix, lvl in _LEVEL_PREFIXES: if t.startswith(prefix): return lvl return "answer" # test devices (design D2): an admin flag, never automatic; suggestions are only shown _SUGGEST = (("sdk_gphone", "模擬器"), ("android sdk built for", "模擬器"), ("emulator", "模擬器"), ("generic", "模擬器"), ("sm-x730", "開發平板 Tab S11")) def suggest_test(model: str | None) -> str | None: m = (model or "").lower() return next((why for pat, why in _SUGGEST if (m.startswith(pat) if pat == "sm-x730" else pat in m)), None) def test_flags() -> dict[str, dict]: from app.db import admin_device_flags as f with db.read_connection() as conn: return {r.device_id: {"test": bool(r.test), "note": r.note, "updated_at": r.updated_at} for r in conn.execute(select(f))} def test_device_ids() -> set[str]: return {d for d, v in test_flags().items() if v["test"]} def set_test_device(device_id: str, test: bool, note: str | None = None) -> None: from app.db import admin_device_flags as f, now_iso from sqlalchemy import delete, insert with db.engine().begin() as conn: conn.execute(delete(f).where(f.c.device_id == device_id)) if test: conn.execute(insert(f).values(device_id=device_id, test=1, note=(note or "")[:200], updated_at=now_iso())) def _excl(exclude_test: bool) -> set[str]: return test_device_ids() if exclude_test else set() def _parse(ts) -> datetime | None: try: t = datetime.fromisoformat(str(ts).replace("Z", "+00:00")) except (TypeError, ValueError): return None return t if t.tzinfo else t.replace(tzinfo=timezone.utc) def _naive(t: datetime) -> str: return t.astimezone(timezone.utc).replace(tzinfo=None).isoformat() def _msg_device(r) -> str | None: return r.device_id or (r.session_id if r.origin == "app" else None) def _window(rows: list[dict], start: datetime, end: datetime | None = None) -> list[dict]: """Rows with start <= t < end (end = end of the Taipei day: future-dated rows never count as "today").""" return [r for r in rows if r["t"] is not None and r["t"] >= start and (end is None or r["t"] < end)] def overview(now: datetime | None = None, exclude_test: bool = False) -> dict: """First screen (FR-TELE-21): today (Taipei) and the last 7 Taipei days, plus what needs attention.""" from app.db import feedback, images, service_errors now = now or datetime.now(timezone.utc) today0 = now.astimezone(TPE).replace(hour=0, minute=0, second=0, microsecond=0) start7 = today0 - timedelta(days=6) lo = _naive(start7 - timedelta(days=1)) # coarse SQL bound; exact filtering after parsing flags = test_flags() # once per request (review 2026-11-19 nit) excl = {d for d, v in flags.items() if v["test"]} if exclude_test else set() with db.read_connection() as conn: msgs = [{"dev": _msg_device(r), "sid": r.session_id, "role": r.role, "content": r.content, # images: App photos are counted from `images` below (they may arrive only via sync, local ONNX); # the legacy Web image row is the only record of a Web photo (review 2026-11-19 S1) "img": r.has_image == 1 and not (r.msg_id or "").startswith("img-"), "t": _parse(r.ts)} for r in conn.execute(select(messages.c.msg_id, messages.c.device_id, messages.c.session_id, messages.c.origin, messages.c.role, messages.c.content, messages.c.has_image, messages.c.ts) .where(messages.c.ts >= lo))] app_imgs = [{"dev": r.device_id, "t": _parse(r.ts)} for r in conn.execute( select(images.c.device_id, images.c.ts).where(images.c.ts >= lo, images.c.hidden == 0))] tel = [{"dev": r.device_id, "t": _parse(r.received_at)} for r in conn.execute( select(telemetry_events.c.device_id, telemetry_events.c.received_at).where(telemetry_events.c.received_at >= lo))] feats = _events(conn, FEATURE_EVENTS + ("app_start",), lo) new_devs = [{"dev": r.device_id, "t": _parse(r.created_at)} for r in conn.execute( select(devices.c.device_id, devices.c.created_at).where(devices.c.created_at >= lo))] downs = [{"dev": r.device_id or r.session_id, "t": _parse(r.ts)} for r in conn.execute( select(feedback.c.device_id, feedback.c.session_id, feedback.c.ts) .where(feedback.c.rating == "down", feedback.c.ts >= lo))] unrev = [r.device_id or r.session_id for r in conn.execute( select(feedback.c.device_id, feedback.c.session_id).where(feedback.c.rating == "down", feedback.c.reviewed_at.is_(None)))] errs = [{"t": _parse(r.ts)} for r in conn.execute(select(service_errors.c.ts).where(service_errors.c.ts >= lo))] all_devs = [r.device_id for r in conn.execute(select(devices.c.device_id))] keep = lambda d: d not in excl # noqa: E731 msgs = [m for m in msgs if keep(m["dev"]) and keep(m["sid"])] tel = [e for e in tel if e["dev"] and keep(e["dev"])] feats = [e for e in feats if keep(e["device_id"])] new_devs = [e for e in new_devs if keep(e["dev"])] downs = [e for e in downs if keep(e["dev"])] app_imgs = [e for e in app_imgs if keep(e["dev"])] for e in feats: e["t"] = _parse(e["at"]) day_end = today0 + timedelta(days=1) def win(start: datetime) -> dict: _w = lambda rows: _window(rows, start, day_end) # noqa: E731 m = _w(msgs) replies = Counter(reply_level(x["content"]) for x in m if x["role"] == "assistant") answered = sum(replies[k] for k in ANSWERED) active = {x["dev"] for x in m if x["dev"]} | {e["dev"] for e in _w(tel)} f = [e for e in _w(feats) if e["device_id"]] return { "new_devices": len(_w(new_devs)), "active_devices": len(active), "questions": sum(1 for x in m if x["role"] == "user" and (x["content"] or "").strip() != TRIGGER_MESSAGE), "replies": {k: replies[k] for k in LEVELS}, "answered": answered, "l3_rate": round(replies["L3"] / (answered + replies["L3"]), 3) if answered + replies["L3"] else None, "images": sum(1 for x in m if x["img"]) + len(_w(app_imgs)), "down": len(_w(downs)), "errors": len(_w(errs)), "feature": {name: {"n": sum(1 for e in f if e["event"] == name), "devices": len({e["device_id"] for e in f if e["event"] == name})} for name in FEATURE_EVENTS}, } daily = [] for i in range(7): d0 = start7 + timedelta(days=i) d1 = d0 + timedelta(days=1) inday = lambda t: t is not None and d0 <= t < d1 # noqa: E731 dm = [x for x in msgs if inday(x["t"])] daily.append({ "day": d0.date().isoformat(), "active_devices": len({x["dev"] for x in dm if x["dev"]} | {e["dev"] for e in tel if inday(e["t"])}), "questions": sum(1 for x in dm if x["role"] == "user" and (x["content"] or "").strip() != TRIGGER_MESSAGE), "l3": sum(1 for x in dm if x["role"] == "assistant" and reply_level(x["content"]) == "L3"), "down": sum(1 for e in downs if inday(e["t"])), }) caps = _all_caps_models() suggested = sum(1 for d in set(all_devs) | set(caps) if d and not flags.get(d, {}).get("test") and suggest_test(caps.get(d))) return { "generated_at": _naive(now), "exclude_test": exclude_test, "windows": {"today": win(today0), "7d": win(start7)}, "daily": daily, "unreviewed_down": sum(1 for d in unrev if keep(d)), "backup": _backup_view(), "cloud": _cloud_view(), "test_devices": sum(1 for v in flags.values() if v["test"]), "test_suggested": suggested, } def _all_caps_models() -> dict[str, str | None]: with db.read_connection() as conn: return {d: c.get("model") for d, c in _latest_caps(conn).items()} def _backup_view() -> dict: try: from app import notify from app.backup import status st = status() settled = datetime.now(timezone.utc) - notify._STARTED > notify.RESTORE_GRACE except Exception: # noqa: BLE001 — the page still renders return {"warn": "讀取失敗"} warn = ("備份 dataset 是公開的" if st.get("repo_public") else "開機還原失敗:請重新部署,不要按立即推送" if st.get("restore_failed") else "備份衝突,已停推" if st.get("conflict") else "備份未啟用" if (st.get("repo") and st.get("push_enabled") is False and settled) else "未設定備份" if not st.get("repo") else None) return {"last_sync": st.get("last_sync"), "dirty": st.get("dirty"), "conflict": bool(st.get("conflict")), "push_enabled": st.get("push_enabled"), "warn": warn} def _cloud_view() -> dict: try: from app import cloud_switch s = cloud_switch.state() return {"enabled": s.get("enabled") is True, "until": s.get("until")} except Exception: # noqa: BLE001 return {"enabled": False, "until": None} def _turn_passages(conn, since: str) -> dict[str, list[tuple[datetime, int]]]: """case_id → [(client time, len(passage_ids))] of chat_turn events that carry passage_ids (design D1).""" out: dict[str, list[tuple[datetime, int]]] = {} for r in conn.execute(select(telemetry_events.c.props, telemetry_events.c.client_ts, telemetry_events.c.received_at) .where(telemetry_events.c.event == "chat_turn", telemetry_events.c.received_at >= since)): try: p = json.loads(r.props or "{}") except ValueError: continue if not isinstance(p, dict) or not isinstance(p.get("case_id"), str) or not isinstance(p.get("passage_ids"), list): continue t = _parse(r.client_ts) or _parse(r.received_at) if t is not None: out.setdefault(p["case_id"], []).append((t, len(p["passage_ids"]))) return out _IMG_REF = re.compile(r"\[圖片 ([A-Za-z0-9_-]{1,64})\]") def _img_id(r) -> str | None: if (r.msg_id or "").startswith("img-"): return r.msg_id[4:] m = _IMG_REF.match(r.content or "") return m.group(1) if m else None def questions(days: int = 7, level: str = "", origin: str = "", exclude_test: bool = False, limit: int = 200, now: datetime | None = None, today: bool = False) -> list[dict]: """One row per user question with its reply's level, plus one row per photo (level `image`) so image-only conversations stay reachable (FR-TELE-23; review 2026-11-19 S4). today=True → since Taipei 00:00 (S6).""" now = now or datetime.now(timezone.utc) since = (now.astimezone(TPE).replace(hour=0, minute=0, second=0, microsecond=0) if today else now - timedelta(days=days)) tests = test_device_ids() excl = tests if exclude_test else set() with db.read_connection() as conn: rows = list(conn.execute( select(messages.c.msg_id, messages.c.session_id, messages.c.conv_id, messages.c.role, messages.c.content, messages.c.ts, messages.c.device_id, messages.c.case_id, messages.c.route, messages.c.origin, messages.c.img_class, messages.c.img_prob) .where(messages.c.ts >= _naive(since - timedelta(days=1)), messages.c.role.in_(("user", "assistant", "image"))) .order_by(messages.c.ts))) turns = _turn_passages(conn, _naive(since - timedelta(days=2))) caps = {d: c.get("model") for d, c in _latest_caps(conn).items()} convs: dict[tuple, list] = {} for r in rows: convs.setdefault((r.session_id, r.conv_id), []).append(r) out = [] for seq in convs.values(): for i, r in enumerate(seq): t = _parse(r.ts) if r.role == "assistant" or t is None or t < since or (r.content or "").strip() == TRIGGER_MESSAGE: continue dev = _msg_device(r) if (dev and dev in excl) or r.session_id in excl: continue o = r.origin or "web" if origin and o != origin: continue if r.role == "image": if level and level != "image": continue try: p = f" {round(float(r.img_prob) * 100)}%" except (TypeError, ValueError): p = "" out.append({ "ts": r.ts, "origin": o, "device": (dev or "")[:8] or None, "model": caps.get(dev) if dev else None, "conv_id": r.conv_id, "case_id": r.case_id, "msg_id": r.msg_id, "img_id": _img_id(r), "question": f"[影像] {r.img_class or '—'}{p}", "answer": None, "level": "image", "route": None, "passages": None, "test": bool(dev and dev in tests)}) continue a = next((x for x in seq[i + 1:] if x.role in ("assistant", "user")), None) a = a if a is not None and a.role == "assistant" else None lvl = reply_level(a.content) if a is not None else "none" if level and lvl != level: continue passages = None if a is not None and r.case_id and (at := _parse(a.ts)) is not None: near = [(abs((tt - at).total_seconds()), n) for tt, n in turns.get(r.case_id, [])] near = [x for x in near if x[0] <= 300] passages = min(near)[1] if near else None out.append({ "ts": r.ts, "origin": o, "device": (dev or "")[:8] or None, "model": caps.get(dev) if dev else None, "conv_id": r.conv_id, "case_id": r.case_id, "msg_id": a.msg_id if a is not None else None, "question": (r.content or "")[:200], "answer": (a.content or "")[:240] if a is not None else None, "level": lvl, "route": (a.route or "API") if a is not None else None, "passages": passages, "test": bool(dev and dev in tests), "img_id": None, }) out.sort(key=lambda x: _parse(x["ts"]) or since, reverse=True) return out[:limit] def image_meta() -> dict[str, dict]: """img_id → {cls, prob, case_id, device_id} for the admin image grid (§8.7a); never lat / lon.""" from app.db import images with db.read_connection() as conn: return {r["img_id"]: {"cls": r["class"], "prob": r["prob"], "case_id": r["case_id"], "device_id": r["device_id"]} for r in conn.execute(select(images.c.img_id, images.c["class"], images.c.prob, images.c.case_id, images.c.device_id)).mappings()}