DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(home): build the starting points from L3 plus the last k activities
Bingxi Zhao (Frank)37723d1db38c
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.pyindex d8dd99319..4ba1bec0d 100644--- a/deeptutor/api/routers/dashboard.py+++ b/deeptutor/api/routers/dashboard.py@@ -10,7 +10,7 @@ never be reached.from typing import Any-from fastapi import APIRouter, HTTPException, Query+from fastapi import APIRouter, HTTPExceptionfrom deeptutor.services.session import get_session_store@@ -47,21 +47,24 @@ async def get_recent_activities(limit: int = 50, type: str | None = None):@router.get("/suggestions")-async def get_starter_suggestions(language: str = Query(default="en")):+async def get_starter_suggestions():"""The three starting points for the home composer.Returns immediately, even when the set is stale — regeneration happensbehind 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`.+ in memory to ground a suggestion in, and the client renders nothing.++ No language parameter: the output language is the learner's own+ model-output setting, resolved server-side. See+ :mod:`deeptutor.services.suggestions`."""from deeptutor.services.suggestions import get_suggestions- return await get_suggestions(language)+ return await get_suggestions()@router.post("/suggestions/refresh")-async def refresh_starter_suggestions(language: str = Query(default="en")):+async def refresh_starter_suggestions():"""Generate a new set now. Backs the reroll control.Synchronous, unlike the read: a human clicked and is waiting for a@@ -69,7 +72,7 @@ async def refresh_starter_suggestions(language: str = Query(default="en")):"""from deeptutor.services.suggestions import refresh_suggestions- result = await refresh_suggestions(language)+ result = await refresh_suggestions()return {**result.to_dict(), "stale": False}diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex c48c65c89..5ce7fbb94 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -51,6 +51,9 @@ from deeptutor.services.settings.interface_settings import (DEFAULT_UI_SETTINGS as INTERFACE_DEFAULTS,)from deeptutor.services.settings.interface_settings import resolve_languages+from deeptutor.services.settings.starter_settings import (+ TRACE_COUNT_RANGE as STARTER_TRACE_COUNT_RANGE,+)from deeptutor.tools.builtin import USER_TOGGLEABLE_TOOL_NAMESrouter = APIRouter()@@ -220,6 +223,16 @@ class ChatAttachmentSettingsUpdate(BaseModel):)+class ChatStarterSettingsUpdate(BaseModel):+ """How much recent activity shapes the home screen's starting points.++ Bounds mirror ``starter_settings.TRACE_COUNT_RANGE`` so the API rejects+ loudly what the file layer would silently clamp.+ """++ trace_count: int = Field(ge=STARTER_TRACE_COUNT_RANGE[0], le=STARTER_TRACE_COUNT_RANGE[1])++class MinerUSettingsUpdate(BaseModel):"""MinerU PDF-parsing backend settings.@@ -762,6 +775,33 @@ async def get_chat_attachment_settings():return _chat_attachments_payload()[email protected]("/chat-starters")+async def get_chat_starter_settings():+ """How many recent activities shape the home screen's starting points.++ Per user and not admin-gated, unlike the attachment caps next door: this+ changes the size of one prompt built from the caller's own memory, not any+ resource other people share.+ """+ from deeptutor.services.settings.starter_settings import (+ TRACE_COUNT_RANGE,+ get_starter_settings,+ )++ return {"settings": get_starter_settings(), "bounds": {"trace_count": TRACE_COUNT_RANGE}}++[email protected]("/chat-starters")+async def update_chat_starter_settings(payload: ChatStarterSettingsUpdate):+ from deeptutor.services.settings.starter_settings import (+ TRACE_COUNT_RANGE,+ save_starter_settings,+ )++ saved = save_starter_settings({"trace_count": payload.trace_count})+ return {"settings": saved, "bounds": {"trace_count": TRACE_COUNT_RANGE}}++@router.put("/chat-attachments")async def update_chat_attachment_settings(payload: ChatAttachmentSettingsUpdate):_require_settings_admin()diff --git a/deeptutor/services/settings/starter_settings.py b/deeptutor/services/settings/starter_settings.pynew file mode 100644index 000000000..68cdc382b--- /dev/null+++ b/deeptutor/services/settings/starter_settings.py@@ -0,0 +1,85 @@+"""Starter-suggestion settings.++One knob, stored per user in ``data/user/settings/starters.json``: how many+recent activities the model is shown when it proposes what to explore next.++Per user rather than deployment-wide because it tunes a reading of *this*+learner's own memory, and because it costs nothing on the server — it changes+the size of one prompt, not the resources anyone else can claim.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++# Twenty is enough to cover a week of ordinary use without burying the model in+# a list it has to skim. The floor is where a suggestion stops being grounded+# in anything; the ceiling is where the trace list starts crowding out L3,+# which is the more useful half of the material.+DEFAULT_TRACE_COUNT = 20+TRACE_COUNT_RANGE = (3, 100)++DEFAULT_STARTER_SETTINGS: dict[str, Any] = {+ "version": 1,+ "trace_count": DEFAULT_TRACE_COUNT,+}+++def _settings_file():+ # Resolved on every call so a per-user PathService (installed after auth)+ # routes reads to the caller's own file rather than the admin scope frozen+ # at import time.+ return get_path_service().get_settings_file("starters")+++def _clamp(value: Any) -> int:+ low, high = TRACE_COUNT_RANGE+ try:+ return max(low, min(high, int(value)))+ except (TypeError, ValueError):+ return DEFAULT_TRACE_COUNT+++def get_starter_settings() -> dict[str, Any]:+ """Current settings, with defaults filled in. Never raises."""+ try:+ path = _settings_file()+ raw = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+ except (OSError, json.JSONDecodeError):+ logger.debug("starter settings unreadable; using defaults", exc_info=True)+ raw = {}+ if not isinstance(raw, dict):+ raw = {}+ return {+ "version": 1,+ "trace_count": _clamp(raw.get("trace_count", DEFAULT_TRACE_COUNT)),+ }+++def save_starter_settings(settings: dict[str, Any]) -> dict[str, Any]:+ """Persist *settings* (clamped) and return what was written."""+ resolved = {+ "version": 1,+ "trace_count": _clamp(settings.get("trace_count", DEFAULT_TRACE_COUNT)),+ }+ path = _settings_file()+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(".json.tmp")+ tmp.write_text(json.dumps(resolved, ensure_ascii=False, indent=2), encoding="utf-8")+ tmp.replace(path)+ return resolved+++__all__ = [+ "DEFAULT_STARTER_SETTINGS",+ "DEFAULT_TRACE_COUNT",+ "TRACE_COUNT_RANGE",+ "get_starter_settings",+ "save_starter_settings",+]diff --git a/deeptutor/services/suggestions.py b/deeptutor/services/suggestions.pyindex e01331a7a..ed8d243d6 100644--- a/deeptutor/services/suggestions.py+++ b/deeptutor/services/suggestions.py@@ -67,16 +67,15 @@ _TTL_SECONDS = 6 * 3600# meaningfully change that fast._PROBE_INTERVAL_SECONDS = 60.0_LLM_TIMEOUT = 25.0-# How much history shapes the lines. A month rather than a week: labels are-# deduplicated by name and capped per surface, so a long window does not mean a-# long list — it means a learner who spent this week on one thing still has-# something to be offered. A week left an active user with a single usable-# trace once repeats were collapsed.+# How far back a trace can be and still count as "what they are working on".+# A month rather than a week: labels are deduplicated and the list is cut to+# ``trace_count``, so a longer window means depth, not length — it means a+# learner who spent this week on one thing still has a history to draw on._LOOKBACK_DAYS = 30-_MAX_TOPICS = 8-# Per surface, so chat cannot crowd out the quiz and the KB. The whole point of-# reading every surface is that the three differ in kind.-_MAX_PER_SURFACE = 3+# How much of L3 reaches the prompt. Generous — this is the consolidated read+# on the learner and the most useful half of the material — but bounded,+# because L3 grows without limit and this runs on a schedule.+_MAX_PROFILE_CHARS = 6000# Below this a label carries no subject to propose anything about — a knowledge# base named "q", a search for "q2", an untitled draft. They are real activity# and recall is right to return them; they just cannot ground a suggestion, and@@ -207,6 +206,39 @@ def _save(value: SuggestionSet) -> None:logger.debug("suggestions cache unwritable", exc_info=True)+# ── Settings ─────────────────────────────────────────────────────────────+++def _output_language() -> str:+ """The language these lines are written in.++ The learner's model-output setting (Settings → Appearance), the same one+ that decides what the chat agent answers in — not the UI locale. A chip+ proposing something to ask should read like the answer it will get.+ """+ try:+ from deeptutor.services.settings.interface_settings import get_response_language++ return get_response_language(default="en")+ except Exception:+ logger.debug("suggestions: response language unreadable", exc_info=True)+ return "en"+++def _trace_count() -> int:+ """How many recent activities to show the model (Settings → Chat)."""+ from deeptutor.services.settings.starter_settings import (+ DEFAULT_TRACE_COUNT,+ get_starter_settings,+ )++ try:+ return int(get_starter_settings()["trace_count"])+ except Exception:+ logger.debug("suggestions: starter settings unreadable", exc_info=True)+ return DEFAULT_TRACE_COUNT++# ── Material ─────────────────────────────────────────────────────────────# What each surface is called when it is described to the model. Deliberately@@ -239,54 +271,137 @@ class _Topic:days_ago: int | None-def _collect_topics() -> list[_Topic]:- """Recent activity, spread across surfaces rather than dominated by one.+@dataclass(frozen=True, slots=True)+class _Material:+ """Everything the model is given: who this learner is, and what they did.++ Two halves that answer different questions. ``profile`` is L3 — the+ consolidated read on this learner, including which topics they are still+ unsure about, which is the single most useful thing to know when proposing+ what to look at next. ``topics`` is raw recent activity, which is what+ keeps a proposal anchored to something that actually happened.+ """++ profile: str+ topics: list[_Topic]++ def __bool__(self) -> bool:+ return bool(self.profile or self.topics)+++# L3 slots, most useful first. Order decides who gets the character budget when+# the documents outgrow it: ``preferences`` is tiny and absolute, ``scope``+# carries the familiar/practising/unsure split that this whole feature is+# reaching for, and ``recent`` goes last because the trace list below already+# says what happened lately, in more detail.+_L3_ORDER = ("preferences", "scope", "profile", "recent")+++def _render_l3(cap: int) -> str:+ """L3 as the model should read it: sections and bullets, no citations.++ Reads through :class:`~deeptutor.services.memory.store.MemoryStore`'s+ parser rather than the raw markdown, so footnote markers and their HTML+ comments — which are addressing machinery, not content — never reach the+ prompt.- 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 starting points of three different kinds possible.+ Section names are deliberately passed through untranslated. They are+ written by the consolidator in the deployment's own language ("不确定" /+ "Unsure"), and reading them is exactly the model's job; a lookup table here+ would be a second place for that vocabulary to drift.+ """+ from deeptutor.services.memory import get_memory_store++ try:+ store = get_memory_store()+ except Exception:+ logger.debug("suggestions: memory store unavailable", exc_info=True)+ return ""++ per_slot = max(1, cap // len(_L3_ORDER))+ carry = 0+ blocks: list[str] = []+ for slot in _L3_ORDER:+ try:+ doc = store.read_doc("L3", slot)+ except Exception:+ logger.debug("suggestions: L3 %s unreadable", slot, exc_info=True)+ continue+ budget = per_slot + carry+ lines: list[str] = []+ used = 0+ for section, entries in doc.sections:+ head = f"### {section}"+ if used + len(head) > budget:+ break+ lines.append(head)+ used += len(head)+ for entry in entries:+ text = " ".join(entry.text.split())+ if not text:+ continue+ bullet = f"- {text}"+ if used + len(bullet) > budget:+ break+ lines.append(bullet)+ used += len(bullet)+ # Carry the unspent budget forward: preferences is a line or two, and+ # its leftover is what lets scope be shown in full.+ carry = budget - used+ if lines:+ blocks.append(f"## {doc.title or slot}\n" + "\n".join(lines))+ return "\n\n".join(blocks)+++def _collect_material(trace_count: int) -> _Material:+ """L3 plus the most recent *trace_count* activities, newest first.++ The traces are deliberately flat — one list across every surface, ordered+ by time alone. What a learner touched most recently is the best signal for+ what they are in the middle of, and which surface it happened on says+ nothing about that."""from deeptutor.services.memory import recall- by_surface: dict[str, list[_Topic]] = {}+ seen: set[str] = set()+ topics: list[_Topic] = []- def _add(surface: str, label: str, age: int | None) -> None:- stripped = label.strip()- if len(stripped) < _MIN_TOPIC_CHARS or stripped.casefold() in _PLACEHOLDER_LABELS:- return- bucket = by_surface.setdefault(surface, [])- if len(bucket) >= _MAX_PER_SURFACE:+ def _add(hit) -> None:+ label = hit.label.strip()+ if len(label) < _MIN_TOPIC_CHARS or label.casefold() in _PLACEHOLDER_LABELS:return- if any(existing.label.casefold() == label.casefold() for existing in bucket):+ if label.casefold() in seen:return- bucket.append(_Topic(surface=surface, label=label, days_ago=age))+ seen.add(label.casefold())+ topics.append(_Topic(surface=hit.surface, label=label, days_ago=hit.days_ago))- 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)+ hits = []+ for source, kwargs in (+ (recall.recent, {"days": _LOOKBACK_DAYS, "limit": trace_count * 3}),+ (recall.recent_queries, {"days": _LOOKBACK_DAYS, "limit": trace_count}),+ ):+ try:+ hits.extend(source(**kwargs))+ except Exception:+ logger.debug("suggestions: %s failed", source.__name__, 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)+ # One ordering across everything, then take the head. Over-fetching above+ # is what makes the cut meaningful: filtering after a limit would let a run+ # of placeholder titles eat the whole allowance.+ hits.sort(key=lambda hit: (hit.ts != "", hit.ts), reverse=True)+ for hit in hits:+ if len(topics) >= trace_count:+ break+ _add(hit)- # 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]+ return _Material(profile=_render_l3(_MAX_PROFILE_CHARS), topics=topics)-def _fingerprint(topics: list[_Topic], language: str) -> str:+def _fingerprint(material: _Material, language: str) -> str:digest = hashlib.sha1(usedforsecurity=False)digest.update(language.encode("utf-8"))- for topic in topics:+ digest.update(material.profile.encode("utf-8"))+ for topic in material.topics:digest.update(b"\0")digest.update(f"{topic.surface}:{topic.label}".encode("utf-8"))return digest.hexdigest()[:16]@@ -403,34 +518,41 @@ def _sanitize(raw: str, language: str = "en") -> tuple[Suggestion, ...]:return tuple(items[:_COUNT]) if len(items) >= _COUNT else ()-async def _generate(language: str, topics: list[_Topic]) -> SuggestionSet:- """Build a fresh set from *topics*. Always returns one — empty on failure.+async def _generate(language: str, material: _Material) -> SuggestionSet:+ """Build a fresh set from *material*. Always returns one — empty on failure.- Takes the material rather than collecting it, so one pass reads the- surfaces once and every downstream decision — the fingerprint, whether an- empty result is meaningful — is made about the same snapshot.+ Takes the material rather than collecting it, so one pass reads memory once+ and every downstream decision — the fingerprint, whether an empty result is+ meaningful — is made about the same snapshot."""- fingerprint = _fingerprint(topics, language)+ fingerprint = _fingerprint(material, language)empty = SuggestionSet(suggestions=(),language=language,generated_at=time.time(),fingerprint=fingerprint,)- if not topics:+ if not material:# Nothing to ground a suggestion in. Say so instead of asking a model# to invent a learning history.return emptyzh = _is_zh(language)- user_prompt = (- f"这个学习者最近留下的痕迹:\n{_render_topics(topics, zh)}\n\n请提出那三个探索方向。"- if zh- else (- "Traces this learner has left recently:\n"- f"{_render_topics(topics, zh)}\n\nPropose the three things worth exploring next."+ sections: list[str] = []+ if material.profile:+ sections.append(+ ("# 关于这个学习者(长期记忆)\n" if zh else "# What is known about this learner\n")+ + material.profile)+ if material.topics:+ sections.append(+ ("# 最近的活动痕迹\n" if zh else "# Recent activity\n")+ + _render_topics(material.topics, zh)+ )+ closing = (+ "\n请提出那三个探索方向。" if zh else "\nPropose the three things worth exploring next.")+ user_prompt = "\n\n".join(sections) + "\n" + closingtry:from deeptutor.services.llm import complete@@ -470,8 +592,8 @@ def _is_fresh(cached: SuggestionSet | None, language: str, *, now: float) -> boo)-async def _generate_and_cache(language: str, topics: list[_Topic]) -> SuggestionSet:- """Generate from *topics* and cache the result — unless it is a failure.+async def _generate_and_cache(language: str, material: _Material) -> SuggestionSet:+ """Generate from *material* and cache the result — unless it is a failure.An empty result is only written when it is the *right* answer: there was nomaterial to work from, and saying so costs nothing to repeat. An empty@@ -481,48 +603,42 @@ async def _generate_and_cache(language: str, topics: list[_Topic]) -> Suggestionpass would see nothing due and never retry. Those are dropped instead, andthe next visit tries again."""- value = await _generate(language, topics)- if value.suggestions or not topics:+ value = await _generate(language, material)+ if value.suggestions or not material:_save(value)return value-async def refresh_suggestions(language: str = "en") -> SuggestionSet:+async def refresh_suggestions() -> SuggestionSet:"""Generate a new set now and cache it. For the manual reroll."""- return await _generate_and_cache(language, _collect_topics())+ language = _output_language()+ return await _generate_and_cache(language, _collect_material(_trace_count()))-async def _regenerate_if_due(language: str) -> None:+async def _regenerate_if_due() -> 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+ Reading memory 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-revalidatemeans."""- topics = _collect_topics()- fingerprint = _fingerprint(topics, language)+ language = _output_language()+ material = _collect_material(_trace_count())+ fingerprint = _fingerprint(material, language)cached = _load()if _is_fresh(cached, language, now=time.time()) and cached.fingerprint == fingerprint:return- await _generate_and_cache(language, topics)-+ await _generate_and_cache(language, material)-def _schedule_probe(language: str) -> None:- """Check (and maybe regenerate) in the background, throttled and deduped.- The throttle is keyed by scope *and* language. A cached set in one language- is not an answer for another, so a learner whose UI is Chinese must not be- held behind a throttle stamped by an English probe — that combination- leaves them looking at an empty slot until the interval expires, with a- perfectly fresh cache sitting there in the wrong language.- """+def _schedule_probe() -> None:+ """Check (and maybe regenerate) in the background, throttled and deduped."""try:loop = asyncio.get_running_loop()except RuntimeError:return- scope = _scope_key()- key = f"{scope}\0{language}"+ key = _scope_key()now = time.monotonic()pending = _inflight.get(key)if pending is not None and not pending.done():@@ -533,7 +649,7 @@ def _schedule_probe(language: str) -> None:async def _go() -> None:try:- await _regenerate_if_due(language)+ await _regenerate_if_due()except Exception:logger.debug("background suggestion refresh failed", exc_info=True)finally:@@ -544,16 +660,23 @@ def _schedule_probe(language: str) -> None:_inflight[key] = task-async def get_suggestions(language: str = "en") -> dict[str, Any]:+async def get_suggestions() -> dict[str, Any]:"""The lines 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.+ answer — a learner with nothing in memory has nothing to suggest from — and+ ``stale`` tells the caller whether it is worth looking again shortly.++ Takes no language: the output language is the learner's own model-output+ setting, read here. A caller-supplied language would let the UI's own+ locale — which can resolve before the user's settings load — decide what a+ model writes, and with one cache per user the two would overwrite each+ other on every visit."""+ language = _output_language()cached = _load()fresh = _is_fresh(cached, language, now=time.time())- _schedule_probe(language)+ _schedule_probe()if cached is not None and cached.language == language:return {**cached.to_dict(), "stale": not fresh}diff --git a/tests/api/test_dashboard_suggestions.py b/tests/api/test_dashboard_suggestions.pyindex feb0e0e34..a2f63b518 100644--- a/tests/api/test_dashboard_suggestions.py+++ b/tests/api/test_dashboard_suggestions.py@@ -28,10 +28,12 @@ def test_suggestions_is_not_swallowed_by_the_entry_route() -> None:import deeptutor.services.suggestions as service- async def _get(language: str = "en") -> dict[str, Any]:+ async def _get() -> dict[str, Any]:+ # The language is resolved server-side from the learner's model-output+ # setting; the endpoint takes no parameter for it.return {"suggestions": [{"label": "复习链式法则", "prompt": "再讲一遍链式法则"}],- "language": language,+ "language": "zh","generated_at": 1.0,"fingerprint": "abc","stale": False,@@ -39,7 +41,7 @@ def test_suggestions_is_not_swallowed_by_the_entry_route(monkeypatch.setattr(service, "get_suggestions", _get)- response = client.get("/api/v1/dashboard/suggestions", params={"language": "zh"})+ response = client.get("/api/v1/dashboard/suggestions")assert response.status_code == 200body = response.json()@@ -51,10 +53,10 @@ def test_refresh_returns_a_fresh_set(client: TestClient, monkeypatch: pytest.Monimport deeptutor.services.suggestions as servicefrom deeptutor.services.suggestions import Suggestion, SuggestionSet- async def _refresh(language: str = "en") -> SuggestionSet:+ async def _refresh() -> SuggestionSet:return SuggestionSet(suggestions=(Suggestion(label="Practise eigenvalues", prompt="Give me five"),),- language=language,+ language="en",generated_at=2.0,fingerprint="def",)diff --git a/tests/services/test_starter_settings.py b/tests/services/test_starter_settings.pynew file mode 100644index 000000000..cb055ff55--- /dev/null+++ b/tests/services/test_starter_settings.py@@ -0,0 +1,77 @@+"""Starter-suggestion settings: per-user, clamped, and never fatal."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from deeptutor.services.settings import starter_settings+++class _FakePathService:+ def __init__(self, root: Path) -> None:+ self._root = root++ def get_settings_file(self, name: str) -> Path:+ return self._root / f"{name}.json"++[email protected](autouse=True)+def scoped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setattr(starter_settings, "get_path_service", lambda: _FakePathService(tmp_path))+ return tmp_path+++def test_defaults_without_a_file() -> None:+ assert starter_settings.get_starter_settings() == {+ "version": 1,+ "trace_count": starter_settings.DEFAULT_TRACE_COUNT,+ }+++def test_round_trip(scoped: Path) -> None:+ saved = starter_settings.save_starter_settings({"trace_count": 42})++ assert saved["trace_count"] == 42+ assert starter_settings.get_starter_settings()["trace_count"] == 42+ assert json.loads((scoped / "starters.json").read_text(encoding="utf-8"))["trace_count"] == 42+++ "given,expected",+ [+ (0, starter_settings.TRACE_COUNT_RANGE[0]),+ (10_000, starter_settings.TRACE_COUNT_RANGE[1]),+ ("nonsense", starter_settings.DEFAULT_TRACE_COUNT),+ (None, starter_settings.DEFAULT_TRACE_COUNT),+ ],+)+def test_values_are_clamped_not_rejected(given, expected) -> None:+ """The file layer clamps so a hand-edited file can never wedge the feature.++ The API rejects the same values loudly — see ``ChatStarterSettingsUpdate``+ — so a bad request is still an error rather than a silent adjustment.+ """+ assert starter_settings.save_starter_settings({"trace_count": given})["trace_count"] == expected+++def test_a_corrupt_file_falls_back_to_defaults(scoped: Path) -> None:+ (scoped / "starters.json").write_text("{not json", encoding="utf-8")++ assert (+ starter_settings.get_starter_settings()["trace_count"]+ == starter_settings.DEFAULT_TRACE_COUNT+ )+++def test_the_service_reads_the_setting(monkeypatch: pytest.MonkeyPatch, scoped: Path) -> None:+ """The knob has to actually reach the material collector."""+ from deeptutor.services import suggestions+ import deeptutor.services.path_service as path_service++ monkeypatch.setattr(path_service, "get_path_service", lambda: _FakePathService(scoped))+ starter_settings.save_starter_settings({"trace_count": 7})++ assert suggestions._trace_count() == 7diff --git a/tests/services/test_suggestions.py b/tests/services/test_suggestions.pyindex 261418e2e..89bc33204 100644--- a/tests/services/test_suggestions.py+++ b/tests/services/test_suggestions.py@@ -1,4 +1,4 @@-"""Starter suggestions — caching, shaping, and staying off the request path."""+"""Starter suggestions — material, caching, shaping, and staying off the request path."""from __future__ import annotations@@ -12,6 +12,10 @@ import pytestfrom deeptutor.services import suggestionsfrom deeptutor.services.memory.recall import RecallHit+# The autouse fixture stubs _render_l3 so trace tests speak only about traces.+# The L3 tests below restore this.+_REAL_RENDER_L3 = suggestions._render_l3+class _FakePathService:def __init__(self, root: Path) -> None:@@ -20,13 +24,22 @@ class _FakePathService:def get_workspace_dir(self) -> Path:return self._root+ def get_settings_file(self, name: str) -> Path:+ return self._root / "settings" / f"{name}.json"+@pytest.fixture(autouse=True)def isolated_scope(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """Route the cache into tmp_path and clear the in-process maps."""+ """Route the cache into tmp_path, clear in-process maps, pin the language.++ L3 is stubbed empty by default so material tests speak only about traces;+ the tests that care about L3 override it.+ """import deeptutor.services.path_service as path_servicemonkeypatch.setattr(path_service, "get_path_service", lambda: _FakePathService(tmp_path))+ monkeypatch.setattr(suggestions, "_output_language", lambda: "en")+ monkeypatch.setattr(suggestions, "_render_l3", lambda cap: "")suggestions._inflight.clear()suggestions._last_probe.clear()yield tmp_path@@ -42,8 +55,14 @@ def no_material(monkeypatch: pytest.MonkeyPatch) -> None: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 _hit(surface: str, label: str, age: int = 1, ts: str = "") -> RecallHit:+ # Descending ts by age keeps "newest first" meaningful in flat ordering.+ return RecallHit(+ surface=surface,+ label=label,+ ts=ts or f"2026-08-{max(1, 30 - age):02d}T10:00:00+00:00",+ days_ago=age,+ )def _stub_material(monkeypatch: pytest.MonkeyPatch, hits: list[RecallHit]) -> None:@@ -69,11 +88,10 @@ def _stub_llm(monkeypatch: pytest.MonkeyPatch, reply: str) -> list[str]:_THREE = json.dumps([- {"label": "复习链式法则", "prompt": "把我上次做错的那道链式法则的题再讲一遍"},- {"label": "练特征值", "prompt": "出五道特征值的练习题给我"},- {"label": "回到 Agentic RAG", "prompt": "接着上次的 Agentic RAG,讲讲检索怎么排序"},- ],- ensure_ascii=False,+ {"label": "How agentic RAG differs from naive RAG", "prompt": "Explain the difference."},+ {"label": "Why the chain rule underlies backprop", "prompt": "Walk me through it."},+ {"label": "What an eigenvalue actually measures", "prompt": "Start from the geometry."},+ ])@@ -89,40 +107,26 @@ def _write_cache(root: Path, payload: dict) -> None:def test_sanitize_accepts_a_plain_array() -> None:- items = suggestions._sanitize(_THREE)+ items = suggestions._sanitize(_THREE, "en")- assert [item.label for item in items] == ["复习链式法则", "练特征值", "回到 Agentic RAG"]- assert items[0].prompt.startswith("把我上次")+ assert [item.label for item in items] == [+ "How agentic RAG differs from naive RAG",+ "Why the chain rule underlies backprop",+ "What an eigenvalue actually measures",+ ]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+ assert len(suggestions._sanitize(raw, "en")) == 3def test_sanitize_discards_a_partial_set() -> None:"""One lonely line 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_keeps_labels_long_enough_to_be_specific() -> None:- """Naming a real distinction costs words, and that is the whole point.-- A label bound tight enough to force "Explain a topic" would throw away- every line worth showing, so these realistic ones must survive.- """- raw = json.dumps(- [- {"label": "How agentic RAG differs from naive RAG", "prompt": "a"},- {"label": "Why the chain rule underlies backpropagation", "prompt": "b"},- {"label": "Where self-attention beats a plain RNN", "prompt": "c"},- ]- )-- assert len(suggestions._sanitize(raw, "en")) == 3+ assert suggestions._sanitize(raw, "en") == ()def test_sanitize_bounds_are_per_language() -> None:@@ -137,19 +141,16 @@ def test_sanitize_bounds_are_per_language() -> None:{"label": "How Self-Correction loops in LangGraph reduce pedagogical hallucinations","prompt": "How can I use LangGraph's cyclic patterns to implement a "- "self-correction loop that verifies factual accuracy before a "- "response reaches the student?",+ "self-correction loop that verifies factual accuracy?",},{"label": "Why RAG retrieval constraints differ for educational coaching versus search",- "prompt": "In an educational coaching context, how should RAG retrieval be "- "constrained to guide the student toward an answer rather than "- "simply providing it?",+ "prompt": "How should RAG retrieval be constrained to guide a student "+ "toward an answer rather than simply providing it?",},{"label": "The trade-off between agentic autonomy and curriculum adherence",- "prompt": "How do we balance an agent's autonomy to follow student tangents "- "against the need to adhere to a syllabus?",+ "prompt": "How do we balance an agent's autonomy against a syllabus?",},])@@ -183,7 +184,7 @@ def test_sanitize_dedupes_repeated_labels() -> None:])- assert [item.label for item in suggestions._sanitize(raw)] == ["Same", "Other", "Third"]+ assert [i.label for i in suggestions._sanitize(raw, "en")] == ["Same", "Other", "Third"]def test_sanitize_strips_quotes_and_collapses_whitespace() -> None:@@ -195,62 +196,173 @@ def test_sanitize_strips_quotes_and_collapses_whitespace() -> None:])- items = suggestions._sanitize(raw)+ items = suggestions._sanitize(raw, "en")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") == ()+ assert suggestions._sanitize('{"label": "x", "prompt": "y"}', "en") == ()+ assert suggestions._sanitize("no json here at all", "en") == ()-# ── Material ─────────────────────────────────────────────────────────────+# ── Material: traces ─────────────────────────────────────────────────────-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."""+def test_traces_are_flat_and_newest_first(monkeypatch: pytest.MonkeyPatch) -> None:+ """One ordering across every surface. Which surface it came from says+ nothing about whether the learner is in the middle of it."""_stub_material(monkeypatch,- [_hit("chat", f"Session {i}") for i in range(6)]- + [_hit("quiz", "What is an eigenvalue?")]- + [_hit("book", "Calculus notes")],+ [+ _hit("book", "Calculus notes", age=5),+ _hit("chat", "Chain rule", age=1),+ _hit("quiz", "What is an eigenvalue?", age=3),+ ],)- topics = suggestions._collect_topics()+ topics = suggestions._collect_material(10).topics++ assert [t.label for t in topics] == [+ "Chain rule",+ "What is an eigenvalue?",+ "Calculus notes",+ ]+- 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_trace_count_bounds_the_list(monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_material(monkeypatch, [_hit("chat", f"Session {i}", age=i) for i in range(1, 30)])+ assert len(suggestions._collect_material(5).topics) == 5+ assert len(suggestions._collect_material(20).topics) == 20-def test_topics_merge_kb_queries_from_the_trace(monkeypatch: pytest.MonkeyPatch) -> None:++def test_traces_merge_kb_queries(monkeypatch: pytest.MonkeyPatch) -> None:from deeptutor.services.memory import recall- monkeypatch.setattr(recall, "recent", lambda **_: [_hit("chat", "Chain rule")])+ monkeypatch.setattr(recall, "recent", lambda **_: [_hit("chat", "Chain rule", age=2)])monkeypatch.setattr(- recall, "recent_queries", lambda **_: [_hit("kb", "how does backprop work")]+ recall, "recent_queries", lambda **_: [_hit("kb", "how does backprop work", age=1)]+ )++ labels = [t.label for t in suggestions._collect_material(10).topics]++ assert labels == ["how does backprop work", "Chain rule"]+++def test_traces_drop_noise_before_the_cut(monkeypatch: pytest.MonkeyPatch) -> None:+ """Filtering after the cut would let a run of placeholders eat the budget.++ Placeholder titles are the *newest* rows by definition — a conversation is+ created before it is named — so a naive "take k then filter" returns+ nothing on an install where someone just opened three blank chats.+ """+ _stub_material(+ monkeypatch,+ [+ _hit("chat", "New conversation", age=0),+ _hit("chat", "新对话", age=0),+ _hit("kb", "q", age=0),+ _hit("chat", "LangGraph checkpointing", age=4),+ ],)- labels = [topic.label for topic in suggestions._collect_topics()]+ assert [t.label for t in suggestions._collect_material(2).topics] == ["LangGraph checkpointing"]- assert labels == ["Chain rule", "how does backprop work"]+def test_traces_dedupe_by_label(monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_material(+ monkeypatch,+ [_hit("chat", "Chain rule", age=1), _hit("book", "chain RULE", age=3)],+ )-def test_topics_survive_a_broken_recall(monkeypatch: pytest.MonkeyPatch) -> None:+ assert len(suggestions._collect_material(10).topics) == 1+++def test_traces_survive_a_broken_recall(monkeypatch: pytest.MonkeyPatch) -> None:from deeptutor.services.memory import recalldef _boom(**_):raise RuntimeError("memory unreadable")monkeypatch.setattr(recall, "recent", _boom)- monkeypatch.setattr(recall, "recent_queries", lambda **_: [_hit("kb", "a query")])+ monkeypatch.setattr(recall, "recent_queries", lambda **_: [_hit("kb", "a real query")])++ assert [t.label for t in suggestions._collect_material(10).topics] == ["a real query"]+++# ── Material: L3 ─────────────────────────────────────────────────────────+++class _FakeDoc:+ def __init__(self, title: str, sections: list[tuple[str, list[str]]]) -> None:+ self.title = title+ self.sections = [+ (name, [type("E", (), {"text": t})() for t in texts]) for name, texts in sections+ ]+++def test_l3_renders_sections_and_bullets(monkeypatch: pytest.MonkeyPatch) -> None:+ import deeptutor.services.memory as memory++ docs = {+ "scope": _FakeDoc("Knowledge scope", [("Unsure", ["Reranking trade-offs"])]),+ "profile": _FakeDoc("User profile", [("Level", ["Comfortable with Python"])]),+ }++ class _Store:+ def read_doc(self, layer: str, key: str):+ return docs.get(key, _FakeDoc("", []))++ monkeypatch.setattr(memory, "get_memory_store", lambda: _Store())+ monkeypatch.setattr(suggestions, "_render_l3", _REAL_RENDER_L3)++ rendered = suggestions._render_l3(6000)++ assert "## Knowledge scope" in rendered+ # Section names pass through untranslated — the consolidator writes them in+ # the deployment's language and reading them is the model's job.+ assert "### Unsure" in rendered+ assert "- Reranking trade-offs" in rendered+ assert "## User profile" in rendered+++def test_l3_is_bounded_and_carries_unspent_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """A tiny preferences doc must not cost scope its share."""+ import deeptutor.services.memory as memory- assert [topic.label for topic in suggestions._collect_topics()] == ["a query"]+ docs = {+ "preferences": _FakeDoc("Preferences", [("P", ["Terse"])]),+ "scope": _FakeDoc("Scope", [("Unsure", [f"item {i} " + "x" * 40 for i in range(40)])]),+ }++ class _Store:+ def read_doc(self, layer: str, key: str):+ return docs.get(key, _FakeDoc("", []))++ monkeypatch.setattr(memory, "get_memory_store", lambda: _Store())+ monkeypatch.setattr(suggestions, "_render_l3", _REAL_RENDER_L3)++ small = suggestions._render_l3(200)+ large = suggestions._render_l3(4000)++ assert len(small) <= 400 # bounded, with per-section headers as overhead+ assert len(large) > len(small)+ # The scope entries got more than a bare quarter share, because preferences+ # spent almost none of its own.+ assert large.count("item ") > 4+++def test_l3_failure_is_not_fatal(monkeypatch: pytest.MonkeyPatch) -> None:+ import deeptutor.services.memory as memory++ def _boom():+ raise RuntimeError("memory offline")++ monkeypatch.setattr(memory, "get_memory_store", _boom)+ monkeypatch.setattr(suggestions, "_render_l3", _REAL_RENDER_L3)++ assert suggestions._render_l3(6000) == ""# ── Reads ────────────────────────────────────────────────────────────────@@ -258,7 +370,7 @@ def test_topics_survive_a_broken_recall(monkeypatch: pytest.MonkeyPatch) -> None@pytest.mark.asyncioasync def test_read_without_a_cache_is_empty_and_stale(no_material) -> None:- result = await suggestions.get_suggestions("zh")+ result = await suggestions.get_suggestions()assert result["suggestions"] == []assert result["stale"] is True@@ -275,15 +387,15 @@ async def test_read_never_calls_the_model(isolated_scope,{"suggestions": [{"label": "cached", "prompt": "from disk"}],- "language": "zh",+ "language": "en","generated_at": time.time(),"fingerprint": "whatever",},)- result = await suggestions.get_suggestions("zh")+ result = await suggestions.get_suggestions()- assert [item["label"] for item in result["suggestions"]] == ["cached"]+ assert [i["label"] for i in result["suggestions"]] == ["cached"]assert result["stale"] is Falseassert calls == []@@ -298,43 +410,39 @@ async def test_expired_cache_is_still_served_while_it_regenerates(isolated_scope,{"suggestions": [{"label": "yesterday", "prompt": "old"}],- "language": "zh",+ "language": "en","generated_at": time.time() - suggestions._TTL_SECONDS - 1,"fingerprint": "old",},)- result = await suggestions.get_suggestions("zh")+ result = await suggestions.get_suggestions()# Served immediately, flagged for a second look.- assert [item["label"] for item in result["suggestions"]] == ["yesterday"]+ assert [i["label"] for i 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",- ]+ after = await suggestions.get_suggestions()+ assert len(after["suggestions"]) == 3@pytest.mark.asyncio-async def test_a_language_switch_is_not_served_from_the_other_language(- isolated_scope: Path, no_material+async def test_a_cache_in_another_language_is_not_served(+ monkeypatch: pytest.MonkeyPatch, isolated_scope: Path, no_material) -> None:+ """Changing the model-output setting invalidates what was generated before."""_write_cache(isolated_scope,{- "suggestions": [{"label": "cached", "prompt": "from disk"}],+ "suggestions": [{"label": "缓存的", "prompt": "旧的"}],"language": "zh","generated_at": time.time(),"fingerprint": "x",},)- result = await suggestions.get_suggestions("en")+ result = await suggestions.get_suggestions() # setting says "en"assert result["suggestions"] == []assert result["stale"] is True@@ -344,74 +452,79 @@ async def test_a_language_switch_is_not_served_from_the_other_language(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)- )+ scheduled: list[int] = []++ async def _noop() -> None:+ scheduled.append(1)++ monkeypatch.setattr(suggestions, "_regenerate_if_due", _noop)for _ in range(5):- await suggestions.get_suggestions("en")+ await suggestions.get_suggestions()await asyncio.gather(*suggestions._inflight.values())assert len(scheduled) == 1+# ── Generation ───────────────────────────────────────────────────────────++@pytest.mark.asyncio-async def test_the_throttle_does_not_swallow_a_language_switch(+async def test_no_material_means_no_model_call(monkeypatch: pytest.MonkeyPatch, no_material) -> None:- """A cached set in one language is not an answer for another.-- The UI can ask in English before i18n settles and in Chinese immediately- after. If the second ask is throttled behind the first, the Chinese user- stares at an empty slot while a perfectly fresh English set sits in the- cache, unusable — for the whole throttle interval.- """- scheduled: list[str] = []- monkeypatch.setattr(- suggestions, "_regenerate_if_due", lambda language: _noop(scheduled, language)- )+ """A brand-new learner has no history to ground a suggestion in."""+ calls = _stub_llm(monkeypatch, _THREE)- await suggestions.get_suggestions("en")- await suggestions.get_suggestions("zh")- await suggestions.get_suggestions("zh") # this one IS throttled- await asyncio.gather(*suggestions._inflight.values())+ result = await suggestions.refresh_suggestions()- assert scheduled == ["en", "zh"]+ assert result.suggestions == ()+ assert calls == []-async def _noop(sink: list[str], language: str) -> None:- sink.append(language)+async def test_l3_alone_is_enough_material(monkeypatch: pytest.MonkeyPatch, no_material) -> None:+ """Someone whose traces have aged out still has a consolidated profile."""+ monkeypatch.setattr(suggestions, "_render_l3", lambda cap: "## Scope\n### Unsure\n- Rerankers")+ calls = _stub_llm(monkeypatch, _THREE)+ result = await suggestions.refresh_suggestions()-# ── Generation ───────────────────────────────────────────────────────────+ assert len(result.suggestions) == 3+ assert "Rerankers" in calls[0]@pytest.mark.asyncio-async def test_no_material_means_no_model_call(- monkeypatch: pytest.MonkeyPatch, no_material+async def test_generation_shows_both_halves_of_the_material(+ monkeypatch: pytest.MonkeyPatch,) -> None:- """A brand-new learner has no history to ground a suggestion in."""+ _stub_material(monkeypatch, [_hit("quiz", "What is an eigenvalue?", age=0)])+ monkeypatch.setattr(suggestions, "_render_l3", lambda cap: "## Scope\n### Unsure\n- Eigenbases")calls = _stub_llm(monkeypatch, _THREE)- result = await suggestions.refresh_suggestions("en")+ await suggestions.refresh_suggestions()- assert result.suggestions == ()- assert calls == []+ prompt = calls[0]+ assert "Eigenbases" in prompt # L3+ assert "What is an eigenvalue?" in prompt # trace+ assert "practice question" in prompt # surface, in the learner's words+ assert "today" in prompt # recency@pytest.mark.asyncio-async def test_generation_describes_the_material_in_the_learners_words(+async def test_output_language_comes_from_the_setting(monkeypatch: pytest.MonkeyPatch,) -> None:- _stub_material(monkeypatch, [_hit("quiz", "What is an eigenvalue?", age=0)])+ """Not from the caller: the UI locale can resolve before settings load."""+ monkeypatch.setattr(suggestions, "_output_language", lambda: "zh")+ _stub_material(monkeypatch, [_hit("quiz", "特征值的几何意义", age=0)])calls = _stub_llm(monkeypatch, _THREE)- await suggestions.refresh_suggestions("zh")+ result = await suggestions.refresh_suggestions()- assert "错题" in calls[0]+ assert result.language == "zh"+ assert "错题" in calls[0] # Chinese surface vocabularyassert "今天" in calls[0]- assert "What is an eigenvalue?" in calls[0]@pytest.mark.asyncio@@ -427,7 +540,7 @@ async def test_a_failing_model_leaves_an_empty_set_not_an_exception(monkeypatch.setattr(llm, "complete", _boom)- result = await suggestions.refresh_suggestions("en")+ result = await suggestions.refresh_suggestions()assert result.suggestions == ()@@ -450,23 +563,23 @@ async def test_a_failed_generation_is_not_cached_over_the_material(raise RuntimeError("provider timed out")monkeypatch.setattr(llm, "complete", _boom)- await suggestions.refresh_suggestions("en")+ await suggestions.refresh_suggestions()assert not (isolated_scope / "suggestions" / "starters.json").exists()# And the retry lands, rather than being skipped as "nothing due".calls = _stub_llm(monkeypatch, _THREE)- await suggestions._regenerate_if_due("en")+ await suggestions._regenerate_if_due()assert len(calls) == 1- assert len((await suggestions.get_suggestions("en"))["suggestions"]) == 3+ assert len((await suggestions.get_suggestions())["suggestions"]) == 3@pytest.mark.asyncioasync def test_an_empty_result_with_no_material_is_cached(- monkeypatch: pytest.MonkeyPatch, isolated_scope: Path, no_material+ isolated_scope: Path, no_material) -> None:"""Empty is the right answer here, and repeating it should stay free."""- await suggestions.refresh_suggestions("en")+ await suggestions.refresh_suggestions()assert (isolated_scope / "suggestions" / "starters.json").exists()@@ -478,16 +591,33 @@ async def test_unchanged_material_inside_the_ttl_skips_the_model(_stub_material(monkeypatch, [_hit("chat", "Chain rule")])calls = _stub_llm(monkeypatch, _THREE)- await suggestions.refresh_suggestions("en")+ await suggestions.refresh_suggestions()assert len(calls) == 1# Same material, still fresh: the background pass must not spend a call.- await suggestions._regenerate_if_due("en")+ await suggestions._regenerate_if_due()assert len(calls) == 1# New material: it must._stub_material(monkeypatch, [_hit("chat", "Eigenvalues")])- await suggestions._regenerate_if_due("en")+ await suggestions._regenerate_if_due()+ assert len(calls) == 2+++async def test_changed_l3_alone_triggers_regeneration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The profile is half the material, so it belongs in the fingerprint."""+ _stub_material(monkeypatch, [_hit("chat", "Chain rule")])+ monkeypatch.setattr(suggestions, "_render_l3", lambda cap: "## Scope\n- A")+ calls = _stub_llm(monkeypatch, _THREE)++ await suggestions.refresh_suggestions()+ assert len(calls) == 1++ monkeypatch.setattr(suggestions, "_render_l3", lambda cap: "## Scope\n- B")+ await suggestions._regenerate_if_due()assert len(calls) == 2@@ -499,7 +629,7 @@ 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."""+ user's lines must not leak into another's response."""import deeptutor.services.path_service as path_servicealice, bob = tmp_path / "alice", tmp_path / "bob"@@ -508,10 +638,10 @@ async def test_two_users_never_see_each_others_suggestions(_stub_material(monkeypatch, [_hit("chat", "Chain rule")])_stub_llm(monkeypatch, _THREE)- await suggestions.refresh_suggestions("zh")- mine = await suggestions.get_suggestions("zh")+ await suggestions.refresh_suggestions()+ mine = await suggestions.get_suggestions()assert len(mine["suggestions"]) == 3current["root"] = bob- theirs = await suggestions.get_suggestions("zh")+ theirs = await suggestions.get_suggestions()assert theirs["suggestions"] == []diff --git a/web/app/(utility)/settings/starters/page.tsx b/web/app/(utility)/settings/starters/page.tsxnew file mode 100644index 000000000..82ca51476--- /dev/null+++ b/web/app/(utility)/settings/starters/page.tsx@@ -0,0 +1,164 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ inputClass,+} from "@/components/settings/shared";+import { useSettings } from "@/components/settings/SettingsContext";+import { apiFetch, apiUrl } from "@/lib/api";++type StarterSettings = { trace_count: number };++type StarterSettingsPayload = {+ settings: StarterSettings;+ bounds: { trace_count: [number, number] };+};++export default function StarterSettingsPage() {+ const { t } = useTranslation();+ const { registerExtension } = useSettings();+ const [payload, setPayload] = useState<StarterSettingsPayload | null>(null);+ const [draft, setDraft] = useState<StarterSettings | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ async function load() {+ setLoading(true);+ setError(null);+ try {+ const response = await apiFetch(+ apiUrl("/api/v1/settings/chat-starters"),+ );+ const data = (await response.json().catch(() => ({}))) as+ | StarterSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? String(data.detail)+ : t("Failed to load starter settings."),+ );+ }+ if (cancelled) return;+ const next = data as StarterSettingsPayload;+ setPayload(next);+ setDraft({ ...next.settings });+ } catch (err) {+ if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ load();+ return () => {+ cancelled = true;+ };+ }, [t]);++ const dirty = useMemo(+ () => Boolean(payload && draft && payload.settings.trace_count !== draft.trace_count),+ [draft, payload],+ );++ // Flush through the global Apply (top toolbar) instead of a local button.+ const draftRef = useRef(draft);+ draftRef.current = draft;+ const save = useCallback(async () => {+ const current = draftRef.current;+ if (!current) return;+ setError(null);+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings/chat-starters"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(current),+ });+ const data = (await response.json().catch(() => ({}))) as+ | StarterSettingsPayload+ | { detail?: string };+ if (!response.ok) {+ throw new Error(+ "detail" in data && data.detail+ ? String(data.detail)+ : t("Failed to save starter settings."),+ );+ }+ const next = data as StarterSettingsPayload;+ setPayload(next);+ setDraft({ ...next.settings });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [t]);++ useEffect(() => {+ registerExtension("chat-starters", { dirty, save });+ return () => registerExtension("chat-starters", null);+ }, [dirty, save, registerExtension]);++ const bounds = payload?.bounds.trace_count;++ return (+ <div>+ <SettingsPageHeader+ title={t("Starting points")}+ description={t(+ "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.",+ )}+ />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {t("Loading starter settings...")}+ </div>+ )}++ {!loading && error && (+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && payload && draft && (+ <SettingSection+ title={t("Material")}+ description={t(+ "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.",+ )}+ >+ <SettingRow+ title={t("Recent activities")}+ description={t(+ "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.",+ )}+ control={+ <input+ className={`${inputClass} w-28`}+ type="number"+ min={bounds?.[0] ?? 3}+ max={bounds?.[1] ?? 100}+ value={draft.trace_count}+ onChange={(event) =>+ setDraft((current) =>+ current+ ? { ...current, trace_count: Number(event.target.value) }+ : current,+ )+ }+ />+ }+ />+ </SettingSection>+ )}+ </div>+ );+}diff --git a/web/components/chat/home/StarterSuggestions.tsx b/web/components/chat/home/StarterSuggestions.tsxindex 54adb4dd5..93e36ca43 100644--- a/web/components/chat/home/StarterSuggestions.tsx+++ b/web/components/chat/home/StarterSuggestions.tsx@@ -60,12 +60,9 @@ export default function StarterSuggestions({onPick: (prompt: string) => void;disabled?: boolean;}) {- const { t, i18n, ready } = useTranslation();- // Asking before i18n settles resolves to "en" for everyone, and the backend- // caches per language — so one early request makes an English set that a- // Chinese UI can then never use. Wait for the real answer.- const language = i18n.language?.toLowerCase().startsWith("zh") ? "zh" : "en";- // Everything rendered here is generated, already in the learner's language,+ const { t } = useTranslation();+ // Everything rendered here is generated, already in the learner's chosen+ // output language (resolved server-side from their model-output setting),// and never goes through the i18n table — a label that happened to match a// key would be silently replaced by an unrelated translation.const [items, setItems] = useState<Suggestion[]>([]);@@ -76,7 +73,7 @@ export default function StarterSuggestions({async (signal?: AbortSignal): Promise<SuggestionPayload | null> => {try {const response = await apiFetch(- apiUrl(`/api/v1/dashboard/suggestions?language=${language}`),+ apiUrl("/api/v1/dashboard/suggestions"),{ signal, cache: "no-store" },);if (!response.ok) return null;@@ -85,11 +82,10 @@ export default function StarterSuggestions({return null;}},- [language],+ [],);useEffect(() => {- if (!ready) return;const controller = new AbortController();void (async () => {const payload = await load(controller.signal);@@ -118,13 +114,13 @@ export default function StarterSuggestions({controller.abort();if (timerRef.current) clearTimeout(timerRef.current);};- }, [load, ready]);+ }, [load]);const reroll = useCallback(async () => {setRefreshing(true);try {const response = await apiFetch(- apiUrl(`/api/v1/dashboard/suggestions/refresh?language=${language}`),+ apiUrl("/api/v1/dashboard/suggestions/refresh"),{ method: "POST" },);if (response.ok) {@@ -138,7 +134,7 @@ export default function StarterSuggestions({} finally {setRefreshing(false);}- }, [language]);+ }, []);if (!items.length) return null;diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex 45b6a323d..e4bdeefde 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -18,6 +18,7 @@ import {Paperclip,Search,SlidersHorizontal,+ Sparkles,Wrench,type LucideIcon,} from "lucide-react";@@ -181,6 +182,17 @@ const CHAT_CHILDREN: SettingsLeaf[] = [icon: SlidersHorizontal,tile: "bg-lime-500/10 text-lime-600 dark:text-lime-400",},+ {+ key: "starters",+ href: "/settings/starters",+ label: { zh: "起始建议", en: "Starting points" },+ blurb: {+ zh: "主页输入框下方那三行引导的素材范围。",+ en: "How much history shapes the three lines under the composer.",+ },+ icon: Sparkles,+ tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",+ },{key: "attachments",href: "/settings/attachments",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 6a9c2ad22..8bdece002 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -303,6 +303,15 @@"Evening — what shall we explore?": "Evening — what shall we explore?","It's late today.": "It's late today.","Burning the midnight oil?": "Burning the midnight oil?",+ "Starting points": "Starting points",+ "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.": "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.",+ "Material": "Material",+ "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.": "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.",+ "Recent activities": "Recent activities",+ "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.": "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.",+ "Loading starter settings...": "Loading starter settings...",+ "Failed to load starter settings.": "Failed to load starter settings.",+ "Failed to save starter settings.": "Failed to save starter settings.","Suggest something else": "Suggest something else","Ask anything — I'm here to help you understand.": "Ask anything — I'm here to help you understand.","Welcome to DeepTutor": "Welcome to DeepTutor",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 4f5a40c72..e2061798d 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -303,6 +303,15 @@"Evening — what shall we explore?": "晚上好——想探索点什么?","It's late today.": "已经很晚了。","Burning the midnight oil?": "还在熬夜?",+ "Starting points": "起始建议",+ "The three lines under the composer on an empty home screen, generated from your long-term memory and what you have been working on lately.": "主页空白时输入框下方的那三行引导,由你的长期记忆和最近在做的事生成。",+ "Material": "素材",+ "Your consolidated memory is always included. This controls how much raw recent activity goes with it — conversations, practice questions, searches, documents, in one list ordered by time.": "你的长期记忆始终会带上。这里控制随之附带多少条原始的近期活动——对话、错题、检索、文档,按时间排成一条列表。",+ "Recent activities": "近期活动条数",+ "More gives the model a longer view of what you have touched; fewer keeps it focused on this week. Takes effect the next time the lines are regenerated.": "调大让模型看到更长的历史,调小则更聚焦在本周。下次重新生成时生效。",+ "Loading starter settings...": "正在加载起始建议设置…",+ "Failed to load starter settings.": "加载起始建议设置失败。",+ "Failed to save starter settings.": "保存起始建议设置失败。","Suggest something else": "换一批","Ask anything — I'm here to help you understand.": "随便问——我来帮你搞懂。","Welcome to DeepTutor": "欢迎使用 DeepTutor",