DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(home): keep the slot present when there are no lines to show
Bingxi Zhao (Frank)1511e914c646
diff --git a/deeptutor/services/suggestions.py b/deeptutor/services/suggestions.pyindex ed8d243d6..07d5ea71b 100644--- a/deeptutor/services/suggestions.py+++ b/deeptutor/services/suggestions.py@@ -632,8 +632,15 @@ async def _regenerate_if_due() -> None:await _generate_and_cache(language, material)-def _schedule_probe() -> None:- """Check (and maybe regenerate) in the background, throttled and deduped."""+def _schedule_probe(*, force: bool = False) -> None:+ """Check (and maybe regenerate) in the background, throttled and deduped.++ ``force`` skips the interval, not the in-flight guard. The throttle exists+ because page loads arrive in bursts and the material rarely changes between+ them — but when the caller already *knows* the cached set is unusable (the+ output language was just changed), waiting out the interval means up to a+ minute of empty screen with nothing working to fill it.+ """try:loop = asyncio.get_running_loop()except RuntimeError:@@ -643,7 +650,7 @@ def _schedule_probe() -> None: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:+ if not force and now - _last_probe.get(key, 0.0) < _PROBE_INTERVAL_SECONDS:return_last_probe[key] = now@@ -676,7 +683,9 @@ async def get_suggestions() -> dict[str, Any]:language = _output_language()cached = _load()fresh = _is_fresh(cached, language, now=time.time())- _schedule_probe()+ # A cache in another language is not stale, it is unusable: the learner+ # just changed the setting and is looking at an empty slot right now.+ _schedule_probe(force=cached is not None and cached.language != language)if cached is not None and cached.language == language:return {**cached.to_dict(), "stale": not fresh}diff --git a/tests/services/test_suggestions.py b/tests/services/test_suggestions.pyindex 89bc33204..64d00bd1b 100644--- a/tests/services/test_suggestions.py+++ b/tests/services/test_suggestions.py@@ -466,6 +466,69 @@ async def test_probe_is_throttled_across_a_burst_of_loads(assert len(scheduled) == 1+async def test_a_language_switch_regenerates_without_waiting_out_the_throttle(+ monkeypatch: pytest.MonkeyPatch, isolated_scope: Path, no_material+) -> None:+ """Changing the output setting must not leave a minute of empty screen.++ The learner is on the home screen (which already spent this scope's probe),+ goes to Settings, changes the language, and comes back. The cached set is+ now unusable, so the ordinary interval — which exists for bursts of page+ loads where nothing changed — is exactly the wrong thing to enforce.+ """+ scheduled: list[int] = []++ async def _noop() -> None:+ scheduled.append(1)++ monkeypatch.setattr(suggestions, "_regenerate_if_due", _noop)+ _write_cache(+ isolated_scope,+ {+ "suggestions": [{"label": "\u65e7\u7684", "prompt": "\u65e7\u7684"}],+ "language": "zh",+ "generated_at": time.time(),+ "fingerprint": "x",+ },+ )+ # Spend the throttle, as a first page load would.+ suggestions._last_probe[suggestions._scope_key()] = time.monotonic()++ result = await suggestions.get_suggestions() # setting now says "en"+ await asyncio.gather(*suggestions._inflight.values())++ assert result["suggestions"] == []+ assert scheduled == [1], "the language switch should have forced a probe"+++async def test_a_forced_probe_still_respects_the_in_flight_guard(+ monkeypatch: pytest.MonkeyPatch, no_material+) -> None:+ """Bypassing the interval must not mean fanning out concurrent calls."""+ started = asyncio.Event()+ release = asyncio.Event()+ runs: list[int] = []++ async def _slow() -> None:+ runs.append(1)+ started.set()+ await release.wait()++ monkeypatch.setattr(suggestions, "_regenerate_if_due", _slow)++ suggestions._schedule_probe(force=True)+ await started.wait()+ suggestions._schedule_probe(force=True)+ suggestions._schedule_probe(force=True)++ release.set()+ await asyncio.gather(*suggestions._inflight.values())++ assert runs == [1]++# ── Generation ───────────────────────────────────────────────────────────diff --git a/web/components/chat/home/StarterSuggestions.tsx b/web/components/chat/home/StarterSuggestions.tsxindex 93e36ca43..0ea339107 100644--- a/web/components/chat/home/StarterSuggestions.tsx+++ b/web/components/chat/home/StarterSuggestions.tsx@@ -2,7 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { RefreshCw } from "lucide-react";+import { Loader2, Sparkles } from "lucide-react";import { apiFetch, apiUrl } from "@/lib/api";interface Suggestion {@@ -26,11 +26,26 @@ interface SuggestionPayload {* fresh set exists a moment later — but "a moment" is a model call, which on a* cold provider is comfortably longer than one interval. A few spaced re-reads* cover that without turning into a poll; they stop as soon as something- * arrives, and the first visit of a session is the only time they all run.+ * arrives, and after the last one the manual control takes over.*/const RESETTLE_MS = 3500;const RESETTLE_ATTEMPTS = 4;+/**+ * What the slot is showing.+ *+ * ``idle`` is the important one: it is reached from a cold cache, a generation+ * that produced nothing, a failed request, and a set of re-reads that timed+ * out — every way this can fail to have lines. All of them render the same+ * explicit control, so the answer to "why is there nothing there" is always a+ * button rather than an empty space.+ */+type View =+ | { kind: "loading" }+ | { kind: "ready"; items: Suggestion[] }+ | { kind: "working" }+ | { kind: "idle"; note?: "no-material" };+/*** The three things worth exploring next, under the home composer.*@@ -38,14 +53,15 @@ const RESETTLE_ATTEMPTS = 4;* from what this learner has actually been working on — and sends its* ``prompt`` as their own message, 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.+ * caching and staleness live on the backend; this renders the result, and owns+ * the manual way back when there is nothing to render.*- * There is no fixed fallback, and that is deliberate. The whole value of these- * lines is that they are about *this* learner's material; generic copy in the- * same slot would teach them to ignore it. With nothing in memory to draw on,- * the component renders nothing at all and the home screen looks exactly as it- * did before.+ * There is no generic fallback copy: the value of these lines is that they are+ * about *this* learner's material, and filler in the same slot would teach+ * people to stop reading it. But "no lines" is not the same as "no slot" — a+ * cold cache, a model that failed, or an output-language switch that+ * invalidated the cache all leave a visible control that regenerates on+ * demand.** One per line, left-aligned to the composer's own edge, with no border or* fill: these name specific ideas, and a specific sentence in a pill reads as@@ -61,21 +77,21 @@ export default function StarterSuggestions({disabled?: boolean;}) {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[]>([]);- const [refreshing, setRefreshing] = useState(false);+ // Everything generated here is 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. Only this component's+ // own chrome is translated.+ const [view, setView] = useState<View>({ kind: "loading" });const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const load = useCallback(async (signal?: AbortSignal): Promise<SuggestionPayload | null> => {try {- const response = await apiFetch(- apiUrl("/api/v1/dashboard/suggestions"),- { signal, cache: "no-store" },- );+ const response = await apiFetch(apiUrl("/api/v1/dashboard/suggestions"), {+ signal,+ cache: "no-store",+ });if (!response.ok) return null;return (await response.json()) as SuggestionPayload;} catch {@@ -89,23 +105,32 @@ export default function StarterSuggestions({const controller = new AbortController();void (async () => {const payload = await load(controller.signal);- if (!payload) return;- setItems(payload.suggestions);- if (!payload.stale) return;- // A fresher set is being generated — which is also the ordinary first- // visit, where memory has material but nothing has been generated from- // it yet. Collect it as it lands rather than poll: the first look is- // early enough for a cache hit, the later ones cover a slow model.+ if (controller.signal.aborted) return;+ if (payload?.suggestions.length) {+ setView({ kind: "ready", items: payload.suggestions });+ return;+ }+ // Nothing yet. If the backend says a set is on its way, wait for it and+ // show that something is happening; otherwise hand over the control.+ if (!payload?.stale) {+ setView({ kind: "idle", note: payload ? "no-material" : undefined });+ return;+ }+ setView({ kind: "working" });let attempt = 0;const collect = () => {void load(controller.signal).then((next) => {+ if (controller.signal.aborted) return;if (next?.suggestions.length) {- setItems(next.suggestions);+ setView({ kind: "ready", items: next.suggestions });return;}- if (++attempt < RESETTLE_ATTEMPTS && !controller.signal.aborted) {+ if (++attempt < RESETTLE_ATTEMPTS) {timerRef.current = setTimeout(collect, RESETTLE_MS);+ return;}+ // Gave it long enough. Stop spinning and let the learner decide.+ setView({ kind: "idle" });});};timerRef.current = setTimeout(collect, RESETTLE_MS);@@ -116,70 +141,97 @@ export default function StarterSuggestions({};}, [load]);- const reroll = useCallback(async () => {- setRefreshing(true);+ const generate = useCallback(async () => {+ if (timerRef.current) clearTimeout(timerRef.current);+ setView({ kind: "working" });try {const response = await apiFetch(apiUrl("/api/v1/dashboard/suggestions/refresh"),{ method: "POST" },);- if (response.ok) {- const payload = (await response.json()) as SuggestionPayload;- // Keep what is on screen when the reroll came back empty: replacing- // three usable lines with nothing is worse than not rerolling.- if (payload.suggestions.length) setItems(payload.suggestions);+ if (!response.ok) {+ setView({ kind: "idle" });+ return;}+ const payload = (await response.json()) as SuggestionPayload;+ setView(+ payload.suggestions.length+ ? { kind: "ready", items: payload.suggestions }+ : { kind: "idle", note: "no-material" },+ );} catch {- // A failed reroll is not worth an error message.- } finally {- setRefreshing(false);+ // A failed generation is not worth an error banner; the control stays.+ setView({ kind: "idle" });}}, []);- if (!items.length) return null;+ // Only the very first read renders nothing: lines appearing a beat late is+ // calmer than a control that flashes and is immediately replaced.+ if (view.kind === "loading") return null;return (// 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">- {items.map((item) => (- <li key={item.label} className="max-w-full">- <button- type="button"- disabled={disabled}- onClick={() => onPick(item.prompt)}- title={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">{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"+ {view.kind === "ready" && (+ <ul className="flex flex-col items-start">+ {view.items.map((item) => (+ <li key={item.label} className="max-w-full">+ <button+ type="button"+ disabled={disabled}+ onClick={() => onPick(item.prompt)}+ title={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>- </button>- </li>- ))}- </ul>- <button- type="button"- onClick={() => void reroll()}- disabled={refreshing || disabled}- title={t("Suggest something else")}- 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={11}- strokeWidth={1.8}- className={refreshing ? "animate-spin" : ""}- />- {t("Suggest something else")}- </button>+ <span className="truncate">{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>+ )}++ <div className="flex items-center gap-2.5 pt-1.5">+ <button+ type="button"+ onClick={() => void generate()}+ disabled={view.kind === "working" || disabled}+ className={`inline-flex items-center gap-1.5 text-[11.5px] transition-all duration-200 hover:text-[var(--foreground)] disabled:cursor-default ${+ // While there are lines this is a quiet reroll that surfaces on+ // hover; with nothing to show it is the only way forward, so it+ // stays visible.+ view.kind === "ready"+ ? "text-[color-mix(in_srgb,var(--muted-foreground)_55%,transparent)] opacity-0 focus-visible:opacity-100 group-hover/starters:opacity-100"+ : "text-[var(--muted-foreground)]"+ }`}+ >+ {view.kind === "working" ? (+ <Loader2 size={11} strokeWidth={1.8} className="animate-spin" />+ ) : (+ <Sparkles size={11} strokeWidth={1.8} />+ )}+ {view.kind === "working"+ ? t("Finding what to explore next...")+ : view.kind === "ready"+ ? t("Suggest something else")+ : t("Suggest what to explore next")}+ </button>++ {view.kind === "idle" && view.note === "no-material" && (+ <span className="text-[11.5px] text-[color-mix(in_srgb,var(--muted-foreground)_70%,transparent)]">+ {t("Not enough history yet — have a conversation first.")}+ </span>+ )}+ </div></div>);}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 8bdece002..7f0c55a75 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -312,6 +312,9 @@"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 what to explore next": "Suggest what to explore next",+ "Finding what to explore next...": "Finding what to explore next...",+ "Not enough history yet — have a conversation first.": "Not enough history yet — have a conversation first.","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",@@ -2999,5 +3002,42 @@"Container available": "Container available","{{used}} · {{percent}}% of {{total}}": "{{used}} · {{percent}}% of {{total}}","(backend only)": "(backend only)",- "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "Only the backend and its own children. Start DeepTutor through the launcher to include the web server."+ "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.",+ "Generate all chapters": "Generate all chapters",+ "First chapter only": "First chapter only",+ "Confirm spine": "Confirm spine",+ "Chapters will be generated the first time you open them — useful when you want to read as you go, or keep an eye on model usage.": "Chapters will be generated the first time you open them — useful when you want to read as you go, or keep an eye on model usage.",+ "~{{count}} words": "~{{count}} words",+ "~{{count}} min to generate": "~{{count}} min to generate",+ "Generation paused": "Generation paused",+ "Your model provider kept refusing requests, so the remaining chapters were left untouched rather than half-written. Everything generated so far is saved.": "Your model provider kept refusing requests, so the remaining chapters were left untouched rather than half-written. Everything generated so far is saved.",+ "Resume generation": "Resume generation",+ "Resuming…": "Resuming…",+ "Compilation paused: {{reason}}": "Compilation paused: {{reason}}",+ "repeated provider errors": "repeated provider errors",+ "Could not resume: {{message}}": "Could not resume: {{message}}",+ "Continue reading": "Continue reading",+ "Start reading": "Start reading",+ "Continue setup": "Continue setup",+ "{{percent}}% read": "{{percent}}% read",+ "Read": "Read",+ "Unread": "Unread",+ "Bookmark this chapter": "Bookmark this chapter",+ "Remove bookmark": "Remove bookmark",+ "← / → to turn pages": "← / → to turn pages",+ "Edit text": "Edit text",+ "Edit note": "Edit note",+ "Empty note — click to start writing your own annotation.": "Empty note — click to start writing your own annotation.",+ "Empty note.": "Empty note.",+ "Markdown supported. ⌘/Ctrl + Enter to save.": "Markdown supported. ⌘/Ctrl + Enter to save.",+ "Markdown supported. ⌘/Ctrl + Enter to save, Esc to cancel.": "Markdown supported. ⌘/Ctrl + Enter to save, Esc to cancel.",+ "Could not save your edit: {{message}}": "Could not save your edit: {{message}}",+ "How did you do?": "How did you do?",+ "Missed it": "Missed it",+ "Missed one? I can add a worked explanation and an easier set.": "Missed one? I can add a worked explanation and an easier set.",+ "Add extra practice": "Add extra practice",+ "Adding…": "Adding…",+ "Could not add extra practice: {{message}}": "Could not add extra practice: {{message}}",+ "Compile failed: {{message}}": "Compile failed: {{message}}",+ "Regenerate block failed: {{message}}": "Regenerate block failed: {{message}}"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex e2061798d..ad11a5227 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -312,6 +312,9 @@"Loading starter settings...": "正在加载起始建议设置…","Failed to load starter settings.": "加载起始建议设置失败。","Failed to save starter settings.": "保存起始建议设置失败。",+ "Suggest what to explore next": "生成学习引导",+ "Finding what to explore next...": "正在寻找值得探索的方向…",+ "Not enough history yet — have a conversation first.": "学习记录还不够,先聊几句吧。","Suggest something else": "换一批","Ask anything — I'm here to help you understand.": "随便问——我来帮你搞懂。","Welcome to DeepTutor": "欢迎使用 DeepTutor",@@ -2999,5 +3002,42 @@"Container available": "容器可用","{{used}} · {{percent}}% of {{total}}": "{{used}} · 占 {{total}} 的 {{percent}}%","(backend only)": "(仅后端)",- "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "仅统计后端及其子进程。通过 DeepTutor 启动器运行才能把前端服务一起算进来。"+ "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "仅统计后端及其子进程。通过 DeepTutor 启动器运行才能把前端服务一起算进来。",+ "Generate all chapters": "生成全部章节",+ "First chapter only": "只生成第一章",+ "Confirm spine": "确认大纲",+ "Chapters will be generated the first time you open them — useful when you want to read as you go, or keep an eye on model usage.": "章节会在你第一次打开时生成——适合边读边生成,或者想控制模型用量的场景。",+ "~{{count}} words": "约 {{count}} 字",+ "~{{count}} min to generate": "预计生成 {{count}} 分钟",+ "Generation paused": "生成已暂停",+ "Your model provider kept refusing requests, so the remaining chapters were left untouched rather than half-written. Everything generated so far is saved.": "模型提供方持续拒绝请求,因此剩余章节保持未生成状态,而不是留下一堆半成品。已生成的内容都已保存。",+ "Resume generation": "继续生成",+ "Resuming…": "正在继续…",+ "Compilation paused: {{reason}}": "生成已暂停:{{reason}}",+ "repeated provider errors": "模型服务连续报错",+ "Could not resume: {{message}}": "无法继续生成:{{message}}",+ "Continue reading": "继续阅读",+ "Start reading": "开始阅读",+ "Continue setup": "继续设置",+ "{{percent}}% read": "已读 {{percent}}%",+ "Read": "已读",+ "Unread": "未读",+ "Bookmark this chapter": "收藏本章",+ "Remove bookmark": "取消收藏",+ "← / → to turn pages": "← / → 翻页",+ "Edit text": "编辑正文",+ "Edit note": "编辑笔记",+ "Empty note — click to start writing your own annotation.": "空笔记——点击开始写下你的批注。",+ "Empty note.": "空笔记。",+ "Markdown supported. ⌘/Ctrl + Enter to save.": "支持 Markdown,⌘/Ctrl + Enter 保存。",+ "Markdown supported. ⌘/Ctrl + Enter to save, Esc to cancel.": "支持 Markdown,⌘/Ctrl + Enter 保存,Esc 取消。",+ "Could not save your edit: {{message}}": "保存修改失败:{{message}}",+ "How did you do?": "你答对了吗?",+ "Missed it": "答错了",+ "Missed one? I can add a worked explanation and an easier set.": "有做错的?可以补一段详解和一组更简单的练习。",+ "Add extra practice": "补充练习",+ "Adding…": "正在生成…",+ "Could not add extra practice: {{message}}": "补充练习失败:{{message}}",+ "Compile failed: {{message}}": "生成失败:{{message}}",+ "Regenerate block failed: {{message}}": "重新生成模块失败:{{message}}"}