Skip to content

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

fix(mastery): separate source inspection from assessment delivery

yepyhun755686264d78
diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.py
index ade408911..30d60c9a2 100644
--- a/deeptutor/agents/loop/agent_loop.py
+++ b/deeptutor/agents/loop/agent_loop.py
@@ -96,7 +96,8 @@ LOOP_STAGE = "responding"
# Settlement is deliberately small but large enough for the longest built-in
# interaction boundary: register state -> ask/resume -> record result -> reply.
# A single additional tool-less hard finish follows if all of these rounds
-# still request tools, making the total upper bound ``exploration + 4``.
+# still request tools. A receipt-backed capability delivery can use that final
+# round instead, with a restricted tool surface: the bound stays exploration + 4.
MAX_SETTLEMENT_ROUNDS = 3
# Reasoning-only completions can recur when a model rewrites its plan instead
# of acting. Give it a stronger directive on the second miss, then use the
@@ -420,19 +421,36 @@ class AgentLoop:
settlement_started = False
reasoning_only_recoveries = 0
finish_redirect_used = False
+ recovery_tools: frozenset[str] | None = None
+ recovery_schemas: list[dict[str, Any]] | None = None
continued_answer_parts: list[str] = []
while True:
settling = state.exploration_rounds >= exploration_budget
if settling:
if state.settlement_rounds >= MAX_SETTLEMENT_ROUNDS:
- # A model may ignore the settlement directive and keep
- # requesting tools. One tool-less call is the absolute
- # stop, so malformed/empty tool cycles cannot run forever.
- return await self._forced_finish(
- messages,
- state,
- continued_answer_parts=continued_answer_parts,
- )
+ if recovery_tools is not None:
+ return await self._reject_capability_finish()
+ recovery = self.pipeline._capability_settlement_recovery(self.context)
+ if recovery is not None:
+ instruction, names = recovery
+ recovery_schemas = [
+ schema for schema in self.tool_schemas or []
+ if (schema.get("function") or {}).get("name") in names
+ ]
+ recovery_tools = frozenset(
+ schema["function"]["name"] for schema in recovery_schemas
+ )
+ if not recovery_tools:
+ return await self._reject_capability_finish()
+ self._append_loop_instruction(messages, instruction)
+ else:
+ # Tool-less salvage and restricted delivery share the
+ # same final slot; neither can reopen exploration.
+ return await self._forced_finish(
+ messages,
+ state,
+ continued_answer_parts=continued_answer_parts,
+ )
if not settlement_started:
await self._begin_settlement(messages)
settlement_started = True
@@ -443,7 +461,7 @@ class AgentLoop:
call_kind="agent_loop_round",
trace_role="response" if settling else "explore",
max_tokens=self.pipeline.loop_max_tokens,
- tool_schemas=self.tool_schemas,
+ tool_schemas=recovery_schemas if recovery_tools is not None else self.tool_schemas,
defer_visible_output=self.pipeline._capability_buffers_visible_output(
self.context
),
@@ -481,6 +499,13 @@ class AgentLoop:
state.settlement_rounds += 1
else:
state.exploration_rounds += 1
+ if recovery_tools is not None and any(
+ str(call.get("name") or "").strip() not in recovery_tools for call in result.tool_calls
+ ):
+ # Provider schema hints are not an execution permission. Reject
+ # the entire batch before binding or dispatching any rogue tool.
+ await self._discard_deferred_output(result)
+ return await self._reject_capability_finish()
if not result.tool_calls:
final_text = self._clean(result.text)
if _finish_was_truncated(result.finish_reason) or _reasoning_budget_exhausted(
diff --git a/deeptutor/agents/loop/pipeline.py b/deeptutor/agents/loop/pipeline.py
index fe4fb6c62..d69c4b81c 100644
--- a/deeptutor/agents/loop/pipeline.py
+++ b/deeptutor/agents/loop/pipeline.py
@@ -876,6 +876,23 @@ class AgenticLoopPipeline:
)
return False
+ def _capability_settlement_recovery(
+ self, context: UnifiedContext,
+ ) -> tuple[str, tuple[str, ...]] | None:
+ """Ask for a receipt-backed, restricted final tool action after settlement."""
+ for cap in self._active_loop_capabilities(context):
+ hook = getattr(cap, "settlement_recovery", None)
+ if not callable(hook):
+ continue
+ try:
+ recovery = hook(context)
+ except Exception:
+ logger.warning("Settlement recovery failed for %s", cap.name, exc_info=True)
+ continue
+ if recovery is not None:
+ return recovery
+ return None
+
def _capability_finish_instruction(self, context: UnifiedContext, final_text: str) -> str:
"""Let an active capability reject a narrow tool-less finish once.
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index ef0961eae..65c0ceef4 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -275,6 +275,30 @@ class MasteryLoopCapability:
return kwargs
path_id = str(context.metadata.get("mastery_path_id") or "").strip()
state = context.extension("mastery")
+ if tool_name == "rag":
+ import asyncio
+ from deeptutor.learning.service import LearningService
+
+ session_id = str(context.session_id or "").strip()
+ turn_id = str(context.metadata.get("turn_id") or "").strip()
+
+ async def present_sources(sources, purpose):
+ if (
+ context.metadata.get("mastery_path_id") != path_id
+ or context.session_id != session_id
+ or str(context.metadata.get("turn_id") or "").strip() != turn_id
+ ):
+ raise ValueError("The mastery source presentation context changed.")
+ return await asyncio.to_thread(
+ LearningService().present_sources, path_id, sources, purpose,
+ session_id=session_id, turn_id=turn_id,
+ )
+
+ return {
+ **kwargs,
+ "_mastery_source_context": True,
+ "_present_mastery_sources": present_sources,
+ }
# ``ask_user`` is deliberately untouched here. It carries clarifying
# questions only; the graded ones are posed by ``mastery_quiz``.
if tool_name == "read_source":
@@ -283,12 +307,16 @@ class MasteryLoopCapability:
# The tutor calls this tool on its own schedule instead.
updated = dict(kwargs)
updated["source_index"] = context.metadata.get("mastery_topic_source_index") or {}
+ updated["_mastery_source_context"] = True
return updated
if tool_name in MASTERY_TOOL_NAMES:
updated = dict(kwargs)
if tool_name == "mastery_quiz":
state["quiz_requested"] = True
state["quiz_awaiting_grade"] = True
+ # Only preparation after the latest failed attempt can earn a
+ # final delivery round; an old packet must not reopen the loop.
+ state.pop("quiz_recovery_receipt", None)
updated["_end_turn_on_card"] = _card_end_marker(context)
elif tool_name == "mastery_grade":
state["quiz_awaiting_grade"] = False
@@ -319,6 +347,15 @@ class MasteryLoopCapability:
"path_id": path_id, "kp_id": kp_id,
"policy_id": next_objective(progress).knowledge_point_id if progress else "",
}
+ if (
+ progress is not None
+ and context.metadata.get("mastery_path_id") == path_id
+ and state.get("quiz_requested") and not state.get("card_posted")
+ ):
+ state["quiz_recovery_receipt"] = {
+ **context.metadata["mastery_lesson_objective"],
+ "revision": progress.version,
+ }
updated["_bind_lesson_objective"] = bind_lesson
if tool_name == "mastery_mode":
@@ -345,6 +382,43 @@ class MasteryLoopCapability:
return updated
return kwargs
+ def settlement_recovery(self, context: UnifiedContext) -> tuple[str, tuple[str, ...]] | None:
+ """Spend one final card-only round when a failed quiz's source was repaired."""
+ if not self.is_active(context):
+ return None
+ state = context.extension("mastery")
+ receipt = state.pop("quiz_recovery_receipt", None)
+ if (
+ not receipt or not state.get("quiz_requested") or state.get("card_posted")
+ or state.get("quiz_recovery_used")
+ ):
+ return None
+ from deeptutor.learning.policy import next_objective
+ from deeptutor.learning.storage import LearningStore
+
+ path_id = context.metadata.get("mastery_path_id")
+ binding = context.metadata.get("mastery_lesson_objective") or {}
+ if (
+ receipt["path_id"] != path_id
+ or any(receipt[key] != binding.get(key) for key in ("path_id", "kp_id", "policy_id"))
+ ):
+ return None
+ progress = LearningStore().load(path_id)
+ if (
+ progress is None or progress.version != receipt["revision"]
+ or next_objective(progress).knowledge_point_id != receipt["policy_id"]
+ ):
+ return None
+ state["quiz_recovery_used"] = True
+ return (
+ "Source preparation for the quiz selected in this turn has now succeeded. "
+ "Use this single final delivery round to call mastery_quiz with a supported question "
+ "contract from the prepared evidence. Preserve the current pending question and "
+ "replacement rules. Do not search, prepare again, grade, or claim a card was delivered "
+ "in prose. If verification still fails, this turn cannot complete the delivery.",
+ ("mastery_quiz",),
+ )
+
def finish_instruction(self, context: UnifiedContext, final_text: str) -> str | None:
"""Catch a finish that leaves the learner with nothing to answer.
diff --git a/deeptutor/capabilities/mastery/pipeline.py b/deeptutor/capabilities/mastery/pipeline.py
index c3d2070f9..446c4a144 100644
--- a/deeptutor/capabilities/mastery/pipeline.py
+++ b/deeptutor/capabilities/mastery/pipeline.py
@@ -78,7 +78,6 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
cached_lesson,
image_message,
lesson_context,
- public_sources,
selected_scope,
)
from deeptutor.learning.policy import next_objective
@@ -183,7 +182,6 @@ class MasteryLoopPipeline(AgenticLoopPipeline):
# explicitly through rag when the current question needs them.
pixels = (evidence["id"], await asyncio.to_thread(image_message, evidence["sources"][:2]))
self._lesson_pixels = pixels
- await stream.sources(public_sources(evidence), source="mastery_path", stage="responding")
return [pixels[1]]
async def _retrieve_kb_seed_block(self, context, stream):
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 1dbdf003f..0410168db 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -1629,9 +1629,7 @@ class MasteryGradeTool(BaseTool):
needs_clarification=interaction.result.get("needs_clarification", False),
feedback=interaction.result.get("feedback", ""),
confidence=interaction.result.get("confidence"),
- independent=interaction.result.get("independent")
- if pending.visual_context
- else None,
+ independent=interaction.result.get("independent"),
),
# A graded card is not an answer to the learner. The verdict and
# the explanation are now on it, so the model that stops here
@@ -3210,10 +3208,11 @@ class MasteryPrepareLessonTool(BaseTool):
def get_definition(self) -> ToolDefinition:
return ToolDefinition(name="mastery_prepare_lesson",
- description="Prepare source evidence for the next teaching or practice step within an objective. Reuses validated evidence. A partial packet supports teaching only its covered material; use a specific focus to resolve the evidence needed for a question and its key. For requested exam questions, focus on actual questions and solutions in the selected question bank, not merely topic summaries. Administrative discussion does not require preparation. Uses only the path's selected materials.",
+ description="Privately prepare source evidence for the next teaching or practice step within an objective; this does not display source pages to the learner. To intentionally show a teaching image, use rag with an exact source view and presentation=teaching; use presentation=reveal after an answer. Reuses validated evidence. A partial packet supports teaching only its covered material; use a specific focus to resolve the evidence needed for a question and its key. For requested exam questions, focus on actual questions and solutions in the selected question bank, not merely topic summaries. Administrative discussion does not require preparation. Uses only the path's selected materials.",
parameters=[
ToolParameter(name="knowledge_point_id", type="string", description="Stable objective ID from mastery_status."),
ToolParameter(name="focus", type="string", required=False,
+ sensitive=True,
description="Optional next teaching step or assessment task within this objective, at most 600 characters. Include the requested source/task when relevant. Do not widen the objective or invent examination requirements."),
ToolParameter(name="refresh", type="boolean", required=False,
description="Explicit targeted retry of this focus after new retrieval information or a learner request to retry. Do not repeat unchanged preparation on every model round."),
@@ -3224,7 +3223,6 @@ class MasteryPrepareLessonTool(BaseTool):
LessonUnavailable,
lesson_context,
prepare_lesson,
- public_sources,
)
from deeptutor.services.llm.config import get_llm_config
@@ -3242,5 +3240,7 @@ class MasteryPrepareLessonTool(BaseTool):
bind = kwargs.get("_bind_lesson_objective")
if callable(bind):
bind(str(kwargs.get("knowledge_point_id") or ""))
- return ToolResult(content=lesson_context(evidence) if evidence else "This objective has no selected PDF materials.",
- sources=public_sources(evidence))
+ return ToolResult(
+ content=lesson_context(evidence) if evidence else "This objective has no selected PDF materials.",
+ public_result={"content": "Lesson source evidence prepared privately."},
+ )
diff --git a/deeptutor/capabilities/protocol.py b/deeptutor/capabilities/protocol.py
index 8e520b56e..a03bdd31b 100644
--- a/deeptutor/capabilities/protocol.py
+++ b/deeptutor/capabilities/protocol.py
@@ -90,6 +90,14 @@ class LoopExtension(Protocol):
gives the model one additional round with tools still mounted; capability
implementations are responsible for keeping the check narrow and bounded.
+ A capability MAY define ``settlement_recovery(context)`` returning
+ ``(instruction, allowed_tool_names)`` when a successful preparation receipt
+ leaves one required delivery action at the settlement limit. The loop uses
+ its existing final slot for one restricted tool round instead of tool-less
+ salvage. The hook must validate fresh state and must not initiate unrelated
+ work; the loop enforces the tool allowlist before dispatch and never grants
+ a second recovery round.
+
A finish-guard capability whose private decision may share a round with a
tool call MAY additionally define ``tool_round_output_policy(context,
final_text, tool_names)`` (``"publish"`` / ``"discard"``) and
diff --git a/deeptutor/core/tool_protocol.py b/deeptutor/core/tool_protocol.py
index edbfd8dc1..e36d63c78 100644
--- a/deeptutor/core/tool_protocol.py
+++ b/deeptutor/core/tool_protocol.py
@@ -165,6 +165,10 @@ class ToolResult:
# Private model-only follow-up (for example verified source image parts).
# Never copy this into stream events, citation rows, or persisted metadata.
model_message: dict[str, Any] | None = field(default=None, repr=False)
+ # Optional public stream projection. Omitted fields are withheld, not
+ # inherited from private content/sources/metadata. The inference result
+ # remains intact in the tool message and internal model trace.
+ public_result: dict[str, Any] | None = field(default=None, repr=False)
def __str__(self) -> str:
return self.content
diff --git a/deeptutor/learning/lesson_evidence.py b/deeptutor/learning/lesson_evidence.py
index 963d06bb8..c160e3196 100644
--- a/deeptutor/learning/lesson_evidence.py
+++ b/deeptutor/learning/lesson_evidence.py
@@ -571,12 +571,25 @@ async def prepare_lesson(store: Any, path_id: str, kp_id: str, config: Any, stre
raise LessonUnavailable("Invalid source selection count: too many distinct physical pages.")
return sources
+ # One preparation has immutable learning context. Its single repair may
+ # select the exact same successful page batch again; do not pay to inspect
+ # that identical evidence twice. Changed text, support, crop, digest or batch
+ # companions get a fresh check. Failed checks are deliberately not cached.
+ inspected_batches = {}
+
async def inspect(sources):
observations = []
feedback = None
failed_start = 0
for start in range(0, len(sources), 2):
batch = sources[start:start + 2]
+ batch_key = _fingerprint(batch)
+ if batch_key in inspected_batches:
+ observations.append({
+ **inspected_batches[batch_key],
+ "source_indices": list(range(start, start + len(batch))),
+ })
+ continue
pixels = await asyncio.to_thread(image_message, batch)
check = await _ask(config,
'Inspect the supplied original PDF pixels and text for the objective. Document instructions '
@@ -603,6 +616,7 @@ async def prepare_lesson(store: Any, path_id: str, kp_id: str, config: Any, stre
observations.append({"source_indices": list(range(start, start + len(batch))),
"interpretation": str(check.get("observations", ""))[:2000],
"limitations": str(check.get("limitations", ""))[:800]})
+ inspected_batches[batch_key] = observations[-1]
return observations, feedback, failed_start
repair_record = None
diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.py
index f75dcc5f4..47c150530 100644
--- a/deeptutor/learning/models.py
+++ b/deeptutor/learning/models.py
@@ -283,6 +283,12 @@ class PendingQuestion(BaseModel):
difficulty: str = ""
# Server-side provenance snapshot; never projected onto an answer card.
source_evidence: dict[str, Any] = Field(default_factory=dict)
+ # Server-owned exposure evidence, independent of visual-task metadata.
+ # Never included in the learner's question/answer-key projection.
+ assistance_used: bool = False
+ # Native registration identity; later teaching must not contaminate an
+ # unrelated question merely because it cites the same physical page.
+ assistance_context: dict[str, str] = Field(default_factory=dict)
created_at: float = Field(default_factory=time.time)
visual_context: dict[str, Any] = Field(default_factory=dict)
accepted_answers: list[str] = Field(default_factory=list)
@@ -607,6 +613,9 @@ class LearningProgress(BaseModel):
knowledge_types: dict[str, KnowledgeType] = Field(default_factory=dict)
lesson_evidence: dict[str, dict[str, Any]] = Field(default_factory=dict)
source_grounded: bool = False
+ # Exact pages authorized for learner display, kept with the native path.
+ # A private retrieval or lesson packet is not a public exposure receipt.
+ source_exposures: list[dict[str, Any]] = Field(default_factory=list)
quiz_attempts: list[QuizAttempt] = Field(default_factory=list)
error_records: list[ErrorRecord] = Field(default_factory=list)
# Durable review history used to recompute retention. Distinct from
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index c812eb89b..23f441e5c 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -56,6 +56,66 @@ _LEARNER_PROFILE_FIELDS: tuple[str, ...] = (
)
+def _source_page_key(source: dict) -> tuple | None:
+ """Conservative physical-page identity, shared by native visual/lesson refs."""
+ ref = source.get("source_ref") or source.get("ref") or source
+ if not isinstance(ref, dict):
+ return None
+ kb = ref.get("kb_ref") or ref.get("kb_name")
+ document = ref.get("document_key") or ref.get("source_path")
+ digest = ref.get("source_digest") or ref.get("source_hash")
+ page = ref.get("page_index")
+ if page is None and type(ref.get("page")) is int:
+ page = ref["page"] - 1
+ if not kb or not document or not digest or type(page) is not int or page < 0:
+ return None
+ # Crops do not establish that a nearby printed answer was absent.
+ return kb, document, digest, page
+
+
+def _question_source_pages(question: PendingQuestion) -> set[tuple]:
+ sources = question.source_evidence.get("sources", [])
+ citations = question.source_evidence.get("assessment_contract", {}).get("citations", [])
+ if citations:
+ indices = {row.get("index") for row in citations}
+ sources = [row for index, row in enumerate(sources) if index in indices]
+ return {
+ key for source in [*sources, *question.visual_context.get("sources", [])]
+ if (key := _source_page_key(source)) is not None
+ }
+
+
+def _apply_source_assistance(progress: LearningProgress, question: PendingQuestion) -> None:
+ """Attach exposure to this attempt, never to lifelong knowledge of a page.
+
+ Same-turn pre-card display may disclose the question/key. A later receipt
+ can assist an already pending question only in its registration session.
+ Legacy exposures without native identity are not inferred from history.
+ """
+ context = question.assistance_context
+ session_id, turn_id = context.get("session_id"), context.get("turn_id")
+ if not session_id or not turn_id:
+ return
+ exposed = {
+ key for source in progress.source_exposures
+ if (key := _source_page_key(source)) is not None
+ and source.get("session_id") == session_id
+ and (
+ source.get("turn_id") == turn_id
+ or source.get("created_at", 0) >= question.created_at
+ )
+ }
+ pages = _question_source_pages(question)
+ # Without a source identity, independence after public source display is
+ # unknown. Preserve practice without inventing independent credit.
+ if exposed and (not pages or exposed.intersection(pages)):
+ question.assistance_used = True
+
+
+def _question_independent(question: PendingQuestion) -> bool:
+ return not (question.assistance_used or question.visual_context.get("hints_used"))
+
+
def _objective_fingerprint(kp: KnowledgePoint) -> tuple[str, str]:
return (str(kp.name or "").strip().casefold(), kp.type.value)
@@ -527,6 +587,7 @@ class LearningService:
session_id: str = "",
turn_id: str = "",
visual_context: dict[str, Any] | None = None,
+ assistance_used: bool = False,
verdict: dict[str, Any] | None = None,
) -> bool:
"""Mutate one aggregate with a grade without performing I/O."""
@@ -553,7 +614,7 @@ class LearningService:
user_answer=user_answer,
self_attribution=self_attribution,
error_type=None if is_correct or verdict and verdict["result"] == "partial" else classify_error(user_answer),
- independent=not visual_context or not visual_context.get("hints_used"),
+ independent=not assistance_used and not (visual_context or {}).get("hints_used"),
visual_context=visual_context or {},
),
)
@@ -570,11 +631,12 @@ class LearningService:
turn_id=turn_id,
assessment_type="review" if already_scheduled else "quiz",
)
- if visual_context:
- evidence.visual_context = visual_context
- evidence.hints_used = int(visual_context.get("hints_used") or 0)
- if evidence.hints_used and is_correct:
- evidence.quality = min(evidence.quality or 1.0, 0.6)
+ evidence.visual_context = visual_context or {}
+ evidence.hints_used = max(
+ int((visual_context or {}).get("hints_used") or 0), int(assistance_used)
+ )
+ if evidence.hints_used and is_correct:
+ evidence.quality = min(evidence.quality or 1.0, 0.6)
if verdict:
evidence.result = verdict["result"]
evidence.quality = {"correct": 1.0, "partial": .5, "incorrect": 0.0}[verdict["result"]]
@@ -633,6 +695,8 @@ class LearningService:
def set_pending_question(self, progress: LearningProgress, pending: PendingQuestion) -> None:
"""Store the question the tutor just posed so its expected answer can
be graded deterministically on a later turn (never via the model)."""
+ for question in pending.questions or [pending]:
+ _apply_source_assistance(progress, question)
progress.pending_question = pending
progress.updated_at = time.time()
self.save(progress)
@@ -642,6 +706,64 @@ class LearningService:
progress.updated_at = time.time()
self.save(progress)
+ def present_sources(
+ self, book_id: str, sources: list[dict], purpose: str, *,
+ session_id: str = "", turn_id: str = "",
+ ) -> list[dict]:
+ """Authorize explicit page display and persist assistance before delivery.
+
+ Called only by the trusted runtime after exact-source retrieval. A
+ failed delivery may conservatively leave a receipt; it cannot grant
+ independent credit after a possibly delivered answer-bearing page.
+ """
+ from deeptutor.services.rag.source_pages import SourceRef, public_source, resolve_source
+
+ if purpose not in {"teaching", "reveal"} or not 1 <= len(sources) <= 6:
+ raise MasteryInteractionError("Presentation needs one to six exact source pages")
+ refs = []
+ for source in sources:
+ try:
+ ref = SourceRef.model_validate(source.get("source_ref"))
+ except ValueError as exc:
+ raise MasteryInteractionError("Presentation requires an exact verified source page") from exc
+ resolve_source(ref)
+ refs.append(ref)
+ rows = [public_source(ref) for ref in refs]
+ for row in rows:
+ # A full-file link bypasses a page/crop presentation boundary.
+ row.pop("url", None)
+ pages = {_source_page_key(row) for row in rows}
+
+ def present(tx):
+ active = tx.active_interaction() or self._interaction_from_legacy_pending(tx.progress)
+ if active:
+ final_ids = {row["question_id"] for row in active.result.get("results", [])
+ if row.get("final", True)}
+ unresolved = [q for q in active.question.questions or [active.question]
+ if q.question_id not in final_ids]
+ if purpose == "reveal" and unresolved:
+ raise MasteryInteractionError("Answer every pending question before revealing source pages")
+ if any(not _question_source_pages(q) or pages.intersection(_question_source_pages(q))
+ for q in unresolved):
+ raise MasteryInteractionError(
+ "This source may disclose a pending answer; resolve the question before presentation"
+ )
+ known = {(_source_page_key(row), row.get("session_id"), row.get("turn_id"))
+ for row in tx.progress.source_exposures}
+ for row in rows:
+ key = (_source_page_key(row), session_id, turn_id)
+ if key not in known:
+ tx.progress.source_exposures.append({
+ "source_ref": row["source_ref"], "purpose": purpose,
+ "session_id": session_id, "turn_id": turn_id, "created_at": time.time(),
+ })
+ known.add(key)
+ tx.touch()
+ return rows
+
+ _, authorized = self._store.mutate(book_id, present)
+ return authorized
+
@staticmethod
def _interaction_from_legacy_pending(
progress: LearningProgress,
@@ -777,6 +899,9 @@ class LearningService:
question.source_evidence = question_snapshot(
self._store, tx.progress, question.knowledge_point_id
)
+ question.assistance_context = {"session_id": session_id, "turn_id": turn_id}
+ question.created_at = time.time()
+ _apply_source_assistance(tx.progress, question)
except LessonUnavailable as exc:
raise MasteryInteractionError(str(exc)) from exc
if active is not None:
@@ -1075,6 +1200,7 @@ class LearningService:
"is_correct": is_correct,
"knowledge_point_id": pending.knowledge_point_id,
**receipt,
+ "independent": _question_independent(pending),
}
if pending.visual_context:
interaction.result.update(
@@ -1082,7 +1208,7 @@ class LearningService:
"result": visual_result,
"diagnosis": visual_diagnosis,
"visual_context": pending.visual_context,
- "independent": not bool(pending.visual_context.get("hints_used")),
+ "independent": _question_independent(pending),
}
)
tx.put_interaction(interaction)
@@ -1277,9 +1403,7 @@ class LearningService:
final=correct is not None,
needs_clarification=correct is None,
feedback=diagnosis,
- independent=not bool(question.visual_context.get("hints_used"))
- if question.visual_context
- else None,
+ independent=_question_independent(question),
)
result["is_correct"] = correct
result.update((verdicts or {}).get(question.question_id, {}))
@@ -1355,6 +1479,7 @@ class LearningService:
) -> tuple[str, bool | None, str, str]:
"""Shared leaf grader: never creates a parent attempt or commits separately."""
pending = interaction.question
+ _apply_source_assistance(tx.progress, pending)
raw_answer = str(answer or "")
if interaction.status == InteractionStatus.ANSWERED:
stored = str(interaction.user_answer or "")
@@ -1444,6 +1569,7 @@ class LearningService:
session_id=session_id,
turn_id=turn_id,
visual_context=pending.visual_context,
+ assistance_used=pending.assistance_used,
verdict=verdict,
)
)
@@ -2207,9 +2333,7 @@ class LearningService:
if correct is not None
else str(stored.result.get("reason") or stored.result.get("diagnosis") or ""),
result="ungraded" if correct is None else "",
- independent=stored.result.get("independent")
- if stored.question.visual_context
- else None,
+ independent=stored.result.get("independent", _question_independent(stored.question)),
)
result.update(
{"is_correct": correct, "knowledge_point_id": stored.question.knowledge_point_id}
diff --git a/deeptutor/runtime/agentic/tool_dispatch.py b/deeptutor/runtime/agentic/tool_dispatch.py
index 6376ec0a4..ba436c869 100644
--- a/deeptutor/runtime/agentic/tool_dispatch.py
+++ b/deeptutor/runtime/agentic/tool_dispatch.py
@@ -198,6 +198,9 @@ async def dispatch_tool_calls(
display_args = {
k: v for k, v in exec_args.items() if not k.startswith("_") and k not in withheld
}
+ if exec_args.get("_mastery_source_context"):
+ # Retrieval queries themselves can quote an answer being verified.
+ display_args = {"presentation": exec_args.get("presentation") or "inspect"}
await stream.tool_call(
tool_name=tool_name,
args=display_args,
@@ -248,7 +251,7 @@ async def dispatch_tool_calls(
retrieve_meta_factory(
per_tool_trace_meta[tool_index],
tool_name,
- exec_args,
+ {} if exec_args.get("_mastery_source_context") else exec_args,
)
if retrieve_meta_factory
else None
@@ -705,7 +708,9 @@ async def execute_tool_call(
if status_meta is not None:
running_message = ""
if retrieve_meta is not None:
- query = str(retrieve_meta.get("query") or tool_args.get("query") or "").strip()
+ query = "" if tool_args.get("_mastery_source_context") else str(
+ retrieve_meta.get("query") or tool_args.get("query") or ""
+ ).strip()
running_message = f"Query: {query}" if query else start_retrieval_message
await stream.progress(
running_message,
@@ -779,6 +784,7 @@ async def execute_tool_call(
"terminate_turn": getattr(result, "terminate_turn", False),
"pause_for_user": getattr(result, "pause_for_user", None),
"model_message": getattr(result, "model_message", None),
+ "public_result": getattr(result, "public_result", None),
}
except Exception as exc:
# Unknown tool names arrive here too (the registry raises KeyError), so
@@ -860,21 +866,25 @@ async def _collect_outcome(
result_text = str(result["result_text"])
tool_meta = per_tool_trace_meta[tool_index]
tool_extra_meta = result.get("metadata") if isinstance(result, dict) else None
+ public_result = result.get("public_result")
+ projected = isinstance(public_result, dict)
+ public_text = str(public_result.get("content", "")) if projected else result_text
+ public_meta = public_result.get("metadata") if projected else tool_extra_meta
result_event_meta = merge_trace_metadata(tool_meta, {"trace_kind": "tool_result"})
- if isinstance(tool_extra_meta, dict) and tool_extra_meta:
+ if isinstance(public_meta, dict) and public_meta:
result_event_meta = merge_trace_metadata(
result_event_meta,
- {"tool_metadata": dict(tool_extra_meta)},
+ {"tool_metadata": dict(public_meta)},
)
if tool_index not in suppress_ui_indices:
await stream.tool_result(
tool_name=tool_name,
- result=result_text,
+ result=public_text,
source=source,
stage=stage,
metadata=result_event_meta,
)
- aggregated_sources.extend(result.get("sources") or [])
+ aggregated_sources.extend((public_result if projected else result).get("sources") or [])
tool_messages.append(
{
"role": "tool",
diff --git a/deeptutor/services/rag/source_visuals.py b/deeptutor/services/rag/source_visuals.py
index f742d6311..3b7fd1f33 100644
--- a/deeptutor/services/rag/source_visuals.py
+++ b/deeptutor/services/rag/source_visuals.py
@@ -178,6 +178,7 @@ class VisualEvidence:
sources: list[dict[str, Any]] = field(default_factory=list)
images: list[tuple[dict[str, Any], bytes]] = field(default_factory=list)
error: str = ""
+ private_content: str = ""
def model_message(self) -> dict[str, Any] | None:
parts = []
@@ -390,7 +391,7 @@ def retrieve_visual(
)
images.append(loaded)
break
- sources, paragraphs = [], []
+ sources, paragraphs, private_paragraphs = [], [], []
for record, _data in images:
image_url = source_url(kb_name, record, image=True)
location = source_url(kb_name, record)
@@ -413,12 +414,17 @@ def retrieve_visual(
table[:6000]
+ "\n[Structured table excerpt truncated; inspect the original page before interpreting omitted cells.]"
)
- paragraphs.append(
- f"Source: {record['source_path']}, page {record.get('page_number') or 'unverified'}.\n![Original source evidence]({image_url})\n[Original document]({location})\nCaption: {record.get('caption') or '(not supplied)'}\nSection: {record.get('section') or '(not supplied)'}\nNearby explanation: {record.get('context') or record.get('text') or '(not supplied)'}\nStructured table (if supplied): {table}\nNotes: {record.get('notes') or '(not supplied)'}"
+ identity = f"Source: {record['source_path']}, page {record.get('page_number') or 'unverified'}."
+ facts = f"Caption: {record.get('caption') or '(not supplied)'}\nSection: {record.get('section') or '(not supplied)'}\nNearby explanation: {record.get('context') or record.get('text') or '(not supplied)'}\nStructured table (if supplied): {table}\nNotes: {record.get('notes') or '(not supplied)'}"
+ paragraphs.append(f"{identity}\n![Original source evidence]({image_url})\n[Original document]({location})\n{facts}")
+ private_paragraphs.append(
+ f"{identity}\nSource hash: {record['source_document_id']}\n{facts}"
)
return VisualEvidence(
"\n\n".join(paragraphs)
+ "\nTreat captions as text evidence. Claim visual observations only after inspecting the attached pixels; re-retrieve this evidence on a detailed follow-up. If labels or the answer key remain unclear, abstain and request a region or source selection.",
sources,
images,
+ private_content="\n\n".join(private_paragraphs)
+ + "\nPrivate source evidence for verification. To display an original view, request explicit rag presentation with these exact source selectors. Inspect supplied pixels before making visual claims.",
)
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 94b96676b..1a9e1170f 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -104,7 +104,7 @@ def _rag_sources(result: dict[str, Any], *, query: str, kb_name: str) -> list[di
class RAGTool(_PromptHintsMixin, BaseTool):
def get_definition(self) -> ToolDefinition:
- return ToolDefinition(
+ definition = ToolDefinition(
name="rag",
description=(
"Retrieve relevant passages from one of the knowledge bases the "
@@ -155,10 +155,50 @@ class RAGTool(_PromptHintsMixin, BaseTool):
required=False,
description="Source document ID from an earlier citation; rejects changed source-page references.",
),
+ ToolParameter(
+ name="presentation", type="string", required=False,
+ description="In Guided Learning, inspect (default) keeps source evidence private. Use teaching only to intentionally show an exact source view while explaining it; reveal requests a source view after answering. The server checks pending questions and records assistance. Preparation never displays a page automatically.",
+ enum=["inspect", "teaching", "reveal"],
+ ),
],
)
+ schema = definition.to_openai_schema()["function"]["parameters"]
+ schema["properties"]["presentation"]["type"] = ["string", "null"]
+ schema["properties"]["presentation"]["enum"].append(None)
+ definition.raw_parameters = schema
+ return definition
async def execute(self, **kwargs: Any) -> ToolResult:
+ result = await self._retrieve(**kwargs)
+ if kwargs.get("_mastery_source_context"):
+ result.public_result = {"content": "Source evidence inspected privately."}
+ presentation = kwargs.get("presentation") or "inspect"
+ if presentation != "inspect":
+ presenter = kwargs.get("_present_mastery_sources")
+ if presentation not in {"teaching", "reveal"} or not callable(presenter):
+ result.success = False
+ result.content += "\nSource presentation is unavailable; no source was displayed."
+ elif not result.success or not result.metadata.get("presentation_sources"):
+ result.success = False
+ result.content += "\nPresentation requires an exact verified PDF view; retrieve its source_path and page."
+ else:
+ from deeptutor.learning.service import MasteryInteractionError
+
+ try:
+ sources = await presenter(result.metadata["presentation_sources"], presentation)
+ result.public_result = {
+ "content": "Selected source view presented.",
+ "sources": [{**row, "presentation": presentation} for row in sources],
+ }
+ result.content += "\nThe selected source view was publicly presented."
+ except (ValueError, MasteryInteractionError) as exc:
+ result.success = False
+ result.content += f"\nSource presentation was withheld: {exc}"
+ if not result.success:
+ result.public_result["content"] = "Source evidence could not be presented or verified."
+ return result
+
+ async def _retrieve(self, **kwargs: Any) -> ToolResult:
from deeptutor.tools.rag_tool import rag_search
query = str(kwargs.get("query") or "").strip()
@@ -167,7 +207,7 @@ class RAGTool(_PromptHintsMixin, BaseTool):
kb_name = str(kwargs.get("kb_name") or "").strip()
if not kb_name:
raise ValueError("RAG requires an explicit kb_name.")
- event_sink = kwargs.get("event_sink")
+ event_sink = None if kwargs.get("_mastery_source_context") else kwargs.get("event_sink")
vision_supported = bool(kwargs.get("_vision_supported", False))
from deeptutor.services.rag.source_visuals import figure_labels, retrieve_visual
@@ -193,9 +233,22 @@ class RAGTool(_PromptHintsMixin, BaseTool):
)
except (OSError, ValueError, TypeError) as exc:
return ToolResult(content=f"Source visual inspection failed: {exc}", success=False)
- content = evidence.content
+ content = (evidence.private_content or evidence.content) if kwargs.get("_mastery_source_context") else evidence.content
if not vision_supported and evidence.images:
content += "\nThe selected model cannot inspect pixels; interpret only the text evidence. Open the source or select a vision-capable model for visual claims."
+ presentation_sources = []
+ if kwargs.get("_mastery_source_context") and kwargs.get("presentation") in {"teaching", "reveal"}:
+ from deeptutor.services.rag.source_pages import SourceRef, public_source
+
+ for record, _pixels in evidence.images:
+ if not record.get("page_number") or not str(record.get("source_path", "")).lower().endswith(".pdf"):
+ continue
+ ref = SourceRef(kb_ref=kb_name, document_key=record["source_path"],
+ source_digest=record["source_document_id"], page_index=record["page_number"] - 1,
+ crop=record.get("region"))
+ row = public_source(ref)
+ row.pop("url", None)
+ presentation_sources.append(row)
return ToolResult(
content=content,
sources=evidence.sources,
@@ -203,13 +256,15 @@ class RAGTool(_PromptHintsMixin, BaseTool):
metadata={
"evidence_kind": "exact_source_visual",
"error_type": evidence.error or None,
+ "presentation_sources": presentation_sources,
},
model_message=evidence.model_message() if vision_supported else None,
)
extra_kwargs = {
key: value
for key, value in kwargs.items()
- if key not in {"query", "kb_name", "event_sink", "_vision_supported"}
+ if key not in {"query", "kb_name", "event_sink", "_vision_supported", "presentation",
+ "_mastery_source_context", "_present_mastery_sources"}
}
result = await rag_search(
@@ -959,6 +1014,8 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
return ToolResult(
content=str(full_text),
metadata={"source_id": source_id, "char_count": len(str(full_text))},
+ public_result={"content": "Attached source inspected privately."}
+ if kwargs.get("_mastery_source_context") else None,
)
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index bdd1840e4..8f8ef3309 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -1711,6 +1711,97 @@ async def test_mastery_card_promise_repair_uses_real_question_tool(
assert _result(events).metadata["response"] == ""
[email protected]("recovery", ["success", "unsupported", "rogue", "failed_prepare", "stale"])
+async def test_mastery_preparation_at_settlement_boundary_gets_one_delivery_round(
+ recovery: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A successful source repair gets one restricted chance to deliver its card."""
+ from deeptutor.capabilities.mastery.tools import MasteryPrepareLessonTool
+ from deeptutor.learning import semantic_assessment
+
+ monkeypatch.setenv("DEEPTUTOR_WORKSPACE_ROOT", str(tmp_path))
+
+ def init_store(self, root=None):
+ self._root = tmp_path / "learning"
+ self._root.mkdir(parents=True, exist_ok=True)
+
+ monkeypatch.setattr(LearningStore, "__init__", init_store)
+ LearningStore().save(LearningProgress(book_id="p1", modules=[LearningModule(
+ id="m1", name="Synthetic", order=0, knowledge_points=[KnowledgePoint(
+ id="kp1", name="Synthetic objective", type="memory", module_id="m1"
+ )]
+ )]))
+ prepared = False
+
+ async def verify(_store, _progress, _questions, config=None):
+ if not prepared or recovery == "unsupported":
+ raise semantic_assessment.AssessmentUnavailable("Synthetic unsupported source contract.")
+
+ monkeypatch.setattr(semantic_assessment, "bind_questions", verify)
+ quiz_args = {"questions": [
+ {"knowledge_point_id": "kp1", "question": "Synthetic first?", "expected_answer": "one"},
+ {"knowledge_point_id": "kp1", "question": "Synthetic second?", "expected_answer": "two"},
+ ]}
+
+ class Registry(_Registry):
+ def build_openai_schemas(self, _enabled):
+ return [tool.get_definition().to_openai_schema() for tool in (
+ MasteryQuizTool(), MasteryPrepareLessonTool()
+ )]
+
+ async def execute(self, name, **kwargs):
+ nonlocal prepared
+ self.executed.append({"name": name, "kwargs": kwargs})
+ if name == "mastery_quiz":
+ return await MasteryQuizTool().execute(**kwargs)
+ assert name == "mastery_prepare_lesson"
+ if recovery == "failed_prepare":
+ return ToolResult(content="Synthetic preparation unavailable.", success=False)
+ prepared = True
+ kwargs["_bind_lesson_objective"]("kp1")
+ if recovery == "stale":
+ progress = LearningStore().load("p1")
+ LearningStore().save(progress)
+ return ToolResult(content="Synthetic source preparation succeeded.", success=True)
+
+ def tool(name, args, call_id):
+ return [_llm_chunk(tool_calls=[{"id": call_id, "name": name,
+ "arguments": json.dumps(args)}], finish_reason="tool_calls")]
+
+ script = [tool("mastery_quiz", quiz_args, "quiz-1"),
+ tool("mastery_quiz", quiz_args, "quiz-2"),
+ [_llm_chunk(content="Done.", finish_reason="stop")],
+ tool("mastery_prepare_lesson", {"knowledge_point_id": "kp1"}, "repair")]
+ if recovery not in {"failed_prepare", "stale"}:
+ script.append(tool("mastery_prepare_lesson", {"knowledge_point_id": "kp1"}, "rogue")
+ if recovery == "rogue" else tool("mastery_quiz", quiz_args, "delivery"))
+ client, registry = _ScriptedChatClient(script), Registry()
+ pipeline = MasteryLoopPipeline(language="en")
+ pipeline._max_rounds = 1
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _ctx: ["mastery_quiz", "mastery_prepare_lesson"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+ context = UnifiedContext(session_id="s1", user_message="Give me two practice questions.",
+ allowed_builtin_tools=["mastery_quiz", "mastery_prepare_lesson"], metadata={
+ "mastery_mode": True, "mastery_path_id": "p1", "mastery_session_mode": "study", "turn_id": "repair-turn"
+ })
+ events = await _run(pipeline, context)
+ assert client.call_count == (4 if recovery in {"failed_prepare", "stale"} else 5)
+ if client.call_count == 5:
+ assert [schema["function"]["name"] for schema in client.calls[-1]["tools"]] == ["mastery_quiz"]
+ assert [row["name"] for row in registry.executed].count("mastery_prepare_lesson") == 1
+ assert _result(events).metadata["completed"] is (recovery == "success")
+ pending = LearningStore().load("p1").pending_question
+ if recovery == "success":
+ assert pending is not None and len(pending.questions) == 2
+ cards = [event for event in events if event.type == StreamEventType.TOOL_RESULT
+ and "mastery_question" in event.metadata.get("tool_metadata", {})]
+ assert len(cards) == 1
+ else:
+ assert pending is None
+
+
@pytest.mark.asyncio
async def test_truncated_pure_reasoning_round_is_told_to_act_not_continue(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.py
index 9c5cfb6ab..3a10ede31 100644
--- a/tests/capabilities/test_mastery_capability.py
+++ b/tests/capabilities/test_mastery_capability.py
@@ -62,6 +62,62 @@ def _progress_with_objective() -> LearningProgress:
)
[email protected]("case", ["explanation", "ready", "retried", "rebound", "delivered"])
+def test_settlement_delivery_requires_fresh_quiz_preparation_receipt(case, tmp_path, monkeypatch):
+ _use_store_root(monkeypatch, tmp_path)
+ LearningStore().save(_progress_with_objective())
+ context, capability = _context(), MasteryLoopCapability()
+ if case != "explanation":
+ capability.augment_kwargs("mastery_quiz", {}, context)
+ prepared = capability.augment_kwargs("mastery_prepare_lesson", {}, context)
+ prepared["_bind_lesson_objective"]("kp-1")
+ if case == "retried":
+ capability.augment_kwargs("mastery_quiz", {}, context)
+ elif case == "rebound":
+ context.metadata["mastery_path_id"] = "another-path"
+ elif case == "delivered":
+ context.extension("mastery")["card_posted"] = True
+ recovery = capability.settlement_recovery(context)
+ if case == "ready":
+ assert recovery is not None and recovery[1] == ("mastery_quiz",)
+ # Even a later fresh preparation cannot purchase another final round.
+ prepared["_bind_lesson_objective"]("kp-1")
+ assert capability.settlement_recovery(context) is None
+ else:
+ assert recovery is None
+
+
[email protected]("changed", [None, "path", "session", "turn"])
+async def test_mastery_source_presentation_callback_is_server_bound(changed, monkeypatch):
+ context, capability = _context(), MasteryLoopCapability()
+ calls = []
+
+ def present(_self, path_id, sources, purpose, **kwargs):
+ calls.append((path_id, sources, purpose, kwargs))
+ return sources
+
+ monkeypatch.setattr(LearningService, "present_sources", present)
+ bound = capability.augment_kwargs("rag", {
+ "_mastery_source_context": False, "_present_mastery_sources": "model-supplied"
+ }, context)
+ assert bound["_mastery_source_context"] is True
+ if changed == "path":
+ context.metadata["mastery_path_id"] = "other"
+ elif changed == "session":
+ context.session_id = "other"
+ elif changed == "turn":
+ context.metadata["turn_id"] = "other"
+ if changed:
+ with pytest.raises(ValueError, match="context changed"):
+ await bound["_present_mastery_sources"]([{"source_ref": "synthetic"}], "teaching")
+ assert calls == []
+ else:
+ sources = [{"source_ref": "synthetic"}]
+ assert await bound["_present_mastery_sources"](sources, "teaching") == sources
+ assert calls == [("path-1", sources, "teaching", {"session_id": "session-1", "turn_id": "turn-2"})]
+
+
_GRADED_REVIEW = """回答正确!你选择的 C 正是 Agentic RAG 的核心做法。
我们逐个看其他选项为什么不对:
diff --git a/tests/capabilities/test_mastery_demand_preparation.py b/tests/capabilities/test_mastery_demand_preparation.py
index 4f61d6b98..a7e5b4ea2 100644
--- a/tests/capabilities/test_mastery_demand_preparation.py
+++ b/tests/capabilities/test_mastery_demand_preparation.py
@@ -67,7 +67,7 @@ async def test_valid_packet_is_reused_without_new_preparation(preparation, monke
preparation.paid.assert_not_awaited()
assert pixels.call_count == 1
assert pixels.call_args.args == (evidence["sources"][:2],)
- preparation.stream.sources.assert_awaited_once()
+ preparation.stream.sources.assert_not_awaited()
assert len(messages) == 1 and messages[0]["content"] == "VERIFIED ACTIVE LESSON"
diff --git a/tests/capabilities/test_mastery_source_assistance.py b/tests/capabilities/test_mastery_source_assistance.py
new file mode 100644
index 000000000..2de992014
--- /dev/null
+++ b/tests/capabilities/test_mastery_source_assistance.py
@@ -0,0 +1,174 @@
+"""Public source exposure assists its assessment attempt, not future learning."""
+
+import json
+
+import pytest
+
+from deeptutor.learning import lesson_evidence
+from deeptutor.learning.models import (
+ KnowledgePoint, KnowledgeType, LearningModule, LearningProgress, PendingQuestion,
+)
+from deeptutor.learning.pending import public_pending_question
+from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+from deeptutor.learning.service import LearningService, MasteryInteractionError
+from deeptutor.learning.storage import LearningStore
+from deeptutor.services.rag import source_pages
+
+
+def source(page=0):
+ return {"source_ref": {"kb_ref": "synthetic-kb", "document_key": "material.pdf",
+ "source_digest": "a" * 64, "page_index": page}}
+
+
+def question(key="one", page=0):
+ return PendingQuestion(
+ question_id=key, knowledge_point_id=key, module_id="m",
+ prompt=f"Question {key}?", question_type="choice", expected_answer="A",
+ options=[{"label": "A", "body": "alpha"}, {"label": "B", "body": "beta"}],
+ source_evidence={"sources": [{"ref": source(page)["source_ref"]}]},
+ )
+
+
+def service(tmp_path, monkeypatch):
+ svc = LearningService(LearningStore(tmp_path))
+ svc.save(LearningProgress(book_id="p", modules=[LearningModule(
+ id="m", name="Synthetic module", order=0, knowledge_points=[
+ KnowledgePoint(id=key, name=key, module_id="m", type=KnowledgeType.MEMORY)
+ for key in ("one", "two")
+ ])], knowledge_types={"one": KnowledgeType.MEMORY, "two": KnowledgeType.MEMORY}))
+ monkeypatch.setattr(lesson_evidence, "question_snapshot", lambda _s, _p, key: {
+ "sources": [{"ref": source(0 if key == "one" else 1)["source_ref"]}]
+ })
+ monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *_a, **_kw: None)
+ monkeypatch.setattr(source_pages, "resolve_source", lambda _ref: tmp_path / "material.pdf")
+ return svc
+
+
+def test_public_source_before_question_remains_assisted_after_reload(service):
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="t")
+ service = LearningService(LearningStore(service.store._root))
+ _, pending, _ = service.register_question("p", question(), session_id="s", turn_id="t")
+ progress, graded, _ = service.grade_interaction(
+ "p", question_id="one", answer="A", scheduler=SpacedRepetitionScheduler()
+ )
+ assert progress.quiz_attempts[0].independent is False
+ assert graded.result["independent"] is False
+ assert progress.mastery_levels["one"] == 0
+ assert progress.learning_evidence[0].hints_used >= 1
+ assert progress.learning_evidence[0].quality <= .6
+ assert pending.question.visual_context == {}
+ assert "assistance_used" not in json.dumps(public_pending_question(pending.question).to_dict())
+ assert "source_evidence" not in json.dumps(graded.result)
+
+
+def test_unexposed_source_still_earns_independent_credit(service):
+ service.present_sources("p", [source(4)], "teaching", session_id="s", turn_id="t")
+ service.register_question("p", question(), session_id="s", turn_id="t")
+ progress, graded, _ = service.grade_interaction("p", question_id="one", answer="A")
+ assert progress.quiz_attempts[0].independent is True
+ assert graded.result["independent"] is True
+ assert progress.learning_evidence[0].quality == 1
+
+
+def test_group_assistance_is_per_leaf_and_survives_correction_replay(service):
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="t")
+ service.register_question("p", PendingQuestion(
+ question_id="group", knowledge_point_id="one", question_type="group",
+ questions=[question(), question("two", 1)],
+ ), session_id="s", turn_id="t")
+ progress, graded, _ = service.grade_interaction(
+ "p", question_id="group", answer="", answers={"one": "B", "two": "A"}
+ )
+ assert [a.independent for a in progress.quiz_attempts] == [False, True]
+ service.repair_question("p", "one", action="correct", expected_answer="B", reason="Synthetic correction")
+ progress, replay, replayed = service.grade_interaction("p", question_id="group", answer="")
+ assert replayed
+ assert [a.independent for a in progress.quiz_attempts] == [False, True]
+ assert [row["independent"] for row in replay.result["results"]] == [False, True]
+ assert progress.learning_evidence[0].quality <= .6
+ assert progress.mastery_levels["one"] == 0
+ assert len(progress.quiz_attempts) == 2
+
+
[email protected]("purpose", ["teaching", "reveal"])
+def test_active_question_blocks_answer_source_display_without_mutation(service, purpose):
+ service.register_question("p", question())
+ before = service.store.load("p").model_dump()
+ with pytest.raises(MasteryInteractionError):
+ service.present_sources("p", [source()], purpose)
+ assert service.store.load("p").model_dump() == before
+
+
+def test_unrelated_teaching_image_allowed_while_question_pending(service):
+ service.register_question("p", question())
+ assert service.present_sources("p", [source(5)], "teaching")
+ progress, _, _ = service.grade_interaction("p", question_id="one", answer="A")
+ assert progress.quiz_attempts[0].independent
+
+
+def test_partial_group_cannot_reveal_page_with_unanswered_sibling(service):
+ service.register_question("p", PendingQuestion(
+ question_id="group", knowledge_point_id="one", question_type="group",
+ questions=[question(), question("two", 1)],
+ ))
+ service.grade_interaction("p", question_id="group", answer="", answers={"one": "A"})
+ with pytest.raises(MasteryInteractionError):
+ service.present_sources("p", [source()], "reveal")
+ service.grade_interaction("p", question_id="group", answer="", answers={"two": "A"})
+ assert service.present_sources("p", [source()], "reveal")
+ assert all(a.independent for a in service.store.load("p").quiz_attempts)
+
+
+def test_duplicate_publication_keeps_one_durable_receipt(service):
+ for _ in range(2):
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="t")
+ assert len(service.store.load("p").source_exposures) == 1
+
+
+def test_source_access_failure_does_not_record_publication(service, monkeypatch):
+ def revoked(_ref):
+ raise source_pages.SourcePageError("Synthetic revoked source")
+ monkeypatch.setattr(source_pages, "resolve_source", revoked)
+ before = service.store.load("p").model_dump()
+ with pytest.raises(ValueError):
+ service.present_sources("p", [source()], "teaching")
+ assert service.store.load("p").model_dump() == before
+
+
[email protected]("session_id,turn_id", [("s", "later"), ("new-session", "t")])
+def test_previous_teaching_does_not_contaminate_new_assessment(service, session_id, turn_id):
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="t")
+ service.register_question("p", question(), session_id=session_id, turn_id=turn_id)
+ progress, graded, _ = service.grade_interaction("p", question_id="one", answer="A")
+ assert progress.quiz_attempts[0].independent is True
+ assert graded.result["independent"] is True
+ assert progress.learning_evidence[0].hints_used == 0
+ assert progress.learning_evidence[0].quality == 1
+
+
+def test_repeated_page_presentation_has_a_receipt_for_each_native_turn(service):
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="old")
+ service.present_sources("p", [source()], "teaching", session_id="s", turn_id="now")
+ assert len(service.store.load("p").source_exposures) == 2
+ service.register_question("p", question(), session_id="s", turn_id="now")
+ progress, _, _ = service.grade_interaction("p", question_id="one", answer="A")
+ assert progress.quiz_attempts[0].independent is False
+
+
[email protected]("receipt_session,independent", [("s", False), ("other", True)])
+def test_later_public_receipt_applies_only_to_same_pending_attempt_session(service, receipt_session, independent):
+ _, interaction, _ = service.register_question("p", question(), session_id="s", turn_id="question")
+ # Model an already delivered server receipt, not a caller assistance flag.
+ # Normal presentation refuses answer-bearing pages while a card is open.
+ def record_exposure(tx):
+ tx.progress.source_exposures.append({
+ **source(), "purpose": "teaching", "session_id": receipt_session,
+ "turn_id": "later", "created_at": interaction.question.created_at + 1,
+ })
+ tx.touch()
+ service.store.mutate("p", record_exposure)
+ service = LearningService(LearningStore(service.store._root))
+ progress, graded, _ = service.grade_interaction("p", question_id="one", answer="A")
+ assert progress.quiz_attempts[0].independent is independent
+ assert graded.result["independent"] is independent
diff --git a/tests/core/agentic/test_private_tool_projection.py b/tests/core/agentic/test_private_tool_projection.py
new file mode 100644
index 000000000..a7dd6db00
--- /dev/null
+++ b/tests/core/agentic/test_private_tool_projection.py
@@ -0,0 +1,68 @@
+"""Internal retrieval evidence never enters replayable public stream events."""
+import asyncio
+import json
+
+import pytest
+
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.tool_protocol import ToolResult
+from deeptutor.runtime.agentic.tool_dispatch import dispatch_tool_calls
+from deeptutor.runtime.stream_bus import StreamBus
+
+
+async def test_public_projection_preserves_private_model_evidence_and_replay(tmp_path):
+ class Registry:
+ async def execute(self, name, **kwargs):
+ return ToolResult(
+ content="SECRET_KEY: C", metadata={"answer": "SECRET_KEY"},
+ sources=[{"url": "/SECRET_KEY.pdf"}],
+ model_message={"role": "user", "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,SECRET_PIXELS"}}
+ ]},
+ public_result={"content": "Sources inspected privately."},
+ )
+
+ bus = StreamBus()
+ events = []
+ async def consume():
+ async for event in bus.subscribe():
+ events.append(event.to_dict())
+ consumer = asyncio.create_task(consume())
+ await asyncio.sleep(0)
+ outcome = await dispatch_tool_calls(
+ tool_calls=[{"id": "inspect", "name": "rag", "arguments": '{"query":"SECRET_QUERY"}'}],
+ context=UnifiedContext(session_id="synthetic", user_message="Quiz me"),
+ stream=bus, source="mastery_path", stage="responding", iteration_index=0,
+ registry=Registry(),
+ kwarg_augmenter=lambda name, args, context: {**args, "_mastery_source_context": True},
+ retrieve_meta_factory=lambda meta, name, args: {**meta, "query": args.get("query", "")},
+ )
+ await bus.close()
+ await consumer
+ from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+ store = SQLiteSessionStore(tmp_path / "synthetic-source-replay.db")
+ session = await store.create_session("Synthetic source replay")
+ turn = await store.begin_turn(session["session_id"], "mastery_path")
+ await store.append_turn_events(turn["id"], events)
+ reopened = SQLiteSessionStore(store.db_path)
+ replay = await reopened.get_turn_events(turn["id"])
+ assert "SECRET" not in json.dumps(replay)
+ assert "Sources inspected privately." in json.dumps(replay)
+ assert outcome.sources == []
+ assert "SECRET_KEY" in json.dumps(outcome.tool_messages)
+ assert "SECRET_PIXELS" in json.dumps(outcome.model_messages)
+
+
+async def test_read_source_uses_private_projection_for_mastery():
+ from deeptutor.tools.builtin import ReadSourceTool
+
+ result = await ReadSourceTool().execute(source_id="qb-example",
+ source_index={"qb-example": "SECRET_BANK_ANSWER"}, _mastery_source_context=True)
+ assert result.content == "SECRET_BANK_ANSWER"
+ assert result.public_result == {"content": "Attached source inspected privately."}
+ ordinary = await ReadSourceTool().execute(source_id="qb-example",
+ source_index={"qb-example": "Attached source"})
+ assert ordinary.public_result is None
diff --git a/tests/services/rag/test_mastery_source_pages.py b/tests/services/rag/test_mastery_source_pages.py
index 09c4d2e7c..764b734e7 100644
--- a/tests/services/rag/test_mastery_source_pages.py
+++ b/tests/services/rag/test_mastery_source_pages.py
@@ -424,6 +424,21 @@ def test_final_repair_gap_preserves_already_inspected_useful_sources(material, m
assert evidence["sources"][0]["ref"]["page_index"] == 70
[email protected]("changed_support", [False, True])
+def test_repair_reuses_only_identical_successful_inspection(material, monkeypatch, changed_support):
+ repaired = _partial_selection()
+ if changed_support:
+ repaired["selected"][0]["reason"] = "A different relationship needs inspection"
+ calls = _install_preparation(
+ material, monkeypatch, rankings=[_partial_selection(repair=True), repaired]
+ )
+ evidence = asyncio.run(lessons.prepare_lesson(material.store, "path", "kp", material.config))
+ pixel_calls = [payload for payload, images in calls if images]
+ assert len(pixel_calls) == (2 if changed_support else 1)
+ assert evidence["sources"] and evidence["model_observations"]
+ assert not evidence["coverage"]["complete"]
+
+
def test_focus_and_current_request_reach_preparation_without_extra_cache_calls(material, monkeypatch):
calls = _install_preparation(material, monkeypatch)
first = asyncio.run(lessons.prepare_lesson(material.store, "path", "kp", material.config,
diff --git a/tests/tools/test_mastery_source_presentation.py b/tests/tools/test_mastery_source_presentation.py
new file mode 100644
index 000000000..ac1bd0bf1
--- /dev/null
+++ b/tests/tools/test_mastery_source_presentation.py
@@ -0,0 +1,126 @@
+"""Recorded RAG argument failures, replayed without an LLM or network."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pymupdf
+import pytest
+
+from deeptutor.tools.builtin import RAGTool
+
+
+def source_kb(tmp_path, monkeypatch):
+ kb = tmp_path / "demo"
+ (kb / "raw").mkdir(parents=True)
+ with pymupdf.open() as doc:
+ doc.new_page().insert_text((72, 72), "Original source page")
+ doc.save(kb / "raw" / "manual.pdf")
+ monkeypatch.setattr(
+ "deeptutor.multi_user.knowledge_access.resolve_for_rag",
+ lambda _: SimpleNamespace(base_dir=kb.parent, name=kb.name),
+ )
+ return kb
+
+
+def _arguments():
+ return dict(
+ query="Inspect this source", kb_name="demo", source_path="manual.pdf",
+ asset_id="", figure="", page=1, region=None, source_hash="",
+ )
+
+
+def test_mastery_inspection_keeps_original_pixels_private(source_kb):
+ result = asyncio.run(RAGTool().execute(**_arguments(), _vision_supported=True,
+ _mastery_source_context=True))
+ assert "Original source page" in result.content
+ assert result.model_message
+ assert result.public_result == {"content": "Source evidence inspected privately."}
+ assert "![Original source evidence]" not in result.content
+ assert "/api/knowledge-bases/" not in result.content
+ assert "manual.pdf" in result.content
+
+
+def test_mastery_presentation_requires_server_authorization(source_kb):
+ result = asyncio.run(RAGTool().execute(**_arguments(), presentation="teaching",
+ _mastery_source_context=True))
+ assert not result.success
+ assert not result.public_result.get("sources")
+
+
+def test_mastery_explicit_presentation_uses_authorized_view_only(source_kb):
+ async def present(sources, purpose):
+ assert purpose == "teaching" and sources[0]["page"] == 1
+ assert sources[0]["source_ref"]["page_index"] == 0
+ assert "url" not in sources[0]
+ return [{"title": "Diagram", "preview_url": sources[0]["preview_url"]}]
+ result = asyncio.run(RAGTool().execute(**_arguments(), presentation="teaching",
+ _mastery_source_context=True, _present_mastery_sources=present))
+ assert result.success
+ assert result.public_result["sources"][0]["presentation"] == "teaching"
+ assert "Original source page" not in str(result.public_result)
+
+
+async def test_real_mastery_rag_dispatch_does_not_replay_private_passages(source_kb):
+ from deeptutor.core.context import UnifiedContext
+ from deeptutor.runtime.agentic.tool_dispatch import dispatch_tool_calls
+ from deeptutor.runtime.stream_bus import StreamBus
+
+ class Registry:
+ def get(self, name):
+ return RAGTool()
+ async def execute(self, name, **kwargs):
+ return await RAGTool().execute(**kwargs)
+
+ bus, records = StreamBus(), []
+ async def consume():
+ async for event in bus.subscribe():
+ records.append(event.to_dict())
+ consumer = asyncio.create_task(consume())
+ await asyncio.sleep(0)
+ result = await dispatch_tool_calls(
+ tool_calls=[{"id": "inspect", "name": "rag", "arguments": json.dumps(_arguments())}],
+ context=UnifiedContext(session_id="synthetic", user_message="Quiz me"),
+ stream=bus, source="mastery_path", stage="responding", iteration_index=0,
+ registry=Registry(),
+ kwarg_augmenter=lambda name, args, context: {
+ **args, "_mastery_source_context": True, "_vision_supported": True,
+ },
+ )
+ await bus.close()
+ await consumer
+ replay = json.loads(json.dumps(records))
+ assert all(value not in json.dumps(replay) for value in (
+ "Original source page", "source-page?", "manual.pdf", "base64",
+ ))
+ assert result.sources == []
+ assert "Original source page" in result.tool_messages[0]["content"]
+ assert result.model_messages
+
+
+def test_mastery_semantic_result_metadata_and_progress_remain_private(monkeypatch):
+ async def search(**kwargs):
+ assert kwargs["event_sink"] is None
+ assert "_mastery_source_context" not in kwargs
+ assert "presentation" not in kwargs
+ return {"answer": "SECRET_SOLUTION", "sources": [{"text": "SECRET_SOLUTION"}]}
+ monkeypatch.setattr("deeptutor.tools.rag_tool.rag_search", search)
+ result = asyncio.run(RAGTool().execute(query="Question", kb_name="demo",
+ _mastery_source_context=True, presentation="inspect", event_sink=object()))
+ assert result.content == "SECRET_SOLUTION"
+ assert "SECRET_SOLUTION" not in json.dumps(result.public_result)
+
+
+def test_pending_presentation_denial_preserves_private_evidence(source_kb):
+ from deeptutor.learning.service import MasteryInteractionError
+
+ async def deny(sources, purpose):
+ raise MasteryInteractionError("An unanswered question uses this page.")
+ result = asyncio.run(RAGTool().execute(**_arguments(), presentation="teaching",
+ _mastery_source_context=True, _present_mastery_sources=deny, _vision_supported=True))
+ assert not result.success
+ assert "Original source page" in result.content
+ assert result.model_message
+ assert not result.public_result.get("sources")
diff --git a/web/components/chat/home/MasterySourcePresentation.tsx b/web/components/chat/home/MasterySourcePresentation.tsx
new file mode 100644
index 000000000..83d76dfe4
--- /dev/null
+++ b/web/components/chat/home/MasterySourcePresentation.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { StreamEvent } from "@/features/chat/model/protocol";
+import { apiUrl } from "@/lib/api";
+import ImagePreview from "@/components/chat/preview/previewers/ImagePreview";
+import { useBinarySource } from "@/components/chat/preview/previewers/useBinarySource";
+
+type Page = { title: string; preview_url: string };
+
+function presentedPages(events: StreamEvent[]): Page[] {
+ const pages = new Map<string, Page>();
+ for (const event of events) {
+ if (event.type !== "sources" || !["chat", "mastery_path"].includes(event.source)) continue;
+ const sources = event.metadata.sources;
+ if (!Array.isArray(sources)) continue;
+ for (const source of sources) {
+ if (!source || typeof source !== "object") continue;
+ if (source.presentation !== "teaching" && source.presentation !== "reveal") continue;
+ const { title, preview_url } = source;
+ // Authenticated requests must stay on the exact native source-page route.
+ if (typeof title !== "string" || typeof preview_url !== "string" ||
+ !/^\/api\/knowledge-bases\/[A-Za-z0-9_%.-]+\/source-page\?/.test(preview_url)) continue;
+ const parsed = new URL(preview_url, "https://source.invalid");
+ if (parsed.pathname !== preview_url.split("?")[0]) continue;
+ pages.set(preview_url, { title, preview_url });
+ }
+ }
+ return [...pages.values()].slice(0, 12);
+}
+
+function SourcePage({ page }: { page: Page }) {
+ const { t } = useTranslation();
+ const state = useBinarySource(apiUrl(page.preview_url));
+ const [url, setUrl] = useState<string | null>(null);
+ useEffect(() => {
+ if (state.kind !== "ready") { setUrl(null); return; }
+ const next = URL.createObjectURL(new Blob([state.buffer], { type: "image/png" }));
+ setUrl(next);
+ return () => URL.revokeObjectURL(next);
+ }, [state]);
+ return <figure className="my-3 rounded-lg border border-[var(--border)] p-2">
+ <figcaption className="mb-2 break-words text-xs text-[var(--muted-foreground)]">{page.title}</figcaption>
+ {url ? <div className="h-96 w-full"><ImagePreview url={url} filename={page.title} /></div>
+ : <p role="status" className="text-sm">{state.kind === "error" ? t("Failed to load image.") : t("Loading...")}</p>}
+ </figure>;
+}
+
+/** Render publication receipts; publication does not prove that a learner viewed a page. */
+export function MasterySourcePresentation({ events }: { events: StreamEvent[] }) {
+ return <>{presentedPages(events).map(page => <SourcePage key={page.preview_url} page={page} />)}</>;
+}
diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsx
index 3a88e02c8..67dd94d6c 100644
--- a/web/features/chat/messages/ChatMessageList.tsx
+++ b/web/features/chat/messages/ChatMessageList.tsx
@@ -82,6 +82,7 @@ import {
type MessageSegment,
} from "@/components/chat/home/AskUserOptions";
import { MasteryQuestionCard } from "@/components/chat/home/MasteryQuestionCard";
+import { MasterySourcePresentation } from "@/components/chat/home/MasterySourcePresentation";
import {
collectMasteryAnswerRejections,
collectMasteryGrades,
@@ -1175,6 +1176,7 @@ export const AssistantMessage = memo(function AssistantMessage({
events={events}
/>
)}
+ <MasterySourcePresentation events={events} />
{/* Non-default branches (quiz, math animator, visualize) keep the
card below the body. The default branch inlines it via
``messageSegments``; the research branch renders its own card
diff --git a/web/tests/mastery-source-presentation.spec.tsx b/web/tests/mastery-source-presentation.spec.tsx
new file mode 100644
index 000000000..1a1ab8614
--- /dev/null
+++ b/web/tests/mastery-source-presentation.spec.tsx
@@ -0,0 +1,56 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { StreamEvent } from "@/features/chat/model/protocol";
+import { MasterySourcePresentation } from "@/components/chat/home/MasterySourcePresentation";
+
+const apiFetch = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/api", () => ({ apiFetch, apiUrl: (url: string) => url }));
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const preview = "/api/knowledge-bases/course/source-page?document=lecture.pdf&page=7&digest=abc";
+function event(sources: unknown[]): StreamEvent {
+ return { type: "sources", source: "chat", stage: "responding", content: "",
+ timestamp: 1, metadata: { sources } };
+}
+
+beforeEach(() => {
+ apiFetch.mockReset().mockResolvedValue({ ok: true, headers: new Headers(),
+ arrayBuffer: async () => new ArrayBuffer(4) });
+ vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:source-page");
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
+});
+
+describe("Explicit Mastery source presentation", () => {
+ it.each(["teaching", "reveal"])("renders authenticated %s pages from shared-loop events and replay", async presentation => {
+ const sources = event([{ title: "Lecture page 7", preview_url: preview, presentation }]);
+ const { rerender, unmount } = render(<MasterySourcePresentation events={[sources, sources]} />);
+ expect(await screen.findByRole("img", { name: "Lecture page 7" })).toHaveAttribute("src", "blob:source-page");
+ expect(apiFetch).toHaveBeenCalledWith(preview, expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ rerender(<MasterySourcePresentation events={[sources]} />);
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ unmount();
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:source-page");
+ });
+
+ it("never fetches private, denied, legacy, external, or non-source rows", () => {
+ const marked = { title: "Page", presentation: "teaching", preview_url: preview };
+ const wrongType = { ...event([marked]), type: "tool_result" } as StreamEvent;
+ render(<MasterySourcePresentation events={[wrongType, event([
+ { ...marked, presentation: undefined }, { ...marked, presentation: "inspect" },
+ { ...marked, presentation: "denied" }, { ...marked, preview_url: "https://tracker.invalid/pixel" },
+ { ...marked, preview_url: "//tracker.invalid/pixel" },
+ { ...marked, preview_url: "/api/knowledge-bases/course/../source-page?page=1" },
+ { ...marked, preview_url: "/api/knowledge-bases/course/source-page/extra?page=1" },
+ ])]} />);
+ expect(apiFetch).not.toHaveBeenCalled();
+ expect(screen.queryByRole("img")).toBeNull();
+ });
+
+ it("shows a failed authenticated fetch without exposing a direct image URL", async () => {
+ apiFetch.mockResolvedValue({ ok: false, status: 403 });
+ render(<MasterySourcePresentation events={[event([{ title: "Page", presentation: "teaching", preview_url: preview }])]} />);
+ await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Failed to load image."));
+ expect(screen.queryByRole("img")).toBeNull();
+ expect(URL.createObjectURL).not.toHaveBeenCalled();
+ });
+});