DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(home): generate starter suggestions from memory
Bingxi Zhao (Frank)7229ef1d3215
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.pyindex ee32e4f68..28ef5a074 100644--- a/deeptutor/api/routers/dashboard.py+++ b/deeptutor/api/routers/dashboard.py@@ -1,8 +1,16 @@-"""Dashboard API backed by the unified SQLite session store."""+"""Dashboard API — what the home screen shows before a conversation starts.++Recent activity comes from the unified SQLite session store; the starter chips+come from :mod:`deeptutor.services.suggestions`, which reads memory.++Route order matters here: ``/{entry_id}`` at the bottom of this module matches+any single segment, so every literal path must be declared above it or it will+never be reached.+"""from typing import Any-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Queryfrom deeptutor.services.session import get_session_store@@ -38,6 +46,33 @@ async def get_recent_activities(limit: int = 50, type: str | None = None):return activities[:limit][email protected]("/suggestions")+async def get_starter_suggestions(language: str = Query(default="en")):+ """The three starter chips for the home composer.++ Returns immediately, even when the set is stale — regeneration happens+ behind the response. An empty ``suggestions`` list means there is nothing+ in memory to ground a suggestion in; the client shows its own fixed+ starters then. See :mod:`deeptutor.services.suggestions`.+ """+ from deeptutor.services.suggestions import get_suggestions++ return await get_suggestions(language)++[email protected]("/suggestions/refresh")+async def refresh_starter_suggestions(language: str = Query(default="en")):+ """Generate a new set now. Backs the reroll control.++ Synchronous, unlike the read: a human clicked and is waiting for a+ different set.+ """+ from deeptutor.services.suggestions import refresh_suggestions++ result = await refresh_suggestions(language)+ return {**result.to_dict(), "stale": False}++@router.get("/{entry_id}")async def get_activity_entry(entry_id: str):store = get_session_store()diff --git a/deeptutor/services/suggestions.py b/deeptutor/services/suggestions.pynew file mode 100644index 000000000..1b53fa451--- /dev/null+++ b/deeptutor/services/suggestions.py@@ -0,0 +1,468 @@+"""Starter suggestions — the three chips under the home composer.++Each chip is two strings that do different jobs. ``label`` is what the learner+reads: a few words, sized for a chip. ``prompt`` is what gets *sent as their+own message* when they click, so it has to be first-person, complete, and+specific enough to answer — "把我上次做错的那道链式法则的题再讲一遍", not+"你上次在学链式法则", which a model can only agree with.++Never on the request path+-------------------------+An LLM call is far too slow to sit between a click and a rendered page. So+reads are stale-while-revalidate: :func:`get_suggestions` returns whatever is+cached immediately — even if stale, even if empty — and schedules the work+behind the response. The next visit gets the new set.++Reading the cache is the *only* thing that happens synchronously: one small+JSON file. Deciding whether the material changed means walking seven surfaces,+which is cheap but not free, so that decision lives in the background task+too, throttled to at most once a minute per user.++When it regenerates+-------------------+The background pass regenerates when the material changed (a fingerprint over+the labels) or when the set is older than :data:`_TTL_SECONDS` — the first is+when the *content* should change, the second is so the same three chips do not+greet someone all week. A manual refresh bypasses both and generates+synchronously, because there a human is deliberately waiting.++Empty is a valid answer. A learner with no history gets no generated chips and+no LLM call; the frontend shows a fixed set of product starters instead, which+is honest about knowing nothing yet.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+import hashlib+import json+import logging+import time+from typing import Any++logger = logging.getLogger(__name__)++# How many chips the home screen shows. Fewer than three looks like a bug;+# more crowds the composer.+_COUNT = 3+# Long enough that the same three chips are not re-generated all afternoon,+# short enough to feel responsive to a day's work.+_TTL_SECONDS = 6 * 3600+# Floor between two background material checks for one user. Page loads can+# come in bursts (navigation, refresh, a second tab); the material cannot+# meaningfully change that fast.+_PROBE_INTERVAL_SECONDS = 60.0+_LLM_TIMEOUT = 25.0+# How much history shapes the chips.+_LOOKBACK_DAYS = 7+_MAX_TOPICS = 8+# Per surface, so three chats cannot crowd out the quiz and the KB. The whole+# point of reading every surface is that the chips differ in kind.+_MAX_PER_SURFACE = 2+# A chip's text, and the message behind it. Over-long output means the model+# ignored the brief; the item is dropped rather than truncated, because half a+# sentence is worse than one fewer chip.+_MAX_LABEL_CHARS = 40+_MAX_PROMPT_CHARS = 240++# One in-flight regeneration per scope; a burst of page loads must not fan out+# into a burst of LLM calls.+_inflight: dict[str, asyncio.Task[Any]] = {}+# Last time a scope's material was checked, for the throttle above. In-process+# only: losing it on restart costs one extra walk.+_last_probe: dict[str, float] = {}+++@dataclass(frozen=True, slots=True)+class Suggestion:+ """One chip: what it says, and what it sends."""++ label: str+ prompt: str++ def to_dict(self) -> dict[str, str]:+ return {"label": self.label, "prompt": self.prompt}+++@dataclass(frozen=True, slots=True)+class SuggestionSet:+ """The chips currently on offer, plus what they were generated from."""++ suggestions: tuple[Suggestion, ...]+ language: str+ generated_at: float+ fingerprint: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "suggestions": [item.to_dict() for item in self.suggestions],+ "language": self.language,+ "generated_at": self.generated_at,+ "fingerprint": self.fingerprint,+ }+++# ── Cache ────────────────────────────────────────────────────────────────+++def _cache_path():+ from deeptutor.services.path_service import get_path_service++ directory = get_path_service().get_workspace_dir() / "suggestions"+ directory.mkdir(parents=True, exist_ok=True)+ return directory / "starters.json"+++def _scope_key() -> str:+ """Identifies whose suggestions these are.++ The cache path already resolves per user through the multi-user path+ service, so it doubles as the scope key for the in-flight and throttle+ maps — no separate notion of identity to keep in sync with the one that+ decides where the file lands.+ """+ try:+ return str(_cache_path())+ except Exception: # pragma: no cover - defensive+ return "<unresolved>"+++def _load() -> SuggestionSet | None:+ try:+ path = _cache_path()+ if not path.exists():+ return None+ raw = json.loads(path.read_text(encoding="utf-8"))+ items = tuple(+ Suggestion(label=str(item["label"]), prompt=str(item["prompt"]))+ for item in (raw.get("suggestions") or [])+ if isinstance(item, dict) and item.get("label") and item.get("prompt")+ )+ return SuggestionSet(+ suggestions=items,+ language=str(raw.get("language") or "en"),+ generated_at=float(raw.get("generated_at") or 0.0),+ fingerprint=str(raw.get("fingerprint") or ""),+ )+ except Exception:+ logger.debug("suggestions cache unreadable", exc_info=True)+ return None+++def _save(value: SuggestionSet) -> None:+ try:+ path = _cache_path()+ tmp = path.with_suffix(".json.tmp")+ tmp.write_text(+ json.dumps(value.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ tmp.replace(path)+ except Exception:+ logger.debug("suggestions cache unwritable", exc_info=True)+++# ── Material ─────────────────────────────────────────────────────────────++# What each surface is called when it is described to the model. Deliberately+# the learner's vocabulary, not the codebase's: "错题" is a thing a learner+# recognises, "quiz surface" is not.+_SURFACE_LABELS_EN: dict[str, str] = {+ "chat": "conversation",+ "quiz": "practice question",+ "notebook": "note",+ "kb": "knowledge base",+ "book": "book",+ "cowriter": "document",+ "partner": "conversation",+}+_SURFACE_LABELS_ZH: dict[str, str] = {+ "chat": "对话",+ "quiz": "错题",+ "notebook": "笔记",+ "kb": "知识库",+ "book": "书",+ "cowriter": "文档",+ "partner": "对话",+}+++@dataclass(frozen=True, slots=True)+class _Topic:+ surface: str+ label: str+ days_ago: int | None+++def _collect_topics() -> list[_Topic]:+ """Recent activity, spread across surfaces rather than dominated by one.++ Chat updates on every turn, so a plain newest-first list is almost all+ chat. Taking a bounded number per surface and interleaving them is what+ makes three chips of three different kinds possible.+ """+ from deeptutor.services.memory import recall++ by_surface: dict[str, list[_Topic]] = {}++ def _add(surface: str, label: str, age: int | None) -> None:+ bucket = by_surface.setdefault(surface, [])+ if len(bucket) >= _MAX_PER_SURFACE:+ return+ if any(existing.label.casefold() == label.casefold() for existing in bucket):+ return+ bucket.append(_Topic(surface=surface, label=label, days_ago=age))++ try:+ for hit in recall.recent(days=_LOOKBACK_DAYS, limit=_MAX_TOPICS * 4):+ _add(hit.surface, hit.label, hit.days_ago)+ except Exception:+ logger.debug("suggestions: recall.recent failed", exc_info=True)++ try:+ for hit in recall.recent_queries(days=_LOOKBACK_DAYS, limit=_MAX_TOPICS):+ _add(hit.surface, hit.label, hit.days_ago)+ except Exception:+ logger.debug("suggestions: recall.recent_queries failed", exc_info=True)++ # Round-robin across surfaces: every kind gets its first item before any+ # kind gets its second.+ topics: list[_Topic] = []+ for rank in range(_MAX_PER_SURFACE):+ for bucket in by_surface.values():+ if rank < len(bucket):+ topics.append(bucket[rank])+ return topics[:_MAX_TOPICS]+++def _fingerprint(topics: list[_Topic], language: str) -> str:+ digest = hashlib.sha1(usedforsecurity=False)+ digest.update(language.encode("utf-8"))+ for topic in topics:+ digest.update(b"\0")+ digest.update(f"{topic.surface}:{topic.label}".encode("utf-8"))+ return digest.hexdigest()[:16]+++# ── Generation ───────────────────────────────────────────────────────────+++_SYSTEM_EN = """You write the three starter chips a learning app shows under its composer.++Each chip is an object with two fields:+- "label": what the learner sees on the chip. Under 6 words, no ending punctuation. A short noun phrase or imperative, not a sentence.+- "prompt": the message sent as the learner's own words when they click. First person, complete, specific enough to answer directly.++Rules:+- Reply with ONLY a JSON array of exactly 3 such objects. No prose, no markdown fence.+- Ground every chip in the material given. Name the actual topic; never invent one.+- Make the three differ from each other — different items, and different things to do with them (explain, practise, review, go deeper).+- No greetings, no emoji, no quotes around the fields' text."""++_SYSTEM_ZH = """你要为一个学习应用写出输入框下方的三个引导按钮。++每个按钮是一个对象,含两个字段:+- "label":学习者在按钮上看到的字,不超过 10 个字,结尾不加标点。是短语或祈使句,不是完整句子。+- "prompt":学习者点击后以自己的身份发出的那句话。第一人称、完整、具体到可以直接回答。++规则:+- 只回复一个 JSON 数组,正好 3 个这样的对象。不要有任何解释文字,不要 markdown 代码块。+- 每个按钮都要基于下面给出的素材,点出真实的内容,绝不编造。+- 三个之间要有区别——取不同的素材,也做不同的事(讲解、练习、复习、深入)。+- 不要问候语、不要 emoji、字段文本里不要加引号。"""+++def _is_zh(language: str) -> bool:+ return str(language or "en").lower().startswith("zh")+++def _render_topics(topics: list[_Topic], zh: bool) -> str:+ labels = _SURFACE_LABELS_ZH if zh else _SURFACE_LABELS_EN+ lines: list[str] = []+ for topic in topics:+ kind = labels.get(topic.surface, topic.surface)+ if topic.days_ago is None:+ when = ""+ elif zh:+ when = ",今天" if topic.days_ago == 0 else f",{topic.days_ago} 天前"+ else:+ when = ", today" if topic.days_ago == 0 else f", {topic.days_ago}d ago"+ lines.append(f"- [{kind}{when}] {topic.label}")+ return "\n".join(lines)+++def _sanitize(raw: str) -> tuple[Suggestion, ...]:+ """Exactly :data:`_COUNT` usable chips, or nothing at all.++ Partial output is discarded rather than shown: one lonely chip under the+ composer reads as a rendering bug, and the caller has a fixed set of+ starters that is better than that.+ """+ from deeptutor.utils.json_parser import parse_json_response++ decoded = parse_json_response(raw, fallback=None)+ if not isinstance(decoded, list):+ return ()++ items: list[Suggestion] = []+ seen: set[str] = set()+ for entry in decoded:+ if not isinstance(entry, dict):+ continue+ label = " ".join(str(entry.get("label") or "").split()).strip("\"'“”‘’ ")+ prompt = " ".join(str(entry.get("prompt") or "").split()).strip("\"'“”‘’ ")+ if not label or not prompt:+ continue+ if len(label) > _MAX_LABEL_CHARS or len(prompt) > _MAX_PROMPT_CHARS:+ continue+ if label.casefold() in seen:+ continue+ seen.add(label.casefold())+ items.append(Suggestion(label=label, prompt=prompt))++ return tuple(items[:_COUNT]) if len(items) >= _COUNT else ()+++async def _generate(language: str) -> SuggestionSet:+ """Build a fresh set. Always returns one — empty on any failure."""+ topics = _collect_topics()+ fingerprint = _fingerprint(topics, language)+ empty = SuggestionSet(+ suggestions=(),+ language=language,+ generated_at=time.time(),+ fingerprint=fingerprint,+ )+ if not topics:+ # Nothing to ground a suggestion in. Say so instead of asking a model+ # to invent a learning history.+ return empty++ zh = _is_zh(language)+ user_prompt = (+ f"学习者最近接触的内容:\n{_render_topics(topics, zh)}\n\n请写出那三个按钮。"+ if zh+ else (+ "The learner has recently been working on:\n"+ f"{_render_topics(topics, zh)}\n\nWrite the three chips."+ )+ )++ try:+ from deeptutor.services.llm import complete++ raw = await asyncio.wait_for(+ complete(+ prompt=user_prompt,+ system_prompt=_SYSTEM_ZH if zh else _SYSTEM_EN,+ temperature=0.8, # suggestions may vary; these are not facts+ max_tokens=500,+ ),+ timeout=_LLM_TIMEOUT,+ )+ except asyncio.TimeoutError:+ logger.debug("suggestions LLM call timed out")+ return empty+ except Exception:+ logger.debug("suggestions LLM call failed", exc_info=True)+ return empty++ return SuggestionSet(+ suggestions=_sanitize(raw),+ language=language,+ generated_at=time.time(),+ fingerprint=fingerprint,+ )+++# ── Public API ───────────────────────────────────────────────────────────+++def _is_fresh(cached: SuggestionSet | None, language: str, *, now: float) -> bool:+ return (+ cached is not None+ and cached.language == language+ and now - cached.generated_at <= _TTL_SECONDS+ )+++async def refresh_suggestions(language: str = "en") -> SuggestionSet:+ """Generate a new set now and cache it. For the manual reroll."""+ value = await _generate(language)+ _save(value)+ return value+++async def _regenerate_if_due(language: str) -> None:+ """The background pass: work out whether anything is due, then do it.++ Walking the surfaces to fingerprint the material happens here rather than+ on the request path — the answer only decides whether to spend an LLM call,+ and acting on it one page load later is exactly what stale-while-revalidate+ means.+ """+ topics = _collect_topics()+ fingerprint = _fingerprint(topics, language)+ cached = _load()+ if _is_fresh(cached, language, now=time.time()) and cached.fingerprint == fingerprint:+ return+ await refresh_suggestions(language)+++def _schedule_probe(language: str) -> None:+ """Check (and maybe regenerate) in the background, throttled and deduped."""+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ key = _scope_key()+ now = time.monotonic()+ pending = _inflight.get(key)+ if pending is not None and not pending.done():+ return+ if now - _last_probe.get(key, 0.0) < _PROBE_INTERVAL_SECONDS:+ return+ _last_probe[key] = now++ async def _go() -> None:+ try:+ await _regenerate_if_due(language)+ except Exception:+ logger.debug("background suggestion refresh failed", exc_info=True)+ finally:+ if _inflight.get(key) is task:+ _inflight.pop(key, None)++ task = loop.create_task(_go())+ _inflight[key] = task+++async def get_suggestions(language: str = "en") -> dict[str, Any]:+ """The chips to show now, plus whether a fresher set is being made.++ Returns immediately, reading one small JSON file. An empty list is a real+ answer — a new learner has nothing to suggest from — and ``stale`` tells+ the caller whether it is worth looking again shortly.+ """+ cached = _load()+ fresh = _is_fresh(cached, language, now=time.time())+ _schedule_probe(language)++ if cached is not None and cached.language == language:+ return {**cached.to_dict(), "stale": not fresh}+ return {+ "suggestions": [],+ "language": language,+ "generated_at": 0.0,+ "fingerprint": "",+ "stale": True,+ }+++__all__ = [+ "Suggestion",+ "SuggestionSet",+ "get_suggestions",+ "refresh_suggestions",+]diff --git a/tests/api/test_dashboard_suggestions.py b/tests/api/test_dashboard_suggestions.pynew file mode 100644index 000000000..feb0e0e34--- /dev/null+++ b/tests/api/test_dashboard_suggestions.py@@ -0,0 +1,84 @@+"""Dashboard suggestion endpoints.++The point of these tests is route *order*: ``/{entry_id}`` at the bottom of the+dashboard router matches any single segment, so a literal path declared after+it would silently become a lookup for an activity entry named "suggestions".+"""++from __future__ import annotations++from typing import Any++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.api.routers import dashboard+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(dashboard.router, prefix="/api/v1/dashboard")+ return TestClient(app)+++def test_suggestions_is_not_swallowed_by_the_entry_route(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ import deeptutor.services.suggestions as service++ async def _get(language: str = "en") -> dict[str, Any]:+ return {+ "suggestions": [{"label": "复习链式法则", "prompt": "再讲一遍链式法则"}],+ "language": language,+ "generated_at": 1.0,+ "fingerprint": "abc",+ "stale": False,+ }++ monkeypatch.setattr(service, "get_suggestions", _get)++ response = client.get("/api/v1/dashboard/suggestions", params={"language": "zh"})++ assert response.status_code == 200+ body = response.json()+ assert body["language"] == "zh"+ assert body["suggestions"][0]["label"] == "复习链式法则"+++def test_refresh_returns_a_fresh_set(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ import deeptutor.services.suggestions as service+ from deeptutor.services.suggestions import Suggestion, SuggestionSet++ async def _refresh(language: str = "en") -> SuggestionSet:+ return SuggestionSet(+ suggestions=(Suggestion(label="Practise eigenvalues", prompt="Give me five"),),+ language=language,+ generated_at=2.0,+ fingerprint="def",+ )++ monkeypatch.setattr(service, "refresh_suggestions", _refresh)++ response = client.post("/api/v1/dashboard/suggestions/refresh")++ assert response.status_code == 200+ body = response.json()+ assert body["stale"] is False+ assert body["suggestions"][0]["prompt"] == "Give me five"+++def test_an_actual_entry_id_still_reaches_the_entry_route(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ class _Store:+ async def get_session_with_messages(self, entry_id: str):+ return {"session_id": entry_id, "title": "Chain rule", "capability": "chat"}++ monkeypatch.setattr(dashboard, "get_session_store", lambda: _Store())++ response = client.get("/api/v1/dashboard/sess-123")++ assert response.status_code == 200+ assert response.json()["id"] == "sess-123"diff --git a/tests/services/test_suggestions.py b/tests/services/test_suggestions.pynew file mode 100644index 000000000..b2efd3ef5--- /dev/null+++ b/tests/services/test_suggestions.py@@ -0,0 +1,403 @@+"""Starter suggestions — caching, shaping, and staying off the request path."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+import time++import pytest++from deeptutor.services import suggestions+from deeptutor.services.memory.recall import RecallHit+++class _FakePathService:+ def __init__(self, root: Path) -> None:+ self._root = root++ def get_workspace_dir(self) -> Path:+ return self._root++[email protected](autouse=True)+def isolated_scope(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """Route the cache into tmp_path and clear the in-process maps."""+ import deeptutor.services.path_service as path_service++ monkeypatch.setattr(path_service, "get_path_service", lambda: _FakePathService(tmp_path))+ suggestions._inflight.clear()+ suggestions._last_probe.clear()+ yield tmp_path+ suggestions._inflight.clear()+ suggestions._last_probe.clear()+++def no_material(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.memory import recall++ monkeypatch.setattr(recall, "recent", lambda **_: [])+ monkeypatch.setattr(recall, "recent_queries", lambda **_: [])+++def _hit(surface: str, label: str, age: int = 1) -> RecallHit:+ return RecallHit(surface=surface, label=label, ts="2026-08-15T10:00:00+00:00", days_ago=age)+++def _stub_material(monkeypatch: pytest.MonkeyPatch, hits: list[RecallHit]) -> None:+ from deeptutor.services.memory import recall++ monkeypatch.setattr(recall, "recent", lambda **_: list(hits))+ monkeypatch.setattr(recall, "recent_queries", lambda **_: [])+++def _stub_llm(monkeypatch: pytest.MonkeyPatch, reply: str) -> list[str]:+ """Replace the LLM with a canned reply; returns the list of prompts seen."""+ import deeptutor.services.llm as llm++ seen: list[str] = []++ async def _complete(prompt: str, **kwargs) -> str:+ seen.append(prompt)+ return reply++ monkeypatch.setattr(llm, "complete", _complete)+ return seen+++_THREE = json.dumps(+ [+ {"label": "复习链式法则", "prompt": "把我上次做错的那道链式法则的题再讲一遍"},+ {"label": "练特征值", "prompt": "出五道特征值的练习题给我"},+ {"label": "回到 Agentic RAG", "prompt": "接着上次的 Agentic RAG,讲讲检索怎么排序"},+ ],+ ensure_ascii=False,+)+++def _write_cache(root: Path, payload: dict) -> None:+ directory = root / "suggestions"+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "starters.json").write_text(+ json.dumps(payload, ensure_ascii=False), encoding="utf-8"+ )+++# ── Shaping ──────────────────────────────────────────────────────────────+++def test_sanitize_accepts_a_plain_array() -> None:+ items = suggestions._sanitize(_THREE)++ assert [item.label for item in items] == ["复习链式法则", "练特征值", "回到 Agentic RAG"]+ assert items[0].prompt.startswith("把我上次")+++def test_sanitize_accepts_a_fenced_array_with_prose_around_it() -> None:+ raw = f"Sure, here they are:\n```json\n{_THREE}\n```\nHope that helps!"++ assert len(suggestions._sanitize(raw)) == 3+++def test_sanitize_discards_a_partial_set() -> None:+ """One lonely chip under the composer reads as a rendering bug."""+ raw = json.dumps([{"label": "a", "prompt": "b"}, {"label": "c", "prompt": "d"}])++ assert suggestions._sanitize(raw) == ()+++def test_sanitize_drops_items_that_ignored_the_brief() -> None:+ raw = json.dumps(+ [+ {"label": "x" * 80, "prompt": "fine"}, # label way over a chip+ {"label": "ok", "prompt": "y" * 400}, # prompt is an essay+ {"label": "missing prompt"},+ {"label": "good", "prompt": "a real question"},+ ]+ )++ # Three were dropped, so the batch is short and goes entirely.+ assert suggestions._sanitize(raw) == ()+++def test_sanitize_dedupes_repeated_labels() -> None:+ raw = json.dumps(+ [+ {"label": "Same", "prompt": "one"},+ {"label": "same", "prompt": "two"},+ {"label": "Other", "prompt": "three"},+ {"label": "Third", "prompt": "four"},+ ]+ )++ assert [item.label for item in suggestions._sanitize(raw)] == ["Same", "Other", "Third"]+++def test_sanitize_strips_quotes_and_collapses_whitespace() -> None:+ raw = json.dumps(+ [+ {"label": '"Quoted"', "prompt": "a ragged\n\nquestion"},+ {"label": "B", "prompt": "b"},+ {"label": "C", "prompt": "c"},+ ]+ )++ items = suggestions._sanitize(raw)+ assert items[0].label == "Quoted"+ assert items[0].prompt == "a ragged question"+++def test_sanitize_rejects_non_arrays() -> None:+ assert suggestions._sanitize('{"label": "x", "prompt": "y"}') == ()+ assert suggestions._sanitize("no json here at all") == ()+++# ── Material ─────────────────────────────────────────────────────────────+++def test_topics_are_capped_per_surface_and_interleaved(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Chat updates on every turn; without a cap it would be the whole list."""+ _stub_material(+ monkeypatch,+ [_hit("chat", f"Session {i}") for i in range(6)]+ + [_hit("quiz", "What is an eigenvalue?")]+ + [_hit("book", "Calculus notes")],+ )++ topics = suggestions._collect_topics()++ by_surface = [topic.surface for topic in topics]+ assert by_surface.count("chat") == suggestions._MAX_PER_SURFACE+ assert {"quiz", "book"} <= set(by_surface)+ # Every kind gets its first item before any kind gets its second.+ assert by_surface[:3] == ["chat", "quiz", "book"]+++def test_topics_merge_kb_queries_from_the_trace(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.memory import recall++ monkeypatch.setattr(recall, "recent", lambda **_: [_hit("chat", "Chain rule")])+ monkeypatch.setattr(+ recall, "recent_queries", lambda **_: [_hit("kb", "how does backprop work")]+ )++ labels = [topic.label for topic in suggestions._collect_topics()]++ assert labels == ["Chain rule", "how does backprop work"]+++def test_topics_survive_a_broken_recall(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.memory import recall++ def _boom(**_):+ raise RuntimeError("memory unreadable")++ monkeypatch.setattr(recall, "recent", _boom)+ monkeypatch.setattr(recall, "recent_queries", lambda **_: [_hit("kb", "a query")])++ assert [topic.label for topic in suggestions._collect_topics()] == ["a query"]+++# ── Reads ────────────────────────────────────────────────────────────────+++async def test_read_without_a_cache_is_empty_and_stale(no_material) -> None:+ result = await suggestions.get_suggestions("zh")++ assert result["suggestions"] == []+ assert result["stale"] is True+++async def test_read_never_calls_the_model(+ monkeypatch: pytest.MonkeyPatch, isolated_scope: Path+) -> None:+ """The request path reads one JSON file and nothing else."""+ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])+ calls = _stub_llm(monkeypatch, _THREE)+ _write_cache(+ isolated_scope,+ {+ "suggestions": [{"label": "cached", "prompt": "from disk"}],+ "language": "zh",+ "generated_at": time.time(),+ "fingerprint": "whatever",+ },+ )++ result = await suggestions.get_suggestions("zh")++ assert [item["label"] for item in result["suggestions"]] == ["cached"]+ assert result["stale"] is False+ assert calls == []+++async def test_expired_cache_is_still_served_while_it_regenerates(+ monkeypatch: pytest.MonkeyPatch, isolated_scope: Path+) -> None:+ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])+ _stub_llm(monkeypatch, _THREE)+ _write_cache(+ isolated_scope,+ {+ "suggestions": [{"label": "yesterday", "prompt": "old"}],+ "language": "zh",+ "generated_at": time.time() - suggestions._TTL_SECONDS - 1,+ "fingerprint": "old",+ },+ )++ result = await suggestions.get_suggestions("zh")++ # Served immediately, flagged for a second look.+ assert [item["label"] for item in result["suggestions"]] == ["yesterday"]+ assert result["stale"] is True++ # The background pass replaces it.+ await asyncio.gather(*suggestions._inflight.values())+ after = await suggestions.get_suggestions("zh")+ assert [item["label"] for item in after["suggestions"]] == [+ "复习链式法则",+ "练特征值",+ "回到 Agentic RAG",+ ]+++async def test_a_language_switch_is_not_served_from_the_other_language(+ isolated_scope: Path, no_material+) -> None:+ _write_cache(+ isolated_scope,+ {+ "suggestions": [{"label": "cached", "prompt": "from disk"}],+ "language": "zh",+ "generated_at": time.time(),+ "fingerprint": "x",+ },+ )++ result = await suggestions.get_suggestions("en")++ assert result["suggestions"] == []+ assert result["stale"] is True+++async def test_probe_is_throttled_across_a_burst_of_loads(+ monkeypatch: pytest.MonkeyPatch, no_material+) -> None:+ scheduled: list[str] = []+ monkeypatch.setattr(+ suggestions, "_regenerate_if_due", lambda language: _noop(scheduled, language)+ )++ for _ in range(5):+ await suggestions.get_suggestions("en")+ await asyncio.gather(*suggestions._inflight.values())++ assert len(scheduled) == 1+++async def _noop(sink: list[str], language: str) -> None:+ sink.append(language)+++# ── Generation ───────────────────────────────────────────────────────────+++async def test_no_material_means_no_model_call(+ monkeypatch: pytest.MonkeyPatch, no_material+) -> None:+ """A brand-new learner has no history to ground a suggestion in."""+ calls = _stub_llm(monkeypatch, _THREE)++ result = await suggestions.refresh_suggestions("en")++ assert result.suggestions == ()+ assert calls == []+++async def test_generation_describes_the_material_in_the_learners_words(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stub_material(monkeypatch, [_hit("quiz", "What is an eigenvalue?", age=0)])+ calls = _stub_llm(monkeypatch, _THREE)++ await suggestions.refresh_suggestions("zh")++ assert "错题" in calls[0]+ assert "今天" in calls[0]+ assert "What is an eigenvalue?" in calls[0]+++async def test_a_failing_model_leaves_an_empty_set_not_an_exception(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import deeptutor.services.llm as llm++ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])++ async def _boom(**_):+ raise RuntimeError("no provider configured")++ monkeypatch.setattr(llm, "complete", _boom)++ result = await suggestions.refresh_suggestions("en")++ assert result.suggestions == ()+++async def test_unchanged_material_inside_the_ttl_skips_the_model(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])+ calls = _stub_llm(monkeypatch, _THREE)++ await suggestions.refresh_suggestions("en")+ assert len(calls) == 1++ # Same material, still fresh: the background pass must not spend a call.+ await suggestions._regenerate_if_due("en")+ assert len(calls) == 1++ # New material: it must.+ _stub_material(monkeypatch, [_hit("chat", "Eigenvalues")])+ await suggestions._regenerate_if_due("en")+ assert len(calls) == 2+++# ── Isolation ────────────────────────────────────────────────────────────+++async def test_two_users_never_see_each_others_suggestions(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The cache is addressed through the multi-user path service, so one+ user's chips must not leak into another's response."""+ import deeptutor.services.path_service as path_service++ alice, bob = tmp_path / "alice", tmp_path / "bob"+ current = {"root": alice}+ monkeypatch.setattr(path_service, "get_path_service", lambda: _FakePathService(current["root"]))+ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])+ _stub_llm(monkeypatch, _THREE)++ await suggestions.refresh_suggestions("zh")+ mine = await suggestions.get_suggestions("zh")+ assert len(mine["suggestions"]) == 3++ current["root"] = bob+ theirs = await suggestions.get_suggestions("zh")+ assert theirs["suggestions"] == []