Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(mastery): group study conversations, and let the tutor suggest what to ask

Bingxi Zhao (Frank)47c00260aa5c
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index 0778a6e41..7871340f2 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -304,6 +304,36 @@ async def list_topics():
return {"topics": topics}
[email protected]("/topics/index")
+async def list_topic_index():
+ """Just enough to *name* a topic: id, title, emoji.
+
+ The sidebar groups study conversations under their topic, and it refreshes
+ on every stream end. ``/topics`` answers with each path's whole knowledge
+ map, review queue and source excerpts — kilobytes per topic, none of which
+ a group header renders. This is the same walk with the payload cut to what
+ a label needs.
+
+ Declared above ``/topics/{path_id}``: that route matches any single
+ segment, so a literal path below it would never be reached.
+ """
+ store = LearningStore()
+ return {
+ "topics": await asyncio.to_thread(
+ lambda: [
+ {
+ "path_id": progress.book_id,
+ "name": learning_policy.path_display_name(progress),
+ "emoji": topic.metadata.emoji,
+ }
+ for progress, topic, _session_count, _interaction in store.list_topic_snapshots(
+ status="active"
+ )
+ ]
+ )
+ }
+
+
@router.post("/topics/draft")
async def generate_topic_route(body: GenerateTopicDraftRequest):
from deeptutor.learning.topic_generation import TopicGenerationError, generate_topic_draft
@@ -466,6 +496,19 @@ async def list_topic_sessions(path_id: str):
return {"path_id": path_id, "sessions": sessions}
[email protected]("/topics/{path_id}/ask-hint")
+async def get_topic_ask_hint(path_id: str, session_id: str = ""):
+ """One question the learner could ask here, for the composer placeholder.
+
+ Written by the task model, never blocking: an empty ``hint`` means the
+ composer keeps the static placeholder it has always had.
+ """
+ _validate_book_id(path_id)
+ from deeptutor.services.mastery_hints import get_ask_hint
+
+ return await get_ask_hint(path_id, session_id)
+
+
@router.websocket("/ws")
async def mastery_topic_websocket(ws: WebSocket) -> None:
"""Subscribe to one living topic with durable revision replay."""
diff --git a/deeptutor/services/mastery_hints.py b/deeptutor/services/mastery_hints.py
new file mode 100644
index 000000000..f6dbfa2e2
--- /dev/null
+++ b/deeptutor/services/mastery_hints.py
@@ -0,0 +1,410 @@
+"""Ask-hints — the line the study composer shows before the learner types.
+
+The placeholder used to be ``Ask your tutor about "<waypoint>"…``, which is the
+third time that waypoint's name appears on the screen and proposes nothing. A
+learner who is stuck is stuck on *what to ask*, and a template cannot help with
+that because it does not know what was just said.
+
+So the line is written, per waypoint, by the task model: one question the
+learner could ask right now, in their own voice, that the tutor's last message
+did not already answer.
+
+It is a question, never an answer
+---------------------------------
+The single hard rule. This runs on a mastery path, where the whole product
+premise is that the learner produces the understanding. A hint that leaks the
+answer ("Because the router picks the tool from the intent…") removes the work
+the path exists to make them do. The system prompt says so, and
+:func:`_sanitize` drops anything that does not end in a question mark.
+
+Never blocks anything
+---------------------
+The composer is fully usable while this is in flight — the static placeholder
+stands until a hint arrives, and a failure just means it keeps standing. So the
+call is made synchronously under a short timeout rather than through a
+stale-while-revalidate cache: nothing on screen is waiting for it, and a hint
+that arrives two seconds late is still the first thing the learner reads.
+
+What is cached is the *result*, keyed on the conversation's own position
+(:func:`_cache_key`) — the path, the waypoint, and how far the transcript has
+got. Remounting the study screen, toggling the outline or switching tabs all
+land on the same key and cost nothing; sending a message moves it, which is
+exactly when a new question is worth writing.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+import logging
+import time
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# A placeholder is read in the half-second before typing, so it has to be
+# scannable at a glance. These are the same per-language bounds the starter
+# suggestions use, for the same reason: a character is not a unit of meaning.
+_MAX_HINT_CHARS = {"zh": 44, "en": 110}
+# Bounded because it sits on a request path. The composer shows its static
+# placeholder until this returns, so an overrun costs a nicety, not a screen.
+_LLM_TIMEOUT = 12.0
+# How much of the transcript reaches the prompt. The last exchange is what a
+# follow-up question has to avoid repeating; anything older is already
+# summarized by where the waypoint sits.
+_HISTORY_TURNS = 4
+_MAX_MESSAGE_CHARS = 700
+# Entries are tiny and keyed on transcript position, so a session generates a
+# handful over its life. The cap is a leak guard, not a tuning knob.
+_CACHE_LIMIT = 256
+_CACHE_TTL_SECONDS = 30 * 60
+
+
+@dataclass(frozen=True, slots=True)
+class AskHint:
+ """One question the learner could ask, and what it was written for."""
+
+ hint: str
+ knowledge_point_id: str
+ generated_at: float
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "hint": self.hint,
+ "knowledge_point_id": self.knowledge_point_id,
+ "generated_at": self.generated_at,
+ }
+
+
+_cache: dict[str, AskHint] = {}
+# One in-flight generation per key: opening the same study screen in two tabs
+# must not become two LLM calls.
+_inflight: dict[str, asyncio.Task[AskHint]] = {}
+
+
+def _cache_key(path_id: str, kp_id: str, anchor: str) -> str:
+ return f"{path_id}\0{kp_id}\0{anchor}"
+
+
+def _remember(key: str, value: AskHint) -> None:
+ _cache[key] = value
+ if len(_cache) > _CACHE_LIMIT:
+ # Oldest first. dicts preserve insertion order, and every write here is
+ # a fresh key, so the head is the least recently generated.
+ for stale in list(_cache)[: len(_cache) - _CACHE_LIMIT]:
+ _cache.pop(stale, None)
+
+
+def _recall(key: str) -> AskHint | None:
+ value = _cache.get(key)
+ if value is None:
+ return None
+ if time.time() - value.generated_at > _CACHE_TTL_SECONDS:
+ _cache.pop(key, None)
+ return None
+ return value
+
+
+# ── Material ─────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True, slots=True)
+class _Material:
+ """What the model is told: where the learner is, and what was just said."""
+
+ path_name: str
+ goal: str
+ module_name: str
+ waypoint: str
+ waypoint_type: str
+ status: str
+ transcript: list[tuple[str, str]]
+ anchor: str
+
+ def __bool__(self) -> bool:
+ return bool(self.waypoint)
+
+
+def _load_position(path_id: str) -> tuple[str, str, str, str, str, str, str]:
+ """``(path_name, goal, module, waypoint, kp_type, status, kp_id)``.
+
+ Reads the same policy the tutor and the outline read, so the hint is about
+ the waypoint the screen says the learner is on rather than a second guess
+ at it.
+ """
+ from deeptutor.learning import policy as learning_policy
+ from deeptutor.learning.storage import LearningStore
+
+ store = LearningStore()
+ progress = store.load(path_id)
+ if progress is None:
+ return ("", "", "", "", "", "", "")
+ step = learning_policy.next_objective(progress)
+ kp, _module_id, module_name = learning_policy.find_knowledge_point(
+ progress, step.knowledge_point_id
+ )
+ # The goal lives on the topic, not on the progress aggregate. Description
+ # first: it is the sentence a learner wrote about what they are after,
+ # whereas ``goal`` is often just the topic's own name typed twice.
+ topic = store.get_topic(path_id, progress=progress)
+ goal = ""
+ if topic is not None:
+ goal = str(topic.metadata.description or topic.metadata.goal or "")
+ return (
+ learning_policy.path_display_name(progress),
+ goal,
+ module_name,
+ step.knowledge_point_name or (kp.name if kp else ""),
+ step.knowledge_point_type,
+ step.status or "",
+ step.knowledge_point_id,
+ )
+
+
+async def _load_transcript(session_id: str) -> tuple[list[tuple[str, str]], str]:
+ """The tail of the conversation, plus an anchor for where it has got to.
+
+ The anchor is what the cache keys on. It is derived from the transcript
+ itself rather than from a timestamp so that reopening a finished session
+ reuses its hint instead of writing a new one every visit.
+ """
+ if not session_id:
+ return ([], "")
+ try:
+ from deeptutor.services.session import get_session_store
+
+ session = await get_session_store().get_session_with_messages(session_id)
+ except Exception:
+ logger.debug("ask-hint: session %s unreadable", session_id, exc_info=True)
+ return ([], "")
+ if not session:
+ return ([], "")
+ messages = [
+ message
+ for message in (session.get("messages") or [])
+ if isinstance(message, dict) and str(message.get("role")) in {"user", "assistant"}
+ ]
+ tail: list[tuple[str, str]] = []
+ for message in messages[-_HISTORY_TURNS:]:
+ content = " ".join(str(message.get("content") or "").split())
+ if content:
+ tail.append((str(message.get("role")), content[:_MAX_MESSAGE_CHARS]))
+ return (tail, f"{len(messages)}")
+
+
+async def _collect(path_id: str, session_id: str) -> _Material:
+ position = await asyncio.to_thread(_load_position, path_id)
+ path_name, goal, module_name, waypoint, kp_type, status, kp_id = position
+ transcript, anchor = await _load_transcript(session_id)
+ return _Material(
+ path_name=path_name,
+ goal=goal,
+ module_name=module_name,
+ waypoint=waypoint,
+ waypoint_type=kp_type,
+ status=status,
+ transcript=transcript,
+ anchor=f"{kp_id}:{anchor}",
+ )
+
+
+# ── Generation ───────────────────────────────────────────────────────────
+
+
+_SYSTEM_EN = """You write ONE question a learner could ask their tutor right now.
+
+You are given where they are on a mastery path and the tail of their conversation. Write the question they would ask next if they knew what to ask.
+
+Hard rule: you write the QUESTION, never the answer. No explanation, no hint at the answer, no "because". If your line teaches the point, it is wrong — the learner is supposed to work that out with the tutor.
+
+Rules:
+- Reply with the question alone. No quotes, no prefix, no markdown, no trailing commentary.
+- First person, as the learner would type it. Under 14 words.
+- End with a question mark.
+- It must be about the current waypoint, and it must not ask something the tutor's last message already answered.
+- Prefer the question that opens the point up: a distinction, a why, a boundary case, a "what happens if". Avoid yes/no questions and avoid asking for a definition the conversation already gave.
+
+Good: "Why does the router need the intent and not just the query?"
+Good: "What breaks if I skip the reflection step?"
+Bad: "Can you explain routing?" <- asks for a lecture, names no edge
+Bad: "Routing picks the tool by intent — right?" <- states the answer"""
+
+_SYSTEM_ZH = """你要写出学习者此刻**可以问导师的一个问题**。
+
+给你的是他在精通路径上的位置,以及这段对话的结尾。写出他如果知道该问什么、接下来会问的那个问题。
+
+硬规则:你写的是**问题**,绝不是答案。不要解释、不要暗示答案、不要出现"因为"。如果你这行字把知识点讲出来了,那就是错的——那部分应该由学习者和导师一起做出来。
+
+规则:
+- 只回复那个问题本身。不要引号、不要前缀、不要 markdown、不要任何补充说明。
+- 第一人称,像学习者自己打出来的。不超过 25 个字。
+- 以问号结尾。
+- 必须是关于当前这个知识点的,且不能问导师上一条消息已经回答过的东西。
+- 优先选那种能把问题打开的:一个区别、一个为什么、一个边界情况、一个"如果……会怎样"。避免是非题,也避免去问对话里已经给过的定义。
+
+好:"路由为什么需要意图,而不是只看查询本身?"
+好:"如果跳过反思那一步,会在哪里出问题?"
+差:"能讲讲路由吗?" <- 要的是一段讲解,没点到任何边界
+差:"路由是按意图选工具,对吧?" <- 把答案说出来了"""
+
+
+def _is_zh(language: str) -> bool:
+ return str(language or "en").lower().startswith("zh")
+
+
+def _render(material: _Material, zh: bool) -> str:
+ lines: list[str] = []
+ if zh:
+ lines.append(f"# 学习主题\n{material.path_name}")
+ if material.goal:
+ lines.append(f"# 学习目标\n{material.goal}")
+ where = f"# 当前知识点\n{material.waypoint}"
+ if material.module_name:
+ where += f"(所属模块:{material.module_name})"
+ if material.waypoint_type:
+ where += f"\n类型:{material.waypoint_type}"
+ if material.status:
+ where += f"\n掌握状态:{material.status}"
+ lines.append(where)
+ else:
+ lines.append(f"# Topic\n{material.path_name}")
+ if material.goal:
+ lines.append(f"# Goal\n{material.goal}")
+ where = f"# Current waypoint\n{material.waypoint}"
+ if material.module_name:
+ where += f" (module: {material.module_name})"
+ if material.waypoint_type:
+ where += f"\nType: {material.waypoint_type}"
+ if material.status:
+ where += f"\nStatus: {material.status}"
+ lines.append(where)
+
+ if material.transcript:
+ speaker = {"user": "学习者" if zh else "Learner", "assistant": "导师" if zh else "Tutor"}
+ body = "\n".join(
+ f"[{speaker.get(role, role)}] {text}" for role, text in material.transcript
+ )
+ lines.append(("# 对话结尾\n" if zh else "# End of the conversation\n") + body)
+ else:
+ lines.append(
+ "# 对话结尾\n(还没开始,这是他要问的第一个问题。)"
+ if zh
+ else "# End of the conversation\n(Nothing yet — this is their opening question.)"
+ )
+
+ lines.append("\n请写出那一个问题。" if zh else "\nWrite that one question.")
+ return "\n\n".join(lines)
+
+
+def _sanitize(raw: str, language: str) -> str:
+ """One clean question, or nothing.
+
+ The question mark is a real check, not tidying: it is the cheapest reliable
+ signal that the model wrote a question rather than the answer it was told
+ not to write.
+ """
+ text = " ".join(str(raw or "").split())
+ # Models reach for a fence or a leading bullet even when told not to.
+ for fence in ("```", "「", "」", '"', "'", "“", "”", "‘", "’"):
+ text = text.replace(fence, "")
+ text = text.lstrip("-•*# ").strip()
+ if not text:
+ return ""
+ # A model that ignored "the question alone" usually answers first and asks
+ # last; keep the final sentence rather than discarding a usable question.
+ if "\n" in text:
+ text = text.split("\n")[-1].strip()
+ if not text.endswith(("?", "?")):
+ return ""
+ limit = _MAX_HINT_CHARS["zh"] if _is_zh(language) else _MAX_HINT_CHARS["en"]
+ if len(text) > limit:
+ return ""
+ return text
+
+
+async def _generate(path_id: str, session_id: str, key_hint: str) -> AskHint:
+ material = await _collect(path_id, session_id)
+ empty = AskHint(hint="", knowledge_point_id=key_hint, generated_at=time.time())
+ if not material:
+ return empty
+
+ from deeptutor.services.settings.interface_settings import get_response_language
+
+ try:
+ language = get_response_language(default="en")
+ except Exception:
+ logger.debug("ask-hint: response language unreadable", exc_info=True)
+ language = "en"
+ zh = _is_zh(language)
+
+ try:
+ from deeptutor.services.llm import complete
+ from deeptutor.services.model_selection.tasks import task_llm_scope
+
+ # Same call class as titles and starter lines — short, frequent, and
+ # nobody asked for it — so it runs on the task model when one is set.
+ with task_llm_scope():
+ raw = await asyncio.wait_for(
+ complete(
+ prompt=_render(material, zh),
+ system_prompt=_SYSTEM_ZH if zh else _SYSTEM_EN,
+ temperature=0.7,
+ max_tokens=120,
+ max_retries=0,
+ ),
+ timeout=_LLM_TIMEOUT,
+ )
+ except asyncio.TimeoutError:
+ logger.debug("ask-hint LLM call timed out")
+ return empty
+ except Exception:
+ logger.debug("ask-hint LLM call failed", exc_info=True)
+ return empty
+
+ return AskHint(
+ hint=_sanitize(raw, language),
+ knowledge_point_id=material.anchor.split(":", 1)[0],
+ generated_at=time.time(),
+ )
+
+
+# ── Public API ───────────────────────────────────────────────────────────
+
+
+async def get_ask_hint(path_id: str, session_id: str = "") -> dict[str, Any]:
+ """The question to offer under the composer. ``hint`` is "" when there is none.
+
+ An empty hint is a real answer, not an error: the composer keeps its static
+ placeholder, which is what it showed before this existed.
+ """
+ material = await _collect(path_id, session_id)
+ if not material:
+ return AskHint(hint="", knowledge_point_id="", generated_at=time.time()).to_dict()
+
+ key = _cache_key(path_id, material.anchor, session_id)
+ cached = _recall(key)
+ if cached is not None:
+ return cached.to_dict()
+
+ pending = _inflight.get(key)
+ if pending is None or pending.done():
+ pending = asyncio.ensure_future(_generate(path_id, session_id, material.anchor))
+ _inflight[key] = pending
+ try:
+ value = await pending
+ except Exception:
+ logger.debug("ask-hint generation failed", exc_info=True)
+ return AskHint(hint="", knowledge_point_id="", generated_at=time.time()).to_dict()
+ finally:
+ if _inflight.get(key) is pending:
+ _inflight.pop(key, None)
+
+ # Only a usable hint is cached. Caching the empty result would pin a
+ # transient failure — a timeout, a model that answered instead of asking —
+ # in place for the whole TTL, and the next visit would never retry.
+ if value.hint:
+ _remember(key, value)
+ return value.to_dict()
+
+
+__all__ = ["AskHint", "get_ask_hint"]
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 6244d7467..d2a487152 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -263,6 +263,7 @@ export default memo(function ChatComposer({
onCancelStreaming,
prefillInputRef,
inputPlaceholder,
+ inputPlaceholderCompletion,
showCapabilityChip = true,
}: {
composerRef: RefObject<HTMLDivElement | null>;
@@ -386,6 +387,8 @@ export default memo(function ChatComposer({
prefillInputRef?: React.MutableRefObject<((text: string) => void) | null>;
/** Override the composer placeholder (e.g. quiz follow-up). */
inputPlaceholder?: string;
+ /** A line Tab accepts while the composer is empty. See ComposerInput. */
+ inputPlaceholderCompletion?: string;
/**
* Hide the capability chip. A surface that only ever runs one capability
* — and names it in its own chrome — gains nothing from a picker that
@@ -789,6 +792,7 @@ export default memo(function ChatComposer({
: undefined
}
placeholder={inputPlaceholder}
+ placeholderCompletion={inputPlaceholderCompletion}
minHeight={hasMessages ? 28 : 64}
/>
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 697317a4d..49f84f378 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -73,6 +73,16 @@ interface ComposerInputProps {
* main chat ("How can I help you today?") / visualize defaults.
*/
placeholder?: string;
+ /**
+ * A line Tab accepts into the empty composer.
+ *
+ * The mastery study screen offers a question the learner could ask; reading
+ * it and then retyping it is exactly the work the offer was meant to save,
+ * so Tab takes it. Only while the composer is empty — past the first
+ * character the learner is writing their own question, and stealing Tab
+ * there would break moving focus out of the box.
+ */
+ placeholderCompletion?: string;
/**
* Minimum textarea height in pixels. The auto-sized hook grows the
* textarea past this as the user types. Bumped on the empty-state
@@ -152,6 +162,7 @@ export const ComposerInput = memo(
onSelectMemoryPicker,
onOpenPersonaSelector,
placeholder,
+ placeholderCompletion,
minHeight = 28,
},
ref,
@@ -309,6 +320,19 @@ export const ComposerInput = memo(
handleSelectAgentMention(filteredAgents[0].name);
return;
}
+ // Tab takes the offered question — but only into an empty composer, so
+ // Tab keeps meaning "leave this box" the moment there is a draft in it.
+ if (
+ e.key === "Tab" &&
+ !e.shiftKey &&
+ placeholderCompletion &&
+ !inputRef.current.trim()
+ ) {
+ e.preventDefault();
+ setInputBoth(placeholderCompletion);
+ onInputChange(placeholderCompletion);
+ return;
+ }
if (shouldSubmitOnEnter(e, isComposingRef.current)) {
e.preventDefault();
if (!isStreaming) doSend();
@@ -327,6 +351,9 @@ export const ComposerInput = memo(
filteredAgents,
handleSelectAgentMention,
isComposingRef,
+ onInputChange,
+ placeholderCompletion,
+ setInputBoth,
],
);
@@ -526,6 +553,15 @@ export const ComposerInput = memo(
className="w-full resize-none overflow-hidden bg-transparent text-[16px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
style={{ transition: "height 0.15s ease-out" }}
/>
+ {/* An offer nobody can find is not an offer: the key that takes the
+ question is named next to it, and only while it would work. */}
+ {placeholderCompletion && !input.trim() ? (
+ <div className="pointer-events-none flex justify-end pt-1">
+ <span className="rounded border border-[var(--border)]/70 px-1 py-px text-[10px] font-medium leading-none text-[var(--muted-foreground)]/70">
+ {t("Tab to ask this")}
+ </span>
+ </div>
+ ) : null}
</div>
);
}),
diff --git a/web/components/chat/home/StandaloneComposer.tsx b/web/components/chat/home/StandaloneComposer.tsx
index 6ff701bc2..3b76a276f 100644
--- a/web/components/chat/home/StandaloneComposer.tsx
+++ b/web/components/chat/home/StandaloneComposer.tsx
@@ -45,6 +45,7 @@ import {
import { listLLMOptions, type LLMOption } from "@/lib/llm-options";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { SpaceMemoryFile } from "@/lib/space-items";
+import { getSubagentSettings } from "@/lib/subagents-api";
import type { LLMSelection } from "@/lib/unified-ws";
const NotebookRecordPicker = dynamic(
@@ -96,6 +97,13 @@ export interface StandaloneComposerSubmission {
memoryReferences: SpaceMemoryFile[];
persona: string | null;
llmSelection: LLMSelection | null;
+ /**
+ * How many times DeepTutor may consult the selected agent this turn, or
+ * null when no agent is selected. Travels on the submission rather than in
+ * `knowledgeBases` because it is a per-turn budget, and the caller is the
+ * one that owns the request config it belongs in.
+ */
+ subagentBudget: number | null;
}
/** Single-entry capability list for surfaces locked to plain chat. */
@@ -117,6 +125,8 @@ interface StandaloneComposerProps {
/** The live turn is paused on an ask_user card and needs an answer. */
awaitingUserReply?: boolean;
inputPlaceholder?: string;
+ /** A line Tab accepts while the composer is empty. See ComposerInput. */
+ inputPlaceholderCompletion?: string;
/**
* Capability chip contents. Defaults to a locked "Chat" entry — pass a
* one-entry list to relabel it, or several to make the chip a picker.
@@ -136,6 +146,14 @@ interface StandaloneComposerProps {
onKnowledgeBasesChange?: (names: string[]) => void;
llmSelection?: LLMSelection | null;
onLLMSelectionChange?: (selection: LLMSelection | null) => void;
+ /**
+ * The persona pinned for this conversation. Session-level like the KB scope
+ * above: passing the pair mounts the toolbar's persona chip (and with it the
+ * `/persona` slash command), omitting it leaves persona as the one-shot the
+ * "+" menu offers. `ChatComposer` gates the chip on the setter's presence.
+ */
+ personaSelection?: string;
+ onPersonaSelectionChange?: (persona: string) => void;
/** Hide the My Agents reference entry. */
agentsAvailable?: boolean;
/** Receives a function that drops text into the textarea (ask_user chips). */
@@ -149,6 +167,7 @@ function StandaloneComposerImpl({
hasMessages,
awaitingUserReply = false,
inputPlaceholder,
+ inputPlaceholderCompletion,
capabilities,
activeCapValue,
onSelectCapability,
@@ -157,6 +176,8 @@ function StandaloneComposerImpl({
onKnowledgeBasesChange,
llmSelection: controlledLLMSelection,
onLLMSelectionChange,
+ personaSelection,
+ onPersonaSelectionChange,
agentsAvailable = false,
prefillInputRef,
}: StandaloneComposerProps) {
@@ -207,6 +228,9 @@ function StandaloneComposerImpl({
const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);
const [showPersonaPicker, setShowPersonaPicker] = useState(false);
const [showMemoryPicker, setShowMemoryPicker] = useState(false);
+ // Chrome for the toolbar's persona chip. Local even when the value itself is
+ // the caller's: whether a dropdown is open is nobody else's business.
+ const [personaSelectorOpen, setPersonaSelectorOpen] = useState(false);
// ── Shared data (KBs + LLMs) ──────────────────────────────────
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBaseSummary[]>(
@@ -228,13 +252,7 @@ function StandaloneComposerImpl({
const run = async () => {
try {
const list = await listKnowledgeBases({ force: false });
- // Connected subagents travel the same request path but are their own
- // composer control, so they never belong in the knowledge picker.
- if (!cancelled) {
- setKnowledgeBases(
- list.filter((kb) => kb.metadata?.type !== "subagent"),
- );
- }
+ if (!cancelled) setKnowledgeBases(list);
} catch {
if (!cancelled) setKnowledgeBases([]);
}
@@ -245,6 +263,34 @@ function StandaloneComposerImpl({
};
}, []);
+ // Connected subagents arrive as `type: subagent` knowledge bases and travel
+ // the same request path, but they are a different question — "who else
+ // should DeepTutor ask" rather than "what should it read" — so they get
+ // their own chip and never appear in the knowledge picker.
+ const agentNameSet = useMemo(
+ () =>
+ new Set(
+ knowledgeBases
+ .filter((kb) => kb.metadata?.type === "subagent")
+ .map((kb) => kb.name),
+ ),
+ [knowledgeBases],
+ );
+ const kbOptions = useMemo(
+ () => knowledgeBases.filter((kb) => kb.metadata?.type !== "subagent"),
+ [knowledgeBases],
+ );
+ const agentOptions = useMemo(
+ () =>
+ knowledgeBases
+ .filter((kb) => kb.metadata?.type === "subagent")
+ .map((kb) => ({
+ name: kb.name,
+ kind: kb.metadata?.agent_kind as string | undefined,
+ })),
+ [knowledgeBases],
+ );
+
useEffect(() => {
let cancelled = false;
const run = async () => {
@@ -488,6 +534,43 @@ function StandaloneComposerImpl({
[applyKnowledgeBases, knowledgeBases, selectedKnowledgeBases],
);
+ // The selected agent lives *in* `selectedKnowledgeBases` — one list reaches
+ // the backend, and an agent is a member of it — so there is no second piece
+ // of state to keep in step. What the pickers see is the split view of it.
+ const selectedAgent = useMemo(
+ () => selectedKnowledgeBases.find((name) => agentNameSet.has(name)) ?? null,
+ [agentNameSet, selectedKnowledgeBases],
+ );
+ const selectedKbOnly = useMemo(
+ () => selectedKnowledgeBases.filter((name) => !agentNameSet.has(name)),
+ [agentNameSet, selectedKnowledgeBases],
+ );
+ const handleSelectAgent = useCallback(
+ (name: string | null) => {
+ // Single-select: drop whichever agent was there, then add the new one.
+ const withoutAgents = selectedKnowledgeBases.filter(
+ (item) => !agentNameSet.has(item),
+ );
+ applyKnowledgeBases(name ? [...withoutAgents, name] : withoutAgents);
+ },
+ [agentNameSet, applyKnowledgeBases, selectedKnowledgeBases],
+ );
+ // Seeded from the configured default; the chip's stepper overrides it for
+ // the next turn. Null until the setting loads, which is also what "no agent
+ // selected" looks like — neither case has a budget to send.
+ const [subagentBudget, setSubagentBudget] = useState<number | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ void getSubagentSettings()
+ .then((settings) => {
+ if (!cancelled) setSubagentBudget(settings.consult_budget);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
const handleClearPersona = useCallback(() => setSelectedPersona(null), []);
const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {
setSelectedMemoryFiles((prev) =>
@@ -571,6 +654,7 @@ function StandaloneComposerImpl({
memoryReferences: [...selectedMemoryFiles],
persona: selectedPersona,
llmSelection,
+ subagentBudget: selectedAgent ? subagentBudget : null,
});
// One-shot references are consumed by the send; the knowledge-base
@@ -590,6 +674,7 @@ function StandaloneComposerImpl({
llmSelection,
notebookReferencesPayload,
onSubmit,
+ selectedAgent,
selectedBookReferences,
selectedHistorySessions,
selectedKnowledgeBases,
@@ -597,6 +682,7 @@ function StandaloneComposerImpl({
selectedNotebookRecords,
selectedPersona,
selectedQuestionEntries,
+ subagentBudget,
],
);
@@ -628,7 +714,16 @@ function StandaloneComposerImpl({
attachments={attachments}
attachmentError={attachmentError}
activeCap={activeCap}
- knowledgeBases={knowledgeBases}
+ knowledgeBases={kbOptions}
+ connectedAgents={agentOptions}
+ selectedAgent={selectedAgent}
+ onSelectAgent={handleSelectAgent}
+ subagentBudget={subagentBudget}
+ onSubagentBudgetChange={setSubagentBudget}
+ personaSelection={personaSelection}
+ onPersonaSelectionChange={onPersonaSelectionChange}
+ personaSelectorOpen={personaSelectorOpen}
+ onPersonaSelectorOpenChange={setPersonaSelectorOpen}
llmOptions={llmOptions}
activeLLMDefault={activeLLMDefault}
llmSelection={llmSelection}
@@ -642,7 +737,7 @@ function StandaloneComposerImpl({
notebookReferenceGroups={notebookReferenceGroups}
selectedPersona={selectedPersona}
selectedMemoryFiles={selectedMemoryFiles}
- selectedKnowledgeBases={selectedKnowledgeBases}
+ selectedKnowledgeBases={selectedKbOnly}
isStreaming={isStreaming}
awaitingUserReply={awaitingUserReply}
isVisualizeMode={false}
@@ -682,6 +777,7 @@ function StandaloneComposerImpl({
onCancelStreaming={onCancelStreaming}
prefillInputRef={prefillInputRef}
inputPlaceholder={inputPlaceholder}
+ inputPlaceholderCompletion={inputPlaceholderCompletion}
/>
<NotebookRecordPicker
diff --git a/web/components/courses/OrganizedSessionList.tsx b/web/components/courses/OrganizedSessionList.tsx
index 2479d9d5f..24690c868 100644
--- a/web/components/courses/OrganizedSessionList.tsx
+++ b/web/components/courses/OrganizedSessionList.tsx
@@ -17,6 +17,8 @@ import {
import { useTranslation } from "react-i18next";
import { SessionAvatar } from "@/components/sidebar/SessionAvatar";
import type { StudyCourse } from "@/lib/courses-api";
+import type { MasteryTopicLabel } from "@/lib/learning-api";
+import { masteryPathIdOf } from "@/lib/mastery-session";
import type {
SessionOrganizationPatch,
SessionSummary,
@@ -27,6 +29,8 @@ import { isPlaceholderSessionTitle } from "@/lib/session-title";
interface OrganizedSessionListProps {
sessions: SessionSummary[];
courses: StudyCourse[];
+ /** Topics whose study conversations get their own group. Omit for none. */
+ masteryTopics?: MasteryTopicLabel[];
activeSessionId: string | null;
emptyLabel?: string;
nested?: boolean;
@@ -80,6 +84,7 @@ function placeMenu(anchor: DOMRect): FloatingMenuPosition {
export default function OrganizedSessionList({
sessions,
courses,
+ masteryTopics = [],
activeSessionId,
emptyLabel,
nested = true,
@@ -120,10 +125,22 @@ export default function OrganizedSessionList({
* conversations never belong to a course and must not be pushed under a
* heading to reach them.
*/
- const { ungrouped, grouped } = useMemo(() => {
+ const { ungrouped, grouped, masteryGrouped } = useMemo(() => {
const byCourse = new Map<string, SessionSummary[]>();
+ const byTopic = new Map<string, SessionSummary[]>();
const loose: SessionSummary[] = [];
for (const session of roots) {
+ // A study conversation files under its topic first. It can also carry a
+ // course id — a path reached from a course keeps that link — but the
+ // topic is the container it was actually held in, so filing it under
+ // the course would put it where the learner never looks for it.
+ const topicId = masteryPathIdOf(session);
+ if (topicId) {
+ const bucket = byTopic.get(topicId);
+ if (bucket) bucket.push(session);
+ else byTopic.set(topicId, [session]);
+ continue;
+ }
const id = String(session.preferences?.course_id || "");
if (!id) {
loose.push(session);
@@ -142,9 +159,21 @@ export default function OrganizedSessionList({
for (const [id, rows] of byCourse) {
if (!knownIds.has(id)) loose.push(...rows);
}
- return { ungrouped: loose, grouped: known };
- }, [courses, roots]);
+ // Topics keep the index's own order, so the sidebar and the Mastery Path
+ // page list them the same way.
+ const topics = masteryTopics
+ .filter((topic) => byTopic.has(topic.path_id))
+ .map((topic) => ({ topic, rows: byTopic.get(topic.path_id) ?? [] }));
+ const knownTopicIds = new Set(masteryTopics.map((topic) => topic.path_id));
+ for (const [id, rows] of byTopic) {
+ if (!knownTopicIds.has(id)) loose.push(...rows);
+ }
+ return { ungrouped: loose, grouped: known, masteryGrouped: topics };
+ }, [courses, masteryTopics, roots]);
+ // One collapse set for both kinds of group: the ids are a course id or a
+ // path id, which never collide, and a learner collapsing a heading does not
+ // care which table it came from.
const [collapsedCourses, setCollapsedCourses] = useState<Set<string>>(
new Set(),
);
@@ -437,43 +466,66 @@ export default function OrganizedSessionList({
);
};
+ /** A collapsible heading over its conversations. Courses mark themselves
+ * with their colour dot, topics with their emoji; everything else about
+ * the two is the same and stays the same. */
+ const renderGroup = (
+ id: string,
+ mark: React.ReactNode,
+ label: string,
+ rows: SessionSummary[],
+ ) => {
+ const collapsed = collapsedCourses.has(id);
+ return (
+ <div key={id} className="mt-1.5 first:mt-0.5">
+ <button
+ type="button"
+ onClick={() => toggleCourse(id)}
+ aria-expanded={!collapsed}
+ className="flex w-full min-w-0 items-center gap-1.5 rounded-lg px-1.5 py-1 text-left text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]/75 transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
+ >
+ <ChevronRight
+ size={11}
+ className={`shrink-0 transition-transform ${collapsed ? "" : "rotate-90"}`}
+ />
+ {mark}
+ <span className="min-w-0 flex-1 truncate normal-case">{label}</span>
+ <span className="shrink-0 tabular-nums opacity-70">{rows.length}</span>
+ </button>
+ {collapsed ? null : (
+ <div className="ml-1.5 border-l border-[var(--border)]/50 pl-1">
+ {rows.map((session) => renderRow(session))}
+ </div>
+ )}
+ </div>
+ );
+ };
+
return (
<div className="py-0.5">
{ungrouped.map((session) => renderRow(session))}
- {grouped.map(({ course, rows }) => {
- const collapsed = collapsedCourses.has(course.id);
- return (
- <div key={course.id} className="mt-1.5 first:mt-0.5">
- <button
- type="button"
- onClick={() => toggleCourse(course.id)}
- aria-expanded={!collapsed}
- className="flex w-full min-w-0 items-center gap-1.5 rounded-lg px-1.5 py-1 text-left text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]/75 transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
- >
- <ChevronRight
- size={11}
- className={`shrink-0 transition-transform ${collapsed ? "" : "rotate-90"}`}
- />
- <span
- aria-hidden
- className="h-1.5 w-1.5 shrink-0 rounded-full"
- style={{ backgroundColor: course.color }}
- />
- <span className="min-w-0 flex-1 truncate normal-case">
- {course.name}
- </span>
- <span className="shrink-0 tabular-nums opacity-70">
- {rows.length}
- </span>
- </button>
- {collapsed ? null : (
- <div className="ml-1.5 border-l border-[var(--border)]/50 pl-1">
- {rows.map((session) => renderRow(session))}
- </div>
- )}
- </div>
- );
- })}
+ {masteryGrouped.map(({ topic, rows }) =>
+ renderGroup(
+ topic.path_id,
+ <span aria-hidden className="shrink-0 text-[11px] leading-none">
+ {topic.emoji || "🧭"}
+ </span>,
+ topic.name,
+ rows,
+ ),
+ )}
+ {grouped.map(({ course, rows }) =>
+ renderGroup(
+ course.id,
+ <span
+ aria-hidden
+ className="h-1.5 w-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: course.color }}
+ />,
+ course.name,
+ rows,
+ ),
+ )}
</div>
);
}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index b501f3ff8..dcfef7d8f 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -35,6 +35,8 @@ import type {
SessionOrganizationPatch,
SessionSummary,
} from "@/lib/session-api";
+import type { MasteryTopicLabel } from "@/lib/learning-api";
+import { masteryPathIdOf } from "@/lib/mastery-session";
import type { StudyCourse } from "@/lib/courses-api";
import { Tooltip } from "@/components/ui/Tooltip";
import { useCapabilityAccess } from "@/components/access/CapabilityAccessContext";
@@ -167,6 +169,8 @@ interface SidebarShellProps {
onRenameSession?: (sessionId: string, title: string) => void | Promise<void>;
onDeleteSession?: (sessionId: string) => void | Promise<void>;
courses?: StudyCourse[];
+ /** Topic labels for grouping mastery study conversations under their path. */
+ masteryTopics?: MasteryTopicLabel[];
onOrganizeSession?: (
sessionId: string,
patch: SessionOrganizationPatch,
@@ -189,6 +193,7 @@ export function SidebarShell({
onRenameSession,
onDeleteSession,
courses = [],
+ masteryTopics = [],
onOrganizeSession,
footerSlot,
}: SidebarShellProps) {
@@ -250,13 +255,19 @@ export function SidebarShell({
router.push("/home");
};
- const recentSessions = sessions
- .filter(
- (session) =>
- !session.preferences?.archived &&
- !session.preferences?.parent_session_id,
- )
- .slice(0, 8);
+ // Recents shows the last 8 loose conversations. Grouped ones are exempt from
+ // that cut: a topic heading that says "4" while listing two of them is worse
+ // than a slightly longer list, and the groups collapse anyway.
+ const visibleSessions = sessions.filter(
+ (session) =>
+ !session.preferences?.archived && !session.preferences?.parent_session_id,
+ );
+ const recentSessions = [
+ ...visibleSessions
+ .filter((session) => !masteryPathIdOf(session))
+ .slice(0, 8),
+ ...visibleSessions.filter((session) => masteryPathIdOf(session)),
+ ];
/* ---- Collapsed state ---- */
if (collapsed) {
@@ -517,6 +528,7 @@ export function SidebarShell({
<OrganizedSessionList
sessions={recentSessions}
courses={courses}
+ masteryTopics={masteryTopics}
activeSessionId={activeSessionId}
onSelect={(sessionId) => {
drawer?.close();
diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsx
index 2dbb7fed1..9f88b2f5a 100644
--- a/web/components/sidebar/UtilitySidebar.tsx
+++ b/web/components/sidebar/UtilitySidebar.tsx
@@ -17,6 +17,11 @@ import {
type SessionSummary,
} from "@/lib/session-api";
import { listCourses, type StudyCourse } from "@/lib/courses-api";
+import {
+ fetchMasteryTopicIndex,
+ type MasteryTopicLabel,
+} from "@/lib/learning-api";
+import { sessionRoute } from "@/lib/mastery-session";
export default function UtilitySidebar() {
const { t } = useTranslation();
@@ -24,6 +29,7 @@ export default function UtilitySidebar() {
const { activeSessionId, setActiveSessionId } = useAppShell();
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [courses, setCourses] = useState<StudyCourse[]>([]);
+ const [masteryTopics, setMasteryTopics] = useState<MasteryTopicLabel[]>([]);
const [loadingSessions, setLoadingSessions] = useState(false);
const hasLoadedSessionsRef = useRef(false);
@@ -32,12 +38,17 @@ export default function UtilitySidebar() {
setLoadingSessions(true);
}
try {
- const [nextSessions, nextCourses] = await Promise.all([
+ // Topic labels only name a group heading, so a failure to load them must
+ // not cost the session list: the conversations then read as ungrouped
+ // rather than as missing.
+ const [nextSessions, nextCourses, nextTopics] = await Promise.all([
listSessions(50, 0, { force: true }),
listCourses({ force: true }),
+ fetchMasteryTopicIndex().catch(() => [] as MasteryTopicLabel[]),
]);
setSessions(nextSessions);
setCourses(nextCourses);
+ setMasteryTopics(nextTopics);
hasLoadedSessionsRef.current = true;
} catch (error) {
console.error("Failed to load sessions", error);
@@ -50,12 +61,14 @@ export default function UtilitySidebar() {
void refreshSessions();
}, [refreshSessions]);
+ // A study conversation opens on its own path — see ``sessionRoute``.
const handleSelectSession = useCallback(
async (sessionId: string) => {
setActiveSessionId(sessionId);
- router.push(`/home/${sessionId}`);
+ const session = sessions.find((item) => item.session_id === sessionId);
+ router.push(session ? sessionRoute(session) : `/home/${sessionId}`);
},
- [router, setActiveSessionId],
+ [router, sessions, setActiveSessionId],
);
const handleRenameSession = useCallback(
@@ -113,6 +126,7 @@ export default function UtilitySidebar() {
showSessions
sessions={sessions}
courses={courses}
+ masteryTopics={masteryTopics}
activeSessionId={activeSessionId}
loadingSessions={loadingSessions}
onNewChat={() => setActiveSessionId(null)}
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index 94ac2d269..8b0ca8e90 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -17,6 +17,11 @@ import {
type SessionSummary,
} from "@/lib/session-api";
import { listCourses, type StudyCourse } from "@/lib/courses-api";
+import {
+ fetchMasteryTopicIndex,
+ type MasteryTopicLabel,
+} from "@/lib/learning-api";
+import { sessionRoute } from "@/lib/mastery-session";
export default function WorkspaceSidebar() {
const { t } = useTranslation();
@@ -30,6 +35,7 @@ export default function WorkspaceSidebar() {
} = useUnifiedChat();
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [courses, setCourses] = useState<StudyCourse[]>([]);
+ const [masteryTopics, setMasteryTopics] = useState<MasteryTopicLabel[]>([]);
const [loadingSessions, setLoadingSessions] = useState(false);
const hasLoadedSessionsRef = useRef(false);
@@ -38,12 +44,17 @@ export default function WorkspaceSidebar() {
setLoadingSessions(true);
}
try {
- const [nextSessions, nextCourses] = await Promise.all([
+ // Topic labels only name a group heading, so a failure to load them must
+ // not cost the session list: the conversations then read as ungrouped
+ // rather than as missing.
+ const [nextSessions, nextCourses, nextTopics] = await Promise.all([
listSessions(50, 0, { force: true }),
listCourses({ force: true }),
+ fetchMasteryTopicIndex().catch(() => [] as MasteryTopicLabel[]),
]);
setSessions(nextSessions);
setCourses(nextCourses);
+ setMasteryTopics(nextTopics);
hasLoadedSessionsRef.current = true;
} catch (error) {
console.error("Failed to load sessions", error);
@@ -91,11 +102,15 @@ export default function WorkspaceSidebar() {
router.push("/home");
}, [cancelStreamingTurn, newSession, router]);
+ // A study conversation opens on its own path, not in the main chat: the
+ // outline, the waypoint header and the tutor's own composer are the context
+ // it was held in, and /home would drop all three.
const handleSelectSession = useCallback(
async (sessionId: string) => {
- router.push(`/home/${sessionId}`);
+ const session = sessions.find((item) => item.session_id === sessionId);
+ router.push(session ? sessionRoute(session) : `/home/${sessionId}`);
},
- [router],
+ [router, sessions],
);
const handleRenameSession = useCallback(
@@ -155,6 +170,7 @@ export default function WorkspaceSidebar() {
showSessions
sessions={orderedSessions}
courses={courses}
+ masteryTopics={masteryTopics}
activeSessionId={selectedSessionId}
loadingSessions={loadingSessions}
onNewChat={handleNewChat}
diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsx
index a8afef659..cdd64be6b 100644
--- a/web/components/space/learning/MasteryComposer.tsx
+++ b/web/components/space/learning/MasteryComposer.tsx
@@ -22,17 +22,26 @@ import { hasPendingAskUser } from "@/lib/ask-user-state";
export function MasteryComposer({
placeholder,
+ askHint,
disabled,
prefillInputRef,
}: {
placeholder: string;
+ /** A question the tutor suggests asking here; Tab takes it. "" for none. */
+ askHint?: string;
/** The session is still opening — nothing can be sent yet. */
disabled?: boolean;
/** Lets the screen drop a handed-off opening line into the textarea. */
prefillInputRef?: React.MutableRefObject<((text: string) => void) | null>;
}) {
- const { state, sendMessage, cancelStreamingTurn, setKBs, setLLMSelection } =
- useUnifiedChat();
+ const {
+ state,
+ sendMessage,
+ cancelStreamingTurn,
+ setKBs,
+ setLLMSelection,
+ setPersonaSelection,
+ } = useUnifiedChat();
const handleSubmit = useCallback(
(submission: StandaloneComposerSubmission) => {
@@ -40,7 +49,11 @@ export function MasteryComposer({
sendMessage(
submission.content,
submission.attachments,
- undefined,
+ // How many times the tutor may consult the selected agent this turn.
+ // Absent when no agent is picked, which is the ordinary case.
+ submission.subagentBudget
+ ? { subagent_consult_budget: submission.subagentBudget }
+ : undefined,
submission.notebookReferences,
submission.historyReferences,
{ bookReferences: submission.bookReferences },
@@ -70,9 +83,15 @@ export function MasteryComposer({
onKnowledgeBasesChange={setKBs}
llmSelection={state.llmSelection}
onLLMSelectionChange={setLLMSelection}
+ personaSelection={state.personaSelection}
+ onPersonaSelectionChange={setPersonaSelection}
onSubmit={handleSubmit}
onCancelStreaming={cancelStreamingTurn}
- inputPlaceholder={placeholder}
+ // The suggested question *is* the placeholder once there is one: naming
+ // the waypoint a third time says nothing the header has not, whereas the
+ // question shows the learner a way in.
+ inputPlaceholder={askHint || placeholder}
+ inputPlaceholderCompletion={askHint}
prefillInputRef={prefillInputRef}
/>
);
diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsx
index b35dbc239..536e513ff 100644
--- a/web/components/space/learning/MasteryStudy.tsx
+++ b/web/components/space/learning/MasteryStudy.tsx
@@ -16,7 +16,7 @@ import { useTranslation } from "react-i18next";
import { ChatMessageList } from "@/components/chat/home/ChatMessages";
import { useUnifiedChat } from "@/context/UnifiedChatContext";
import { useMasteryStudySession } from "@/hooks/useMasteryStudySession";
-import type { MasteryTopic } from "@/lib/learning-api";
+import { fetchMasteryAskHint, type MasteryTopic } from "@/lib/learning-api";
import { consumePendingPrompt } from "@/lib/pending-prompt";
import { topicDisplayName, type Translate } from "./format";
@@ -127,6 +127,34 @@ export function MasteryStudy({
});
}, [state.isStreaming, state.messages]);
+ // A question worth asking here, written by the task model. Fetched when the
+ // turn settles rather than as it streams: what is worth asking next depends
+ // on what the tutor just finished saying. The composer is fully usable
+ // meanwhile — this only ever replaces a placeholder, so a slow or failed
+ // call costs nothing but the offer.
+ const [askHint, setAskHint] = useState("");
+ useEffect(() => {
+ if (state.isStreaming || sessionLoading || sessionError) return;
+ let cancelled = false;
+ void fetchMasteryAskHint(pathId, state.sessionId ?? "")
+ .then((hint) => {
+ if (!cancelled) setAskHint(hint);
+ })
+ .catch(() => {
+ // Keep whatever is showing; the static placeholder is a fine floor.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ pathId,
+ sessionError,
+ sessionLoading,
+ state.isStreaming,
+ state.messages.length,
+ state.sessionId,
+ ]);
+
// A point crossing into "mastered" is the one real payoff this screen
// offers, and the backend does not emit a "just mastered" event to key
// off — every mastery write lands as the same generic revision bump.
@@ -330,21 +358,23 @@ export function MasteryStudy({
</div>
</div>
) : (
- <ChatMessageList
- messages={state.messages}
- isStreaming={state.isStreaming}
- sessionId={state.sessionId}
- language={state.language}
- onCopyAssistantMessage={copyAssistantMessage}
- onRegenerateMessage={regenerateLastMessage}
- onDeleteTurn={deleteTurn}
- selectedBranches={state.selectedBranches}
- onEditMessage={editMessage}
- onSwitchBranch={switchBranch}
- onSubmitUserReply={submitUserReply}
- availableKbNames={new Set(knowledgeBases)}
- showModeBadge={false}
- />
+ <div className="space-y-9">
+ <ChatMessageList
+ messages={state.messages}
+ isStreaming={state.isStreaming}
+ sessionId={state.sessionId}
+ language={state.language}
+ onCopyAssistantMessage={copyAssistantMessage}
+ onRegenerateMessage={regenerateLastMessage}
+ onDeleteTurn={deleteTurn}
+ selectedBranches={state.selectedBranches}
+ onEditMessage={editMessage}
+ onSwitchBranch={switchBranch}
+ onSubmitUserReply={submitUserReply}
+ availableKbNames={new Set(knowledgeBases)}
+ showModeBadge={false}
+ />
+ </div>
)}
<div ref={messagesEndRef} className="h-px" />
</div>
@@ -356,6 +386,7 @@ export function MasteryStudy({
placeholder={t("Ask your tutor about “{{waypoint}}”…", {
waypoint: waypoint.name,
})}
+ askHint={askHint}
disabled={sessionLoading}
prefillInputRef={prefillInputRef}
/>
diff --git a/web/components/space/learning/ProgressRing.tsx b/web/components/space/learning/ProgressRing.tsx
index c1eb7f9e3..3da3a2671 100644
--- a/web/components/space/learning/ProgressRing.tsx
+++ b/web/components/space/learning/ProgressRing.tsx
@@ -5,11 +5,29 @@
* whatever the model happened to pick, rendered at whatever the OS font
* decided — it carried no information and read as clip art. The ring is the
* one number the card is actually about, and it inherits the theme.
+ *
+ * Three things it deliberately is not:
+ *
+ * A *bare integer* in a circle. "7" with no unit is an id, a step number, an
+ * avatar badge — anything but a measurement. The figure carries a small `%`
+ * so it reads as the quantity it is, and the two are set at different sizes
+ * so the number stays the thing you see.
+ *
+ * *Action-coloured*. `--primary` is what buttons and links are, and the card
+ * this sits on is itself one big link. An arc in that blue competes with the
+ * title for the eye and quietly suggests it can be clicked. So the arc is
+ * ink — the page's own foreground — and `--primary` is kept for the single
+ * moment it means something: the path is finished.
+ *
+ * *Heavy*. The stroke is a hairline, and the unfilled track is dimmer than
+ * the border it is drawn from. A ring is a footnote to the title next to it;
+ * at 2.5px it read as the loudest thing on the card, and at low percentages
+ * a thick round cap turns a real value into what looks like a stuck spinner.
*/
export function ProgressRing({
value,
- size = 36,
- stroke = 2.5,
+ size = 32,
+ stroke = 1.75,
showLabel = true,
}: {
/** Completion in 0..1. */
@@ -22,6 +40,7 @@ export function ProgressRing({
const radius = (size - stroke) / 2;
const circumference = 2 * Math.PI * radius;
const percent = Math.round(safe * 100);
+ const complete = safe >= 1;
return (
<span
@@ -36,6 +55,7 @@ export function ProgressRing({
fill="none"
stroke="var(--border)"
strokeWidth={stroke}
+ opacity={0.45}
/>
{safe > 0 && (
<circle
@@ -43,18 +63,24 @@ export function ProgressRing({
cy={size / 2}
r={radius}
fill="none"
- stroke="var(--primary)"
+ stroke={complete ? "var(--primary)" : "var(--foreground)"}
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={circumference}
strokeDashoffset={circumference * (1 - safe)}
+ opacity={complete ? 1 : 0.7}
className="transition-[stroke-dashoffset] duration-500"
/>
)}
</svg>
{showLabel && (
- <span className="absolute text-[10px] font-medium tabular-nums text-[var(--muted-foreground)]">
- {percent}
+ <span className="absolute flex items-baseline text-[var(--muted-foreground)]">
+ <span className="text-[11px] font-medium leading-none tabular-nums">
+ {percent}
+ </span>
+ <span className="text-[7px] font-medium leading-none opacity-70">
+ %
+ </span>
</span>
)}
</span>
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 226850e7c..f160a3d7d 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -452,6 +452,48 @@ export async function fetchMasteryTopics(
return result.topics;
}
+/** Just enough to name a topic. See ``fetchMasteryTopicIndex``. */
+export interface MasteryTopicLabel {
+ path_id: string;
+ name: string;
+ emoji: string;
+}
+
+/**
+ * The id → name map, without each topic's knowledge map and source excerpts.
+ *
+ * The sidebar groups study conversations under their topic and reloads on
+ * every stream end, so it wants the labels and nothing else; `fetchMasteryTopics`
+ * would ship kilobytes per topic to render a header.
+ */
+export async function fetchMasteryTopicIndex(
+ init?: RequestInit,
+): Promise<MasteryTopicLabel[]> {
+ const result = await masteryJson<{ topics: MasteryTopicLabel[] }>(
+ "/api/v1/learning/topics/index",
+ init,
+ "load topic index",
+ );
+ return Array.isArray(result.topics) ? result.topics : [];
+}
+
+/** One question the learner could ask here — "" when there is none to offer. */
+export async function fetchMasteryAskHint(
+ pathId: string,
+ sessionId: string,
+ init?: RequestInit,
+): Promise<string> {
+ const query = sessionId
+ ? `?session_id=${encodeURIComponent(sessionId)}`
+ : "";
+ const result = await masteryJson<{ hint?: string }>(
+ `/api/v1/learning/topics/${encodeURIComponent(pathId)}/ask-hint${query}`,
+ init,
+ "load ask hint",
+ );
+ return typeof result.hint === "string" ? result.hint : "";
+}
+
export function fetchMasteryTopic(
pathId: string,
init?: RequestInit,
diff --git a/web/lib/mastery-session.ts b/web/lib/mastery-session.ts
new file mode 100644
index 000000000..4bc898214
--- /dev/null
+++ b/web/lib/mastery-session.ts
@@ -0,0 +1,34 @@
+/**
+ * Which mastery path a conversation belongs to — the one place that decides.
+ *
+ * A mastery study conversation is an ordinary chat session that happens to
+ * carry `mastery_path_id` in its preferences. Two surfaces need to read that:
+ * the sidebar, to file the conversation under its topic, and the click
+ * handler, to open it on `/mastery/<path>/study/<session>` instead of `/home`.
+ * If those two ever disagreed, a conversation would render under a topic and
+ * then navigate somewhere else — so the rule lives here and neither owns it.
+ *
+ * Both signals are required. `capability` says the last turn actually ran the
+ * mastery tutor, and `mastery_path_id` says which path it ran against; a
+ * session that switched capability mid-conversation keeps the stale id, and a
+ * course-study conversation about a path carries neither.
+ */
+
+import type { SessionSummary } from "@/lib/session-api";
+
+export function masteryPathIdOf(session: SessionSummary): string {
+ const preferences = session.preferences;
+ if (!preferences) return "";
+ if (preferences.capability !== "mastery_path") return "";
+ return String(preferences.mastery_path_id || "");
+}
+
+/** Where clicking this conversation should land. */
+export function sessionRoute(session: SessionSummary): string {
+ const pathId = masteryPathIdOf(session);
+ const sessionId = encodeURIComponent(session.session_id);
+ if (pathId) {
+ return `/mastery/${encodeURIComponent(pathId)}/study/${sessionId}`;
+ }
+ return `/home/${sessionId}`;
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 8110fdb87..ab34b2620 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3757,6 +3757,7 @@
"Currently unavailable": "Currently unavailable",
"Module {{n}}": "Module {{n}}",
"Ask your tutor about “{{waypoint}}”…": "Ask your tutor about “{{waypoint}}”…",
+ "Tab to ask this": "Tab to ask this",
"Mastered “{{name}}”": "Mastered “{{name}}”",
"Due {{relative}} · {{absolute}}": "Due {{relative}} · {{absolute}}",
"interval {{interval}} · {{streak}} in a row": "interval {{interval}} · {{streak}} in a row",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 2b2bd15c4..4fcbe141c 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3757,6 +3757,7 @@
"Currently unavailable": "当前不可用",
"Module {{n}}": "模块 {{n}}",
"Ask your tutor about “{{waypoint}}”…": "问导师关于「{{waypoint}}」的问题…",
+ "Tab to ask this": "按 Tab 直接问这句",
"Mastered “{{name}}”": "已掌握「{{name}}」",
"Due {{relative}} · {{absolute}}": "{{relative}}复习 · {{absolute}}",
"interval {{interval}} · {{streak}} in a row": "第 {{interval}} 档 · 连对 {{streak}}",