DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(home): make the starting points specific, and let them read as invitations
Bingxi Zhao (Frank)399fe5596414
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.pyindex 28ef5a074..d8dd99319 100644--- a/deeptutor/api/routers/dashboard.py+++ b/deeptutor/api/routers/dashboard.py@@ -1,6 +1,6 @@"""Dashboard API — what the home screen shows before a conversation starts.-Recent activity comes from the unified SQLite session store; the starter chips+Recent activity comes from the unified SQLite session store; the starter linescome from :mod:`deeptutor.services.suggestions`, which reads memory.Route order matters here: ``/{entry_id}`` at the bottom of this module matches@@ -48,7 +48,7 @@ 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")):- """The three starter chips for the home composer.+ """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 nothingdiff --git a/deeptutor/services/suggestions.py b/deeptutor/services/suggestions.pyindex 1b53fa451..0ef21bb9b 100644--- a/deeptutor/services/suggestions.py+++ b/deeptutor/services/suggestions.py@@ -1,10 +1,12 @@-"""Starter suggestions — the three chips under the home composer.+"""Starter suggestions — the three lines offered 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.+Each is two strings that do different jobs. ``label`` is the line the learner+reads, and it has one job: name the specific thing worth doing next. "Explain a+topic" names an activity and would fit any learner's screen; "把链式法则的直觉+讲透" names theirs. ``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-------------------------@@ -22,11 +24,11 @@ When it regenerates-------------------The background pass regenerates when the material changed (a fingerprint overthe 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+when the *content* should change, the second is so the same three lines do notgreet someone all week. A manual refresh bypasses both and generatessynchronously, because there a human is deliberately waiting.-Empty is a valid answer. A learner with no history gets no generated chips and+Empty is a valid answer. A learner with no history gets no generated lines andno LLM call; the frontend shows a fixed set of product starters instead, whichis honest about knowing nothing yet."""@@ -43,10 +45,10 @@ from typing import Anylogger = logging.getLogger(__name__)-# How many chips the home screen shows. Fewer than three looks like a bug;-# more crowds the composer.+# How many starting points the home screen offers. One per line, so fewer than+# three reads as a stub and more turns the empty screen into a menu._COUNT = 3-# Long enough that the same three chips are not re-generated all afternoon,+# Long enough that the same three lines 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@@ -54,16 +56,18 @@ _TTL_SECONDS = 6 * 3600# meaningfully change that fast._PROBE_INTERVAL_SECONDS = 60.0_LLM_TIMEOUT = 25.0-# How much history shapes the chips.+# How much history shapes the lines._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.+# point of reading every surface is that the three 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+# The line the learner reads, 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 starting point. The label+# bound is generous enough for "Redo the two eigenvalue questions you missed" —+# naming the actual thing costs words, and that specificity is the point.+_MAX_LABEL_CHARS = 60_MAX_PROMPT_CHARS = 240# One in-flight regeneration per scope; a burst of page loads must not fan out@@ -76,7 +80,7 @@ _last_probe: dict[str, float] = {}@dataclass(frozen=True, slots=True)class Suggestion:- """One chip: what it says, and what it sends."""+ """One starting point: what it says, and what it sends."""label: strprompt: str@@ -87,7 +91,7 @@ class Suggestion:@dataclass(frozen=True, slots=True)class SuggestionSet:- """The chips currently on offer, plus what they were generated from."""+ """The lines currently on offer, plus what they were generated from."""suggestions: tuple[Suggestion, ...]language: str@@ -200,7 +204,7 @@ def _collect_topics() -> list[_Topic]:Chat updates on every turn, so a plain newest-first list is almost allchat. Taking a bounded number per surface and interleaving them is what- makes three chips of three different kinds possible.+ makes three starting points of three different kinds possible."""from deeptutor.services.memory import recall@@ -248,28 +252,36 @@ def _fingerprint(topics: list[_Topic], language: str) -> str:# ── Generation ───────────────────────────────────────────────────────────-_SYSTEM_EN = """You write the three starter chips a learning app shows under its composer.+_SYSTEM_EN = """You write the three starting points a learning app offers its learner. Each is one line of text they click to begin.-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.+Each is an object with two fields:+- "label": the line they read. 4 to 9 words, no ending punctuation. It MUST name the specific thing from the material — the concept, the question, the document. It is a proposal for what to do next, not a category of activity.- "prompt": the message sent as the learner's own words when they click. First person, complete, specific enough to answer directly.+The single most important rule: be concrete. A line that could appear in any learner's app has failed.+- BAD: "Explain a topic" / "Review your notes" / "Practise some questions" — these name an activity, not a subject.+- GOOD: "Build intuition for the chain rule" / "Redo the two eigenvalue questions you missed" / "Pick up where Agentic RAG retrieval left off"+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).+- Every line must be grounded in the material given. Name what is actually there; never invent a topic.+- Make the three differ — different items from the material, and different things to do with them (explain, practise, review, go deeper).- No greetings, no emoji, no quotes around the fields' text."""-_SYSTEM_ZH = """你要为一个学习应用写出输入框下方的三个引导按钮。+_SYSTEM_ZH = """你要为一个学习应用写出三个"从这里开始"的入口。每一个都是一行字,学习者点一下就开始。-每个按钮是一个对象,含两个字段:-- "label":学习者在按钮上看到的字,不超过 10 个字,结尾不加标点。是短语或祈使句,不是完整句子。+每一个是一个对象,含两个字段:+- "label":学习者读到的那行字。8 到 16 个字,结尾不加标点。必须点出素材里那个**具体**的东西——具体的概念、具体的题、具体的文档。它是一个"接下来做这个"的提议,不是一类活动的名称。- "prompt":学习者点击后以自己的身份发出的那句话。第一人称、完整、具体到可以直接回答。+最重要的一条规则:要具体。一句放在谁的界面上都成立的话,就是失败的。+- 差:"讲解一个主题" / "复习一下笔记" / "做几道练习题"——这些说的是活动类型,不是具体内容。+- 好:"把链式法则的直觉讲透" / "重做上次错的那两道特征值" / "接着 Agentic RAG 的检索排序讲"+规则:- 只回复一个 JSON 数组,正好 3 个这样的对象。不要有任何解释文字,不要 markdown 代码块。-- 每个按钮都要基于下面给出的素材,点出真实的内容,绝不编造。-- 三个之间要有区别——取不同的素材,也做不同的事(讲解、练习、复习、深入)。+- 每一行都要基于下面给出的素材,点出真实存在的内容,绝不编造。+- 三个之间要有区别——取素材里不同的东西,也做不同的事(讲解、练习、复习、深入)。- 不要问候语、不要 emoji、字段文本里不要加引号。"""@@ -293,9 +305,9 @@ def _render_topics(topics: list[_Topic], zh: bool) -> str:def _sanitize(raw: str) -> tuple[Suggestion, ...]:- """Exactly :data:`_COUNT` usable chips, or nothing at all.+ """Exactly :data:`_COUNT` usable lines, or nothing at all.- Partial output is discarded rather than shown: one lonely chip under the+ Partial output is discarded rather than shown: one lonely line under thecomposer reads as a rendering bug, and the caller has a fixed set ofstarters that is better than that."""@@ -345,7 +357,7 @@ async def _generate(language: str) -> SuggestionSet:if zhelse ("The learner has recently been working on:\n"- f"{_render_topics(topics, zh)}\n\nWrite the three chips."+ f"{_render_topics(topics, zh)}\n\nWrite the three starting points."))@@ -439,7 +451,7 @@ def _schedule_probe(language: str) -> None:async def get_suggestions(language: str = "en") -> dict[str, Any]:- """The chips to show now, plus whether a fresher set is being made.+ """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 realanswer — a new learner has nothing to suggest from — and ``stale`` tellsdiff --git a/tests/services/test_suggestions.py b/tests/services/test_suggestions.pyindex b2efd3ef5..dbd86490f 100644--- a/tests/services/test_suggestions.py+++ b/tests/services/test_suggestions.py@@ -102,16 +102,34 @@ def test_sanitize_accepts_a_fenced_array_with_prose_around_it() -> None:def test_sanitize_discards_a_partial_set() -> None:- """One lonely chip under the composer reads as a rendering bug."""+ """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 the actual thing 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": "Redo the two eigenvalue questions you missed", "prompt": "a"},+ {"label": "Build intuition for the chain rule", "prompt": "b"},+ {"label": "把上次 Agentic RAG 的检索排序接着讲完", "prompt": "c"},+ ],+ ensure_ascii=False,+ )++ assert len(suggestions._sanitize(raw)) == 3++def test_sanitize_drops_items_that_ignored_the_brief() -> None:raw = json.dumps([- {"label": "x" * 80, "prompt": "fine"}, # label way over a chip+ {"label": "x" * 80, "prompt": "fine"}, # label is a paragraph{"label": "ok", "prompt": "y" * 400}, # prompt is an essay{"label": "missing prompt"},{"label": "good", "prompt": "a real question"},diff --git a/web/components/chat/home/StarterSuggestions.tsx b/web/components/chat/home/StarterSuggestions.tsxindex e34029d61..930c4c3e1 100644--- a/web/components/chat/home/StarterSuggestions.tsx+++ b/web/components/chat/home/StarterSuggestions.tsx@@ -6,7 +6,7 @@ import { RefreshCw } from "lucide-react";import { apiFetch, apiUrl } from "@/lib/api";interface Suggestion {- /** What the chip says — a few words. */+ /** The line the learner reads — names the specific thing worth doing next. */label: string;/** What gets sent as the learner's own message when they click. */prompt: string;@@ -32,33 +32,44 @@ const RESETTLE_MS = 3500;* who has not started anything yet. Fixed product copy rather than a generated* line: with no history there is nothing to ground a suggestion in, and asking* a model anyway would only produce invention.+ *+ * Still written to propose something specific. These cannot name the learner's+ * own material, but they can name a concrete first move rather than a category+ * of activity — "find where a shaky concept breaks down" instead of "explain a+ * topic".*/const FALLBACK: Suggestion[] = [{- label: "Explain a topic",+ label: "Start with the concept you're least sure of",prompt:- "I want to learn a new topic — start me off with the big picture, then go deeper.",+ "I want to start with a concept I'm shaky on — ask me a few questions to find where it breaks down.",},{- label: "Quiz me",+ label: "Ten questions to find my gaps",prompt:- "Give me five questions on a topic I choose, easy to hard, and explain after I answer.",+ "Give me ten questions on a subject I name, easy to hard, and tell me where my gaps are.",},{- label: "Work through a document",- prompt: "I have a document I want to understand. How should we start?",+ label: "Turn a document into something I can explain",+ prompt:+ "I have a document I need to be able to explain in my own words. Where do we start?",},];/**- * The three starter chips under the home composer.+ * The three starting points under the home composer.*- * Each chip shows its ``label`` and sends its ``prompt`` — the full sentence+ * Each line shows its ``label`` and sends its ``prompt`` — the full sentence* the learner would have typed — so a click starts a real conversation rather* than prefilling something they still have to finish. Generation, caching and* staleness live on the backend; this renders the result and offers a reroll.*- * Renders nothing until the first response lands: chips appearing a beat late+ * One per line, left-aligned to the composer's own edge, with no border or+ * fill: the lines name specific things, and a specific sentence in a pill+ * reads as a tag rather than as an invitation. The arrow carries the+ * invitation instead, and is the only coloured element at rest.+ *+ * Renders nothing until the first response lands: lines appearing a beat late* is calmer than fixed copy visibly swapping for generated copy.*/export default function StarterSuggestions({@@ -72,7 +83,7 @@ export default function StarterSuggestions({const { t, i18n } = useTranslation();const language = i18n.language?.toLowerCase().startsWith("zh") ? "zh" : "en";/**- * Generated chips are already in the learner's language and must not go+ * Generated lines are already in the learner's language and must not go* through the i18n table — a generated label that happened to match a key* would be silently replaced by an unrelated translation. Only the fixed* starters are keys.@@ -104,7 +115,7 @@ export default function StarterSuggestions({const controller = new AbortController();void (async () => {const payload = await load(controller.signal);- // A failed read falls back rather than leaving the row empty — the+ // A failed read falls back rather than leaving the list empty — the// fixed starters are useful on their own.if (!payload?.suggestions.length) {setStarters({ items: FALLBACK, source: "fixed" });@@ -138,7 +149,7 @@ export default function StarterSuggestions({if (response.ok) {const payload = (await response.json()) as SuggestionPayload;// Keep what is on screen when the reroll came back empty: replacing- // three usable chips with nothing is worse than not rerolling.+ // three usable lines with nothing is worse than not rerolling.if (payload.suggestions.length) {setStarters({ items: payload.suggestions, source: "generated" });}@@ -154,32 +165,46 @@ export default function StarterSuggestions({const text = (value: string) => (starters.source === "fixed" ? t(value) : value);return (- <div className="group/starters mx-auto flex w-full max-w-[960px] flex-wrap items-center justify-center gap-2 px-6 pb-3 animate-fade-in">- {starters.items.map((item) => (- <button- key={item.label}- type="button"- disabled={disabled}- onClick={() => onPick(text(item.prompt))}- title={text(item.prompt)}- className="max-w-full truncate rounded-full border border-[var(--border)] bg-[var(--background)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:bg-[var(--secondary)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {text(item.label)}- </button>- ))}+ // max-w-[768px] + px-6 mirrors ChatComposer's own empty-state container, so+ // the lines start exactly at the composer's left edge rather than floating+ // near it.+ <div className="group/starters mx-auto w-full max-w-[768px] px-6 pb-6 animate-fade-in">+ <ul className="flex flex-col items-start">+ {starters.items.map((item) => (+ <li key={item.label} className="max-w-full">+ <button+ type="button"+ disabled={disabled}+ onClick={() => onPick(text(item.prompt))}+ title={text(item.prompt)}+ className="group/line flex max-w-full items-baseline gap-2 py-[5px] text-left font-serif text-[15.5px] leading-[1.45] tracking-[-0.005em] text-[color-mix(in_srgb,var(--foreground)_72%,transparent)] transition-colors duration-200 hover:text-[var(--primary)] focus-visible:text-[var(--primary)] focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-40"+ >+ <span className="truncate">{text(item.label)}</span>+ {/* The arrow is the invitation: coloured at rest so the line+ reads as something to click, and it steps right on hover. */}+ <span+ aria-hidden="true"+ className="shrink-0 text-[color-mix(in_srgb,var(--primary)_65%,transparent)] transition-all duration-200 ease-out group-hover/line:translate-x-1 group-hover/line:text-[var(--primary)] group-focus-visible/line:translate-x-1"+ >+ →+ </span>+ </button>+ </li>+ ))}+ </ul><buttontype="button"onClick={() => void reroll()}disabled={refreshing || disabled}title={t("Suggest something else")}- aria-label={t("Suggest something else")}- className="shrink-0 rounded-full p-1.5 text-[var(--muted-foreground)]/40 opacity-0 transition-all hover:bg-[var(--secondary)] hover:text-[var(--foreground)] focus-visible:opacity-100 disabled:opacity-30 group-hover/starters:opacity-100"+ className="mt-1.5 inline-flex items-center gap-1.5 text-[11.5px] text-[color-mix(in_srgb,var(--muted-foreground)_55%,transparent)] opacity-0 transition-all duration-200 hover:text-[var(--foreground)] focus-visible:opacity-100 disabled:opacity-30 group-hover/starters:opacity-100"><RefreshCw- size={13}+ size={11}strokeWidth={1.8}className={refreshing ? "animate-spin" : ""}/>+ {t("Suggest something else")}</button></div>);diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 43761015d..ce518a360 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -303,12 +303,12 @@"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?",- "Explain a topic": "Explain a topic",- "I want to learn a new topic — start me off with the big picture, then go deeper.": "I want to learn a new topic — start me off with the big picture, then go deeper.",- "Quiz me": "Quiz me",- "Give me five questions on a topic I choose, easy to hard, and explain after I answer.": "Give me five questions on a topic I choose, easy to hard, and explain after I answer.",- "Work through a document": "Work through a document",- "I have a document I want to understand. How should we start?": "I have a document I want to understand. How should we start?",+ "Start with the concept you're least sure of": "Start with the concept you're least sure of",+ "I want to start with a concept I'm shaky on — ask me a few questions to find where it breaks down.": "I want to start with a concept I'm shaky on — ask me a few questions to find where it breaks down.",+ "Ten questions to find my gaps": "Ten questions to find my gaps",+ "Give me ten questions on a subject I name, easy to hard, and tell me where my gaps are.": "Give me ten questions on a subject I name, easy to hard, and tell me where my gaps are.",+ "Turn a document into something I can explain": "Turn a document into something I can explain",+ "I have a document I need to be able to explain in my own words. Where do we start?": "I have a document I need to be able to explain in my own words. Where do we start?","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 9e30fadd5..e2046390a 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -303,12 +303,12 @@"Evening — what shall we explore?": "晚上好——想探索点什么?","It's late today.": "已经很晚了。","Burning the midnight oil?": "还在熬夜?",- "Explain a topic": "讲解一个主题",- "I want to learn a new topic — start me off with the big picture, then go deeper.": "我想学一个新主题,先帮我把整体框架讲清楚,再逐步深入。",- "Quiz me": "出题考我",- "Give me five questions on a topic I choose, easy to hard, and explain after I answer.": "就我指定的主题出五道题,由易到难,我答完之后你再讲解。",- "Work through a document": "读懂一份材料",- "I have a document I want to understand. How should we start?": "我有一份材料想读懂,我们该从哪里开始?",+ "Start with the concept you're least sure of": "从你最没把握的那个概念开始",+ "I want to start with a concept I'm shaky on — ask me a few questions to find where it breaks down.": "我想从一个我最没把握的概念开始,你先问我几个问题,定位它到底卡在哪。",+ "Ten questions to find my gaps": "十道题,测出我的薄弱环节",+ "Give me ten questions on a subject I name, easy to hard, and tell me where my gaps are.": "就我说的科目出十道题,由易到难,然后告诉我我的薄弱环节在哪。",+ "Turn a document into something I can explain": "把一份材料读成我能讲出来的东西",+ "I have a document I need to be able to explain in my own words. Where do we start?": "我有一份材料,我需要能用自己的话讲出来。我们从哪开始?","Suggest something else": "换一批","Ask anything — I'm here to help you understand.": "随便问——我来帮你搞懂。","Welcome to DeepTutor": "欢迎使用 DeepTutor",