Skip to content

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

fix(session): ground rendered LaTeX selections (#1676)

XZH3dad78fcbc79
diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.py
index ac6828690..1ea10c547 100644
--- a/deeptutor/services/session/_turn_runtime_shared.py
+++ b/deeptutor/services/session/_turn_runtime_shared.py
@@ -1196,14 +1196,17 @@ def _selection_source_excerpt(
return text
needle = str(selected_text or "").strip()
- selection_start = text.find(needle) if needle else -1
+ selection_start = _selection_start(text, needle) if needle else -1
if selection_start < 0:
return _clip_text(text, limit=limit)
before = max(1_000, (limit - len(needle)) // 2)
start = max(0, selection_start - before)
end = min(len(text), start + limit)
- start = max(0, end - limit)
+ selection_end = min(len(text), selection_start + max(len(needle), 1))
+ if selection_end > end:
+ end = selection_end
+ start = max(0, end - limit)
excerpt = text[start:end]
if start > 0:
excerpt = "[earlier content omitted]\n" + excerpt
@@ -1212,6 +1215,50 @@ def _selection_source_excerpt(
return excerpt
+def _selected_latex_body(selected: str) -> str | None:
+ """Return the body of a complete Markdown math selection, if any."""
+ match = re.fullmatch(r"\$\$(.+?)\$\$|\$(.+?)\$", selected, flags=re.DOTALL)
+ if not match:
+ return None
+ body = " ".join((match.group(1) or match.group(2) or "").split())
+ if not body:
+ return None
+ # Restrict delimiter equivalence to content that plausibly came from a
+ # rendered formula. Ordinary prose selections still require an exact match.
+ if not re.search(r"\\[A-Za-z]+|[_^=+*/<>-]", body):
+ return None
+ return body
+
+
+def _selection_start(source: str, selected: str) -> int:
+ """Find an exact selection, or its equivalent LaTeX body, in source text."""
+ start = source.find(selected) if selected else -1
+ if start >= 0:
+ return start
+ body = _selected_latex_body(selected)
+ if body is None:
+ return -1
+ pattern = r"\s+".join(re.escape(part) for part in body.split(" "))
+ match = re.search(pattern, source, flags=re.DOTALL)
+ return match.start() if match else -1
+
+
+def _latex_selection_is_grounded(source: str, selected: str) -> bool:
+ """Whether selected KaTeX LaTeX has an equivalent body in the source.
+
+ The browser maps a rendered formula back to Markdown ``$...$`` delimiters.
+ The authoritative message may instead contain multiline ``$$`` fences,
+ bracket/parenthesis delimiters, a code span, or bare LaTeX. Comparing the
+ formula body keeps the check content-bound while allowing those display
+ representations to differ.
+ """
+ body = _selected_latex_body(selected)
+ if body is None:
+ return False
+ normalized_source = " ".join(source.split())
+ return body in normalized_source
+
+
def _selection_is_grounded(source_text: str, selected_text: str) -> bool:
"""Whether the claimed selection occurs in its containing message."""
source = str(source_text or "")
@@ -1225,7 +1272,9 @@ def _selection_is_grounded(source_text: str, selected_text: str) -> bool:
# but never accept text that is absent from the authoritative message.
normalized_source = " ".join(source.split())
normalized_selected = " ".join(selected.split())
- return bool(normalized_selected and normalized_selected in normalized_source)
+ if normalized_selected and normalized_selected in normalized_source:
+ return True
+ return _latex_selection_is_grounded(normalized_source, normalized_selected)
async def _resolve_selection_tutor_context(
diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.py
index 3d03d7162..c30cffc1d 100644
--- a/tests/services/session/test_turn_runtime.py
+++ b/tests/services/session/test_turn_runtime.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.services.session._turn_runtime_shared import _selection_source_excerpt
from deeptutor.services.session.turn_runtime import (
_assemble_persisted_answer,
_clip_text,
@@ -373,6 +374,63 @@ class TestSelectionTutorContext:
},
)
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "$$\n{formula}\n$$",
+ "\\[\n{formula}\n\\]",
+ "\\({formula}\\)",
+ "`{formula}`",
+ "{formula}",
+ ],
+ )
+ async def test_resolves_rendered_latex_from_equivalent_source_markup(self, source: str) -> None:
+ formula = r"f(x)=\frac{x^2+1}{\sqrt{1-x}}+\alpha\ln(x)"
+
+ class FakeStore:
+ async def get_messages_for_context(self, _session_id, _leaf_message_id):
+ return [
+ {
+ "id": 42,
+ "role": "assistant",
+ "content": source.format(formula=formula),
+ }
+ ]
+
+ resolved = await _resolve_selection_tutor_context(
+ FakeStore(),
+ {
+ "selected_text": f"$${formula}$$",
+ "parent_session_id": "main-1",
+ "source_message_id": 42,
+ },
+ )
+ assert resolved["selected_text"] == f"$${formula}$$"
+
+ @pytest.mark.asyncio
+ async def test_rejects_rendered_latex_absent_from_authoritative_message(self) -> None:
+ class FakeStore:
+ async def get_messages_for_context(self, _session_id, _leaf_message_id):
+ return [{"id": 42, "role": "assistant", "content": "Trusted source text"}]
+
+ with pytest.raises(ValueError, match="authoritative source message"):
+ await _resolve_selection_tutor_context(
+ FakeStore(),
+ {
+ "selected_text": r"$$\frac{x^2+1}{\sqrt{1-x}}$$",
+ "parent_session_id": "main-1",
+ "source_message_id": 42,
+ },
+ )
+
+ def test_keeps_equivalent_latex_in_bounded_source_excerpt(self) -> None:
+ formula = r"\frac{x^2+1}{\sqrt{1-x}}"
+ source = f"{'x' * 500}\n\\[\n{formula}\n\\]"
+ excerpt = _selection_source_excerpt(source, f"$${formula}$$", limit=100)
+ assert formula in excerpt
+ assert excerpt.startswith("[earlier content omitted]")
+
@pytest.mark.asyncio
async def test_allows_grounded_optimistic_message_fallback(self) -> None:
resolved = await _resolve_selection_tutor_context(