Skip to content

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

feat(reading): add chat section references

Benjamine3d8b05c0d0f
diff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.py
index a85f6d0a9..875689f2a 100644
--- a/deeptutor/capabilities/explore_context/explorer.py
+++ b/deeptutor/capabilities/explore_context/explorer.py
@@ -74,6 +74,7 @@ _KIND_BY_PREFIX: dict[str, tuple[str, str]] = {
"hs-": ("Conversation transcript", "对话记录"),
"nb-": ("Notebook record", "笔记本记录"),
"bk-": ("Book excerpt", "书籍节选"),
+ "rd-": ("Reading excerpt", "阅读材料节选"),
"qb-": ("Question-bank entry", "题库条目"),
"at-": ("Document", "文档"),
}
diff --git a/deeptutor/reading/references.py b/deeptutor/reading/references.py
new file mode 100644
index 000000000..e2b912151
--- /dev/null
+++ b/deeptutor/reading/references.py
@@ -0,0 +1,153 @@
+"""Stable reading-unit references for ordinary chat turns.
+
+The browser sends only material_id plus numeric locators. Text, titles and
+source labels are always re-resolved from the current user's ReadingStore at
+turn start. This keeps a persisted chat reference small, prevents a client from
+smuggling arbitrary text through a trusted source field, and makes deleted
+materials fail closed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Any
+
+from deeptutor.reading.store import MAX_READ_CHARS, ReadingStore
+
+MAX_READING_REFERENCE_MATERIALS = 8
+MAX_READING_REFERENCE_UNITS = 24
+_MATERIAL_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")
+
+
+@dataclass(frozen=True, slots=True)
+class ResolvedReadingSource:
+ """One source-index row resolved from a stored reading unit."""
+
+ source_id: str
+ name: str
+ full_text: str
+
+
+def normalize_reading_references(value: Any) -> list[dict[str, Any]]:
+ """Return a bounded, deduplicated wire representation.
+
+ Malformed rows are ignored rather than partially trusted. Repeated rows for
+ the same material are merged in first-seen order.
+ """
+
+ if not isinstance(value, list):
+ return []
+
+ by_material: dict[str, list[int]] = {}
+ total = 0
+ for raw in value:
+ if not isinstance(raw, dict):
+ continue
+ material_id = str(raw.get("material_id") or "").strip().lower()
+ if not _MATERIAL_ID_RE.fullmatch(material_id):
+ continue
+ locators = raw.get("locators")
+ if not isinstance(locators, list):
+ continue
+ target = by_material.get(material_id)
+ if target is None and len(by_material) >= MAX_READING_REFERENCE_MATERIALS:
+ continue
+ for candidate in locators:
+ locator = _positive_integer(candidate)
+ if locator is None or (target is not None and locator in target):
+ continue
+ if total >= MAX_READING_REFERENCE_UNITS:
+ break
+ if target is None:
+ target = []
+ by_material[material_id] = target
+ target.append(locator)
+ total += 1
+
+ return [
+ {"material_id": material_id, "locators": locators}
+ for material_id, locators in by_material.items()
+ if locators
+ ]
+
+
+def resolve_reading_sources(
+ value: Any,
+ *,
+ store: ReadingStore | None = None,
+) -> list[ResolvedReadingSource]:
+ """Resolve canonical references against the active user's reading store."""
+
+ active_store = store or ReadingStore()
+ resolved: list[ResolvedReadingSource] = []
+ for reference in normalize_reading_references(value):
+ material_id = reference["material_id"]
+ try:
+ manifest = active_store.manifest(material_id)
+ outline = active_store.outline(material_id)
+ unit_refs = active_store.unit_references(material_id)
+ except Exception:
+ # Missing, deleted, or corrupt materials are not readable sources.
+ continue
+
+ headings: dict[int, str] = {}
+ for row in outline:
+ title = row.title.strip()
+ if title:
+ headings.setdefault(row.locator, title)
+ native_titles = {row.locator: row.title.strip() for row in unit_refs if row.title.strip()}
+ material_title = (manifest.title or manifest.filename or material_id).strip()
+
+ for locator in reference["locators"]:
+ if not 1 <= locator <= manifest.unit_count:
+ continue
+ try:
+ body = active_store.unit_text(material_id, locator).strip()
+ except Exception:
+ continue
+ if not body:
+ continue
+ heading = headings.get(locator) or native_titles.get(locator) or ""
+ unit_label = f"{manifest.unit.capitalize()} {locator}"
+ source_name = f"{material_title} — {unit_label}"
+ if heading and heading.casefold() not in source_name.casefold():
+ source_name += f": {heading}"
+ if len(body) > MAX_READ_CHARS:
+ body = (
+ body[:MAX_READ_CHARS].rstrip()
+ + f"\n… [reading unit truncated at {MAX_READ_CHARS:,} characters]"
+ )
+ header = (
+ f"# Reading source: {material_title}\n"
+ f"Source file: {manifest.filename}\n"
+ f"{unit_label}{f': {heading}' if heading else ''}"
+ )
+ resolved.append(
+ ResolvedReadingSource(
+ source_id=f"rd-{material_id}-{locator}",
+ name=source_name,
+ full_text=f"{header}\n\n{body}",
+ )
+ )
+ return resolved
+
+
+def _positive_integer(value: Any) -> int | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value if value > 0 else None
+ if isinstance(value, str) and value.strip().isdigit():
+ parsed = int(value.strip())
+ return parsed if parsed > 0 else None
+ return None
+
+
+__all__ = [
+ "MAX_READING_REFERENCE_MATERIALS",
+ "MAX_READING_REFERENCE_UNITS",
+ "ResolvedReadingSource",
+ "normalize_reading_references",
+ "resolve_reading_sources",
+]
diff --git a/deeptutor/services/session/source_inventory.py b/deeptutor/services/session/source_inventory.py
index 039a2ac69..17a4141e5 100644
--- a/deeptutor/services/session/source_inventory.py
+++ b/deeptutor/services/session/source_inventory.py
@@ -33,6 +33,7 @@ from dataclasses import dataclass, field
import logging
from typing import Any, Sequence
+from deeptutor.reading.references import resolve_reading_sources
from deeptutor.services.session.protocol import SessionStoreProtocol
logger = logging.getLogger(__name__)
@@ -51,7 +52,7 @@ class SourceEntry:
"""One row in the per-turn Attached Sources manifest."""
sid: str
- kind: str # "notebook" | "book" | "history" | "question" | "attachment"
+ kind: str # notebook | book | reading | history | question | attachment
name: str
full_text: str
fresh: bool
@@ -117,6 +118,7 @@ async def build_inventory(
fresh_book_references: Sequence[dict[str, Any]],
fresh_history_session_ids: Sequence[Any],
fresh_question_entry_ids: Sequence[Any],
+ fresh_reading_references: Sequence[dict[str, Any]] = (),
language: str = "en",
) -> SourceInventory:
"""Compose the session-cumulative inventory for one chat turn.
@@ -136,6 +138,7 @@ async def build_inventory(
notebook_records=fresh_notebook_records,
book_context_text=fresh_book_context_text,
book_references=fresh_book_references,
+ reading_references=fresh_reading_references,
)
# History + question entries are async (per-id store fetches), keep them
# in a separate phase so the sync fresh additions don't block.
@@ -239,6 +242,7 @@ def _add_fresh(
notebook_records: Sequence[dict[str, Any]],
book_context_text: str,
book_references: Sequence[dict[str, Any]],
+ reading_references: Sequence[dict[str, Any]],
) -> None:
"""Add the synchronously-available fresh sources (notebook records,
book pages, attachments)."""
@@ -278,6 +282,13 @@ def _add_fresh(
)
)
+ _add_reading_sources(
+ inv,
+ references=reading_references,
+ fresh=True,
+ turn_ordinal=current_turn_ordinal,
+ )
+
for record in attachment_records:
if str(record.get("type", "")).lower() == "image":
continue
@@ -480,6 +491,13 @@ async def _collect_from_user_message(
)
)
+ _add_reading_sources(
+ inv,
+ references=snap.get("readingReferences") or [],
+ fresh=False,
+ turn_ordinal=turn_ordinal,
+ )
+
# History sessions — async, one store fetch per id.
for raw in snap.get("historyReferences") or []:
hs_id = str(raw or "").strip()
@@ -568,6 +586,35 @@ async def _load_lineage(
# ----- Per-type resolvers shared by fresh + historical paths --------------
+def _add_reading_sources(
+ inv: SourceInventory,
+ *,
+ references: Sequence[dict[str, Any]],
+ fresh: bool,
+ turn_ordinal: int,
+) -> None:
+ """Resolve reading locators from the active user's store.
+
+ Persisted chat metadata never supplies source text. Re-resolution here
+ preserves user isolation and makes a deleted material disappear from later
+ turns instead of leaving a stale or spoofable copy in session metadata.
+ """
+
+ for source in resolve_reading_sources(list(references)):
+ if source.source_id in inv and not fresh:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=source.source_id,
+ kind="reading",
+ name=source.name,
+ full_text=source.full_text,
+ fresh=fresh,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+
def _split_book_sections(book_context_text: str) -> list[str]:
"""Split the output of ``build_book_context`` back into per-book
sections. ``build_book_context`` joins sections with ``"\\n\\n---\\n\\n"``;
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 307785f6a..80d633db1 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -250,6 +250,14 @@ def _reading_viewport(value: Any) -> dict[str, Any]:
return viewport
+def _reading_references(value: Any) -> list[dict[str, Any]]:
+ """Normalize reading units explicitly attached to an ordinary chat turn."""
+
+ from deeptutor.reading.references import normalize_reading_references
+
+ return normalize_reading_references(value)
+
+
def _llm_selection_dict(value: Any) -> dict[str, str] | None:
from deeptutor.services.model_selection import LLMSelection
@@ -268,6 +276,7 @@ def _request_snapshot_metadata(
history_references: list[Any],
question_notebook_references: list[Any],
book_references: list[Any],
+ reading_references: Sequence[dict[str, Any]] = (),
persona: str,
memory_references: Sequence[str],
llm_selection: dict[str, str] | None,
@@ -292,6 +301,8 @@ def _request_snapshot_metadata(
snapshot["questionNotebookReferences"] = question_notebook_references
if book_references:
snapshot["bookReferences"] = book_references
+ if reading_references:
+ snapshot["readingReferences"] = list(reading_references)
mastery_path_id = _mastery_path_id(payload.get("mastery_path_id"))
if mastery_path_id:
snapshot["masteryPathId"] = mastery_path_id
@@ -1421,6 +1432,11 @@ class TurnRuntimeManager:
if overrides.get("book_references") is not None
else snapshot.get("bookReferences") or []
),
+ "reading_references": _reading_references(
+ overrides.get("reading_references")
+ if "reading_references" in overrides
+ else snapshot.get("readingReferences")
+ ),
"mastery_path_id": mastery_path_id,
# Recovered from the original turn's snapshot so the regenerate runs
# against the same document. An explicit override wins (the reader
@@ -1744,6 +1760,7 @@ class TurnRuntimeManager:
question_notebook_references = payload.get("question_notebook_references", []) or []
book_context_result = build_book_context(payload.get("book_references", []) or [])
book_references = book_context_result.references
+ reading_references = _reading_references(payload.get("reading_references"))
memory_references = _extract_memory_references(payload)
notebook_context = ""
history_context = ""
@@ -1961,6 +1978,7 @@ class TurnRuntimeManager:
fresh_book_references=book_references,
fresh_history_session_ids=history_references,
fresh_question_entry_ids=question_notebook_references,
+ fresh_reading_references=reading_references,
language=str(payload.get("language", "en") or "en"),
)
source_manifest_text, source_index = render_manifest(inventory)
@@ -2116,6 +2134,7 @@ class TurnRuntimeManager:
history_references=history_references,
question_notebook_references=question_notebook_references,
book_references=book_references,
+ reading_references=reading_references,
persona=active_persona,
memory_references=memory_references,
llm_selection=payload.get("llm_selection"),
@@ -2153,6 +2172,7 @@ class TurnRuntimeManager:
"history_references": history_references,
"question_notebook_references": question_notebook_references,
"book_references": book_references,
+ "reading_references": reading_references,
"mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),
"mastery_path_lease_managed": capability_name == "mastery_path",
# Immersive reading: the open material activates the reading
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 7575c3cc4..1b9a64ce4 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -713,8 +713,8 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
"""Load the full text of an attached Space source by its manifest id.
The chat pipeline auto-enables this tool whenever a turn has any non-image
- attached source (notebook record, book reference, history session,
- question-bank entry, or document attachment). The per-turn full-text
+ attached source (notebook record, book reference, reading unit, history
+ session, question-bank entry, or document attachment). The per-turn full-text
payload is carried in ``context.metadata["source_index"]`` as
``{source_id: str}`` and injected into the tool call by
``_augment_tool_kwargs``. The tool itself stays stateless.
@@ -737,8 +737,8 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
description=(
"The source identifier from the Attached Sources "
"manifest. Begins with one of: nb- (notebook record), "
- "bk- (book reference), hs- (history session), qb- "
- "(question-bank entry), at- (document attachment)."
+ "bk- (book reference), rd- (reading unit), hs- (history "
+ "session), qb- (question-bank entry), at- (document attachment)."
),
),
],
diff --git a/tests/reading/test_references.py b/tests/reading/test_references.py
new file mode 100644
index 000000000..dde6286b2
--- /dev/null
+++ b/tests/reading/test_references.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.reading.references import (
+ MAX_READING_REFERENCE_UNITS,
+ normalize_reading_references,
+ resolve_reading_sources,
+)
+from deeptutor.reading.store import ReadingStore
+
+
+def test_reference_normalization_rejects_paths_and_deduplicates_locators() -> None:
+ assert normalize_reading_references(
+ [
+ {"material_id": "../../etc", "locators": [1]},
+ {"material_id": "ABCDEF0123456789", "locators": [2, 2, "3", 0, True, 1.5]},
+ {"material_id": "abcdef0123456789", "locators": [4]},
+ ]
+ ) == [{"material_id": "abcdef0123456789", "locators": [2, 3, 4]}]
+
+
+def test_reference_normalization_bounds_the_total_unit_count() -> None:
+ refs = normalize_reading_references(
+ [{"material_id": "abcdef0123456789", "locators": list(range(1, 100))}]
+ )
+
+ assert len(refs[0]["locators"]) == MAX_READING_REFERENCE_UNITS
+
+
+def test_empty_rows_do_not_consume_the_material_limit() -> None:
+ empty_rows = [{"material_id": f"{index:016x}", "locators": []} for index in range(20)]
+
+ assert normalize_reading_references(
+ [*empty_rows, {"material_id": "abcdef0123456789", "locators": [1]}]
+ ) == [{"material_id": "abcdef0123456789", "locators": [1]}]
+
+
+def test_references_resolve_from_the_store_not_client_text(tmp_path: Path) -> None:
+ source = tmp_path / "chapter.txt"
+ source.write_text("# Opening\n\nTrusted source text.", encoding="utf-8")
+ store = ReadingStore(tmp_path / "reading")
+ manifest = store.ingest(source)
+
+ resolved = resolve_reading_sources(
+ [
+ {
+ "material_id": manifest.material_id,
+ "locators": [1, 99],
+ "text": "client-supplied text must be ignored",
+ }
+ ],
+ store=store,
+ )
+
+ assert len(resolved) == 1
+ assert resolved[0].source_id == f"rd-{manifest.material_id}-1"
+ assert "Trusted source text." in resolved[0].full_text
+ assert "client-supplied" not in resolved[0].full_text
+ assert manifest.filename in resolved[0].full_text
+
+
+def test_missing_materials_are_safely_ignored(tmp_path: Path) -> None:
+ assert (
+ resolve_reading_sources(
+ [{"material_id": "abcdef0123456789", "locators": [1]}],
+ store=ReadingStore(tmp_path / "reading"),
+ )
+ == []
+ )
diff --git a/tests/reading/test_turn_wiring.py b/tests/reading/test_turn_wiring.py
index fd828368a..bd8d448c8 100644
--- a/tests/reading/test_turn_wiring.py
+++ b/tests/reading/test_turn_wiring.py
@@ -14,6 +14,7 @@ import pytest
from deeptutor.services.session.turn_runtime import (
READING_SELECTION_MAX_CHARS,
_reading_material_id,
+ _reading_references,
_reading_viewport,
_request_snapshot_metadata,
)
@@ -87,6 +88,15 @@ def test_selection_is_bounded_because_it_enters_the_prompt() -> None:
assert len(viewport["selection"]) == READING_SELECTION_MAX_CHARS
+def test_explicit_reading_references_are_normalized_at_the_turn_boundary() -> None:
+ assert _reading_references(
+ [
+ {"material_id": "ABCDEF0123456789", "locators": [2, 2, "3"]},
+ {"material_id": "../../etc", "locators": [1]},
+ ]
+ ) == [{"material_id": "abcdef0123456789", "locators": [2, 3]}]
+
+
# ---------------------------------------------------------------------------
# snapshot persistence
# ---------------------------------------------------------------------------
@@ -123,3 +133,25 @@ def test_a_plain_chat_turn_carries_no_reading_key() -> None:
def test_a_bogus_id_is_not_persisted() -> None:
assert "readingMaterialId" not in _snapshot({"reading_material_id": "../../etc"})
+
+
+def test_explicit_reading_references_are_persisted_for_retry() -> None:
+ snapshot = _request_snapshot_metadata(
+ content="hi",
+ capability="chat",
+ payload={},
+ attachments=[],
+ config={},
+ notebook_references=[],
+ history_references=[],
+ question_notebook_references=[],
+ book_references=[],
+ reading_references=[{"material_id": "abcdef0123456789", "locators": [1, 2]}],
+ persona="",
+ memory_references=[],
+ llm_selection=None,
+ )["request_snapshot"]
+
+ assert snapshot["readingReferences"] == [
+ {"material_id": "abcdef0123456789", "locators": [1, 2]}
+ ]
diff --git a/tests/services/session/test_source_inventory.py b/tests/services/session/test_source_inventory.py
index 136a4927b..c7ec96605 100644
--- a/tests/services/session/test_source_inventory.py
+++ b/tests/services/session/test_source_inventory.py
@@ -6,6 +6,7 @@ from typing import Any
import pytest
+from deeptutor.reading.references import ResolvedReadingSource
from deeptutor.services.session.source_inventory import (
SourceEntry,
SourceInventory,
@@ -350,6 +351,104 @@ async def test_build_inventory_fresh_shadows_historical_on_same_sid() -> None:
assert inv.entries[0].full_text == "fresh body"
+async def test_build_inventory_adds_server_resolved_reading_units(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from deeptutor.services.session import source_inventory
+
+ seen: list[dict[str, Any]] = []
+
+ def resolve(refs: list[dict[str, Any]]) -> list[ResolvedReadingSource]:
+ seen.extend(refs)
+ return [
+ ResolvedReadingSource(
+ source_id="rd-abcdef0123456789-2",
+ name="Source book — Chapter 2",
+ full_text="trusted chapter text",
+ )
+ ]
+
+ monkeypatch.setattr(source_inventory, "resolve_reading_sources", resolve)
+ inv = await build_inventory(
+ FakeStore(),
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=1,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ fresh_reading_references=[{"material_id": "abcdef0123456789", "locators": [2]}],
+ )
+
+ assert seen == [{"material_id": "abcdef0123456789", "locators": [2]}]
+ assert inv.entries[0].sid == "rd-abcdef0123456789-2"
+ assert inv.entries[0].kind == "reading"
+ assert inv.entries[0].fresh is True
+
+
+async def test_historical_reading_units_are_re_resolved_from_snapshot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from deeptutor.services.session import source_inventory
+
+ monkeypatch.setattr(
+ source_inventory,
+ "resolve_reading_sources",
+ lambda refs: (
+ [
+ ResolvedReadingSource(
+ source_id="rd-abcdef0123456789-1",
+ name="Source book — Chapter 1",
+ full_text="current stored chapter text",
+ )
+ ]
+ if refs
+ else []
+ ),
+ )
+ store = FakeStore(
+ messages=[
+ {
+ "id": 1,
+ "role": "user",
+ "parent_message_id": None,
+ "attachments": [],
+ "metadata": {
+ "request_snapshot": {
+ "readingReferences": [
+ {
+ "material_id": "abcdef0123456789",
+ "locators": [1],
+ }
+ ]
+ }
+ },
+ }
+ ]
+ )
+
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=2,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+
+ assert inv.entries[0].fresh is False
+ assert inv.entries[0].full_text == "current stored chapter text"
+
+
# ---------------------------------------------------------------------------
# serialize_referenced_transcript — identity framing (the "floor" fix)
# ---------------------------------------------------------------------------
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index bb6ccfc2e..f4e5a4621 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -123,6 +123,10 @@ import {
selectedBooksToPayload,
type SelectedBookReference,
} from "@/lib/book-references";
+import {
+ selectedReadingsToPayload,
+ type SelectedReadingReference,
+} from "@/lib/reading-references";
import {
normalizeSelectedText,
type SelectionTutorContext,
@@ -161,6 +165,12 @@ const BookReferencePicker = dynamic(
ssr: false,
},
);
+const ReadingReferencePicker = dynamic(
+ () => import("@/components/chat/ReadingReferencePicker"),
+ {
+ ssr: false,
+ },
+);
const SaveToNotebookModal = dynamic(
() => import("@/components/notebook/SaveToNotebookModal"),
{
@@ -613,6 +623,7 @@ export default function ChatPage() {
const [showSaveModal, setShowSaveModal] = useState(false);
const [showNotebookPicker, setShowNotebookPicker] = useState(false);
const [showBookPicker, setShowBookPicker] = useState(false);
+ const [showReadingPicker, setShowReadingPicker] = useState(false);
const [showHistoryPicker, setShowHistoryPicker] = useState(false);
const [showAgentsPicker, setShowAgentsPicker] = useState(false);
const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);
@@ -628,6 +639,9 @@ export default function ChatPage() {
const [selectedBookReferences, setSelectedBookReferences] = useState<
SelectedBookReference[]
>([]);
+ const [selectedReadingReferences, setSelectedReadingReferences] = useState<
+ SelectedReadingReference[]
+ >([]);
const [selectedHistorySessions, setSelectedHistorySessions] = useState<
SelectedHistorySession[]
>([]);
@@ -963,6 +977,10 @@ export default function ChatPage() {
() => selectedBooksToPayload(selectedBookReferences),
[selectedBookReferences],
);
+ const readingReferencesPayload = useMemo(
+ () => selectedReadingsToPayload(selectedReadingReferences),
+ [selectedReadingReferences],
+ );
// Chat-history and imported-agent references are both just session ids and
// share one backend field. Merge + de-dupe them here.
const historyReferencesPayload = useMemo(
@@ -1703,7 +1721,7 @@ export default function ChatPage() {
const messageElementForNode = (node: Node | null): HTMLElement | null => {
const element =
- node instanceof HTMLElement ? node : node?.parentElement ?? null;
+ node instanceof HTMLElement ? node : (node?.parentElement ?? null);
return element?.closest<HTMLElement>("[data-chat-message-id]") ?? null;
};
const anchorMessage = messageElementForNode(selection.anchorNode);
@@ -1849,6 +1867,7 @@ export default function ChatPage() {
(!content &&
!attachments.length &&
!selectedBookReferences.length &&
+ !selectedReadingReferences.length &&
!selectedNotebookRecords.length &&
!selectedHistorySessions.length &&
!selectedQuestionEntries.length &&
@@ -1902,6 +1921,7 @@ export default function ChatPage() {
content ||
(selectedNotebookRecords.length ||
selectedBookReferences.length ||
+ selectedReadingReferences.length ||
selectedHistorySessions.length ||
selectedAgentSessions.length ||
selectedQuestionEntries.length ||
@@ -1920,7 +1940,10 @@ export default function ChatPage() {
config,
notebookReferencesPayload,
historyReferencesPayload,
- { bookReferences: bookReferencesPayload },
+ {
+ bookReferences: bookReferencesPayload,
+ readingReferences: readingReferencesPayload,
+ },
questionNotebookReferencesPayload,
undefined,
memoryPayload,
@@ -1929,6 +1952,7 @@ export default function ChatPage() {
shouldAutoScrollRef.current = true;
setAttachments([]);
setSelectedBookReferences([]);
+ setSelectedReadingReferences([]);
setSelectedNotebookRecords([]);
setSelectedHistorySessions([]);
setSelectedAgentSessions([]);
@@ -1938,6 +1962,7 @@ export default function ChatPage() {
[
attachments,
bookReferencesPayload,
+ readingReferencesPayload,
historyReferencesPayload,
isQuizMode,
isResearchMode,
@@ -1954,6 +1979,7 @@ export default function ChatPage() {
selectedAgentSessions.length,
selectedMemoryFiles.length,
selectedBookReferences.length,
+ selectedReadingReferences.length,
selectedNotebookRecords.length,
selectedQuestionEntries.length,
sendMessage,
@@ -2000,6 +2026,7 @@ export default function ChatPage() {
persistUserMessage: false,
requestSnapshotOverride,
bookReferences: originalSnapshot?.bookReferences,
+ readingReferences: originalSnapshot?.readingReferences,
},
originalSnapshot?.questionNotebookReferences,
originalSnapshot?.persona,
@@ -2078,6 +2105,9 @@ export default function ChatPage() {
const handleSelectBookPicker = useCallback(() => {
setShowBookPicker(true);
}, []);
+ const handleSelectReadingPicker = useCallback(() => {
+ setShowReadingPicker(true);
+ }, []);
const handleSelectHistoryPicker = useCallback(() => {
setShowHistoryPicker(true);
}, []);
@@ -2114,6 +2144,11 @@ export default function ChatPage() {
prev.filter((record) => record.bookId !== bookId),
);
}, []);
+ const handleRemoveReadingReference = useCallback((materialId: string) => {
+ setSelectedReadingReferences((previous) =>
+ previous.filter((record) => record.materialId !== materialId),
+ );
+ }, []);
const handleRemoveQuestion = useCallback((entryId: number) => {
setSelectedQuestionEntries((prev) =>
prev.filter((entry) => entry.id !== entryId),
@@ -2137,12 +2172,21 @@ export default function ChatPage() {
const handleCloseBookPicker = useCallback(() => {
setShowBookPicker(false);
}, []);
+ const handleCloseReadingPicker = useCallback(() => {
+ setShowReadingPicker(false);
+ }, []);
const handleApplyBookReferences = useCallback(
(references: SelectedBookReference[]) => {
setSelectedBookReferences(references);
},
[],
);
+ const handleApplyReadingReferences = useCallback(
+ (references: SelectedReadingReference[]) => {
+ setSelectedReadingReferences(references);
+ },
+ [],
+ );
const handleApplyNotebookRecords = useCallback(
(records: SelectedRecord[]) => {
setSelectedNotebookRecords(records);
@@ -2462,6 +2506,7 @@ export default function ChatPage() {
}
contextBudget={contextBudget}
selectedBookReferences={selectedBookReferences}
+ selectedReadingReferences={selectedReadingReferences}
selectedNotebookRecords={selectedNotebookRecords}
selectedHistorySessions={selectedHistorySessions}
selectedAgentSessions={selectedAgentSessions}
@@ -2482,6 +2527,7 @@ export default function ChatPage() {
onSelectLLM={setLLMSelection}
onSelectNotebookPicker={handleSelectNotebookPicker}
onSelectBookPicker={handleSelectBookPicker}
+ onSelectReadingPicker={handleSelectReadingPicker}
onSelectHistoryPicker={handleSelectHistoryPicker}
onSelectAgentsPicker={handleSelectAgentsPicker}
onSelectQuestionBankPicker={handleSelectQuestionBankPicker}
@@ -2500,6 +2546,7 @@ export default function ChatPage() {
onRemoveHistory={handleRemoveHistory}
onRemoveAgent={handleRemoveAgent}
onRemoveBookReference={handleRemoveBookReference}
+ onRemoveReadingReference={handleRemoveReadingReference}
onRemoveNotebook={handleRemoveNotebook}
onRemoveQuestion={handleRemoveQuestion}
onDragEnter={handleDragEnter}
@@ -2544,6 +2591,12 @@ export default function ChatPage() {
onClose={handleCloseBookPicker}
onApply={handleApplyBookReferences}
/>
+ <ReadingReferencePicker
+ open={showReadingPicker}
+ initialReferences={selectedReadingReferences}
+ onClose={handleCloseReadingPicker}
+ onApply={handleApplyReadingReferences}
+ />
<HistorySessionPicker
open={showHistoryPicker}
onClose={handleCloseHistoryPicker}
diff --git a/web/components/chat/ReadingReferencePicker.tsx b/web/components/chat/ReadingReferencePicker.tsx
new file mode 100644
index 000000000..549f17527
--- /dev/null
+++ b/web/components/chat/ReadingReferencePicker.tsx
@@ -0,0 +1,476 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { BookMarked, Check, ChevronRight, Loader2, Search } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import PickerHeader from "@/components/common/PickerHeader";
+import PickerShell from "@/components/common/PickerShell";
+import {
+ getMaterial,
+ listMaterials,
+ type MaterialDetail,
+ type MaterialInfo,
+} from "@/lib/reading-api";
+import {
+ MAX_READING_REFERENCE_MATERIALS,
+ MAX_READING_REFERENCE_UNITS,
+ countSelectedReadingUnits,
+ type SelectedReadingReference,
+ type SelectedReadingUnit,
+} from "@/lib/reading-references";
+
+interface ReadingReferencePickerProps {
+ open: boolean;
+ initialReferences: SelectedReadingReference[];
+ onClose: () => void;
+ onApply: (references: SelectedReadingReference[]) => void;
+}
+
+function unitKey(materialId: string, locator: number): string {
+ return `${materialId}:${locator}`;
+}
+
+function unitTitle(
+ detail: MaterialDetail,
+ locator: number,
+ fallback: string,
+): string {
+ const outlineTitle = detail.outline.find(
+ (row) => row.locator === locator && row.title.trim(),
+ )?.title;
+ const nativeTitle = detail.unit_refs.find(
+ (row) => row.locator === locator && row.title.trim(),
+ )?.title;
+ return outlineTitle?.trim() || nativeTitle?.trim() || fallback;
+}
+
+export default function ReadingReferencePicker({
+ open,
+ initialReferences,
+ onClose,
+ onApply,
+}: ReadingReferencePickerProps) {
+ const { t } = useTranslation();
+ const [materials, setMaterials] = useState<MaterialInfo[]>([]);
+ const [details, setDetails] = useState<Record<string, MaterialDetail>>({});
+ const [activeMaterialId, setActiveMaterialId] = useState<string | null>(null);
+ const [selected, setSelected] = useState<SelectedReadingReference[]>([]);
+ const [query, setQuery] = useState("");
+ const [loadingMaterials, setLoadingMaterials] = useState(false);
+ const [loadingDetail, setLoadingDetail] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ let mounted = true;
+ // Re-seed the draft on every open; Cancel must not mutate the composer.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setSelected(initialReferences);
+ setQuery("");
+ setError(null);
+ setLoadingMaterials(true);
+ void listMaterials()
+ .then((rows) => {
+ if (!mounted) return;
+ setMaterials(rows);
+ setActiveMaterialId((current) =>
+ rows.some((row) => row.material_id === current)
+ ? current
+ : (rows[0]?.material_id ?? null),
+ );
+ })
+ .catch((cause: unknown) => {
+ if (!mounted) return;
+ setMaterials([]);
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : t("Unable to load reading materials."),
+ );
+ })
+ .finally(() => {
+ if (mounted) setLoadingMaterials(false);
+ });
+ return () => {
+ mounted = false;
+ };
+ }, [initialReferences, open, t]);
+
+ useEffect(() => {
+ if (!open || !activeMaterialId || details[activeMaterialId]) return;
+ let mounted = true;
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setLoadingDetail(true);
+ setError(null);
+ void getMaterial(activeMaterialId)
+ .then((detail) => {
+ if (!mounted) return;
+ setDetails((previous) => ({
+ ...previous,
+ [activeMaterialId]: detail,
+ }));
+ })
+ .catch((cause: unknown) => {
+ if (!mounted) return;
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : t("Unable to load reading sections."),
+ );
+ })
+ .finally(() => {
+ if (mounted) setLoadingDetail(false);
+ });
+ return () => {
+ mounted = false;
+ };
+ }, [activeMaterialId, details, open, t]);
+
+ const filteredMaterials = useMemo(() => {
+ const keyword = query.trim().toLocaleLowerCase();
+ if (!keyword) return materials;
+ return materials.filter((material) =>
+ `${material.title} ${material.filename}`
+ .toLocaleLowerCase()
+ .includes(keyword),
+ );
+ }, [materials, query]);
+
+ const activeMaterial =
+ materials.find((material) => material.material_id === activeMaterialId) ??
+ null;
+ const activeDetail = activeMaterialId
+ ? (details[activeMaterialId] ?? null)
+ : null;
+ const selectedCount = countSelectedReadingUnits(selected);
+ const selectedKeys = useMemo(
+ () =>
+ new Set(
+ selected.flatMap((reference) =>
+ reference.units.map((unit) =>
+ unitKey(reference.materialId, unit.locator),
+ ),
+ ),
+ ),
+ [selected],
+ );
+ const activeUnits = useMemo(() => {
+ if (!activeDetail) return [];
+ return Array.from({ length: activeDetail.unit_count }, (_, index) => {
+ const locator = index + 1;
+ const fallback = t("{{unit}} {{locator}}", {
+ unit: t(activeDetail.unit),
+ locator,
+ });
+ return {
+ locator,
+ title: unitTitle(activeDetail, locator, fallback),
+ } satisfies SelectedReadingUnit;
+ });
+ }, [activeDetail, t]);
+ const allActiveSelected =
+ Boolean(activeMaterial) &&
+ activeUnits.length > 0 &&
+ activeUnits.every((unit) =>
+ selectedKeys.has(unitKey(activeMaterial!.material_id, unit.locator)),
+ );
+
+ const addUnits = (material: MaterialInfo, units: SelectedReadingUnit[]) => {
+ const existing = selected.find(
+ (reference) => reference.materialId === material.material_id,
+ );
+ if (!existing && selected.length >= MAX_READING_REFERENCE_MATERIALS) {
+ setError(
+ t("You can reference up to {{count}} reading materials at once.", {
+ count: MAX_READING_REFERENCE_MATERIALS,
+ }),
+ );
+ return;
+ }
+ const existingLocators = new Set(
+ existing?.units.map((unit) => unit.locator) ?? [],
+ );
+ const pending = units.filter((unit) => !existingLocators.has(unit.locator));
+ const remaining = MAX_READING_REFERENCE_UNITS - selectedCount;
+ const additions = pending.slice(0, Math.max(0, remaining));
+ if (!additions.length) {
+ if (pending.length) {
+ setError(
+ t("You can reference up to {{count}} reading sections at once.", {
+ count: MAX_READING_REFERENCE_UNITS,
+ }),
+ );
+ }
+ return;
+ }
+ if (additions.length < pending.length) {
+ setError(
+ t("Only the first {{count}} available sections were selected.", {
+ count: additions.length,
+ }),
+ );
+ } else {
+ setError(null);
+ }
+ if (existing) {
+ setSelected((previous) =>
+ previous.map((reference) =>
+ reference.materialId === material.material_id
+ ? { ...reference, units: [...reference.units, ...additions] }
+ : reference,
+ ),
+ );
+ return;
+ }
+ setSelected((previous) => [
+ ...previous,
+ {
+ materialId: material.material_id,
+ materialTitle: material.title || material.filename,
+ unit: material.unit,
+ units: additions,
+ },
+ ]);
+ };
+
+ const removeUnits = (materialId: string, locators: Set<number>) => {
+ setSelected((previous) =>
+ previous
+ .map((reference) =>
+ reference.materialId === materialId
+ ? {
+ ...reference,
+ units: reference.units.filter(
+ (unit) => !locators.has(unit.locator),
+ ),
+ }
+ : reference,
+ )
+ .filter((reference) => reference.units.length > 0),
+ );
+ setError(null);
+ };
+
+ const toggleUnit = (unit: SelectedReadingUnit) => {
+ if (!activeMaterial) return;
+ if (selectedKeys.has(unitKey(activeMaterial.material_id, unit.locator))) {
+ removeUnits(activeMaterial.material_id, new Set([unit.locator]));
+ return;
+ }
+ addUnits(activeMaterial, [unit]);
+ };
+
+ const toggleAllActive = () => {
+ if (!activeMaterial || !activeUnits.length) return;
+ if (allActiveSelected) {
+ removeUnits(
+ activeMaterial.material_id,
+ new Set(activeUnits.map((unit) => unit.locator)),
+ );
+ return;
+ }
+ addUnits(activeMaterial, activeUnits);
+ };
+
+ return (
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="reading-reference-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
+ <div className="surface-card flex h-[78vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
+ <PickerHeader
+ icon={BookMarked}
+ titleId="reading-reference-picker-title"
+ title={t("Select Reading Sections")}
+ subtitle={t(
+ "Choose sections from imported reading materials to ground the next answer.",
+ )}
+ onClose={onClose}
+ />
+
+ {error ? (
+ <div
+ role="alert"
+ className="border-b border-amber-500/20 bg-amber-500/8 px-5 py-2.5 text-sm text-amber-700 dark:text-amber-300"
+ >
+ {error}
+ </div>
+ ) : null}
+
+ <div className="grid min-h-0 flex-1 grid-cols-1 md:grid-cols-[300px_minmax(0,1fr)]">
+ <aside className="flex min-h-0 flex-col border-b border-[var(--border)] bg-[var(--background)]/40 p-4 md:border-b-0 md:border-r">
+ <div className="relative mb-3">
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("Search reading materials")}
+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"
+ />
+ </div>
+ <div className="min-h-[130px] flex-1 overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)] md:min-h-0">
+ {loadingMaterials ? (
+ <div className="flex h-full min-h-[140px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : filteredMaterials.length ? (
+ <div className="divide-y divide-[var(--border)]">
+ {filteredMaterials.map((material) => {
+ const active = material.material_id === activeMaterialId;
+ const count =
+ selected.find(
+ (reference) =>
+ reference.materialId === material.material_id,
+ )?.units.length ?? 0;
+ return (
+ <button
+ type="button"
+ key={material.material_id}
+ onClick={() =>
+ setActiveMaterialId(material.material_id)
+ }
+ className={`flex w-full items-center gap-3 px-3 py-3 text-left transition-colors ${
+ active
+ ? "bg-[var(--primary)]/8"
+ : "hover:bg-[var(--muted)]/40"
+ }`}
+ >
+ <BookMarked className="h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium text-[var(--foreground)]">
+ {material.title || material.filename}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
+ {material.unit_count} {t("sections")}
+ </span>
+ </span>
+ {count > 0 ? (
+ <span className="rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">
+ {count}
+ </span>
+ ) : null}
+ <ChevronRight className="h-4 w-4 text-[var(--muted-foreground)]" />
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No reading materials found.")}
+ </div>
+ )}
+ </div>
+ </aside>
+
+ <section className="min-h-0 overflow-y-auto p-5">
+ {!activeMaterial ? (
+ <div className="flex h-full items-center justify-center text-sm text-[var(--muted-foreground)]">
+ {t("Select a reading material to view sections.")}
+ </div>
+ ) : loadingDetail && !activeDetail ? (
+ <div className="flex h-full items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : activeDetail ? (
+ <div className="space-y-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h3 className="truncate text-base font-semibold text-[var(--foreground)]">
+ {activeMaterial.title || activeMaterial.filename}
+ </h3>
+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">
+ {activeMaterial.filename}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={toggleAllActive}
+ className="shrink-0 rounded-xl border border-[var(--border)] px-3 py-2 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"
+ >
+ {allActiveSelected ? t("Clear material") : t("Select all")}
+ </button>
+ </div>
+ <div className="divide-y divide-[var(--border)] overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--background)]/35">
+ {activeUnits.map((unit) => {
+ const checked = selectedKeys.has(
+ unitKey(activeMaterial.material_id, unit.locator),
+ );
+ return (
+ <button
+ type="button"
+ key={unit.locator}
+ onClick={() => toggleUnit(unit)}
+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors ${
+ checked
+ ? "bg-[var(--primary)]/8"
+ : "hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ <span
+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${
+ checked
+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "border-[var(--border)] text-transparent"
+ }`}
+ >
+ <Check size={12} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[13px] font-medium text-[var(--foreground)]">
+ {unit.title}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-[var(--muted-foreground)]">
+ {t("{{unit}} {{locator}}", {
+ unit: t(activeMaterial.unit),
+ locator: unit.locator,
+ })}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ) : null}
+ </section>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 border-t border-[var(--border)] px-5 py-4">
+ <div className="text-sm text-[var(--muted-foreground)]">
+ {selectedCount
+ ? t("{{count}} reading sections selected", {
+ count: selectedCount,
+ })
+ : t("No reading sections selected")}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ setSelected([]);
+ setError(null);
+ }}
+ className="rounded-xl border border-[var(--border)] px-4 py-2 text-sm font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {t("Clear")}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onApply(selected);
+ onClose();
+ }}
+ className="rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
+ >
+ {t("Apply")}
+ </button>
+ </div>
+ </div>
+ </div>
+ </PickerShell>
+ );
+}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 8bbcc5af3..a9a65b1d1 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -12,6 +12,7 @@ import {
import { AnimatePresence, motion } from "framer-motion";
import {
ArrowUp,
+ BookMarked,
BookOpen,
Bot,
Brain,
@@ -45,6 +46,7 @@ import type { LLMOption } from "@/lib/llm-options";
import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";
import type { SpaceMemoryFile } from "@/lib/space-items";
import type { SelectedBookReference } from "@/lib/book-references";
+import type { SelectedReadingReference } from "@/lib/reading-references";
import AgentSelector from "./AgentSelector";
import ContextBudgetChip, { type ContextBudget } from "./ContextBudgetChip";
import KnowledgeSelector from "./KnowledgeSelector";
@@ -57,6 +59,7 @@ type SpaceSelectionCounts = {
chatHistory: number;
myAgents: number;
books: number;
+ reading: number;
notebooks: number;
questionBank: number;
persona: number;
@@ -200,6 +203,7 @@ export default memo(function ChatComposer({
contextBudget = null,
selectedNotebookRecords,
selectedBookReferences,
+ selectedReadingReferences = [],
selectedHistorySessions,
selectedAgentSessions,
selectedQuestionEntries,
@@ -220,6 +224,7 @@ export default memo(function ChatComposer({
onSelectLLM,
onSelectNotebookPicker,
onSelectBookPicker,
+ onSelectReadingPicker,
onSelectHistoryPicker,
onSelectAgentsPicker,
onSelectQuestionBankPicker,
@@ -238,6 +243,7 @@ export default memo(function ChatComposer({
onRemoveHistory,
onRemoveAgent,
onRemoveBookReference,
+ onRemoveReadingReference,
onRemoveNotebook,
onRemoveQuestion,
onDragEnter,
@@ -287,6 +293,7 @@ export default memo(function ChatComposer({
contextBudget?: ContextBudget | null;
selectedNotebookRecords: SelectedRecord[];
selectedBookReferences: SelectedBookReference[];
+ selectedReadingReferences?: SelectedReadingReference[];
selectedHistorySessions: SelectedHistorySession[];
selectedAgentSessions: SelectedHistorySession[];
selectedQuestionEntries: SelectedQuestionEntry[];
@@ -322,6 +329,7 @@ export default memo(function ChatComposer({
onSelectLLM: (selection: LLMSelection | null) => void;
onSelectNotebookPicker: () => void;
onSelectBookPicker: () => void;
+ onSelectReadingPicker?: () => void;
onSelectHistoryPicker: () => void;
onSelectAgentsPicker: () => void;
onSelectQuestionBankPicker: () => void;
@@ -347,6 +355,7 @@ export default memo(function ChatComposer({
onRemoveHistory: (sessionId: string) => void;
onRemoveAgent: (sessionId: string) => void;
onRemoveBookReference: (bookId: string) => void;
+ onRemoveReadingReference?: (materialId: string) => void;
onRemoveNotebook: (notebookId: string) => void;
onRemoveQuestion: (entryId: number) => void;
onDragEnter: (event: React.DragEvent) => void;
@@ -474,7 +483,7 @@ export default memo(function ChatComposer({
setMoreCapsOpen(false);
onSelectCapability(value);
},
- [onSelectCapability],
+ [onSelectCapability, setMoreCapsOpen],
);
// Functional-update form keeps `handleInputChange` identity stable across
@@ -501,6 +510,7 @@ export default memo(function ChatComposer({
const hasReferences =
!!attachments.length ||
!!selectedBookReferences.length ||
+ !!selectedReadingReferences.length ||
!!selectedNotebookRecords.length ||
!!selectedHistorySessions.length ||
!!selectedAgentSessions.length ||
@@ -542,6 +552,10 @@ export default memo(function ChatComposer({
(total, ref) => total + ref.pages.length,
0,
),
+ reading: selectedReadingReferences.reduce(
+ (total, reference) => total + reference.units.length,
+ 0,
+ ),
notebooks: selectedNotebookRecords.length,
questionBank: selectedQuestionEntries.length,
persona: selectedPersona ? 1 : 0,
@@ -566,51 +580,50 @@ export default memo(function ChatComposer({
// toolbar KnowledgeSelector chip instead — same lifecycle class as
// the persona selector.
const contextTreeItems: ContextTreeItem[] = [
- ...selectedBookReferences.map(
- (book): ContextTreeItem => ({
- key: `book-${book.bookId}`,
- icon: BookOpen,
- kind: t("Book"),
- label: `${book.bookTitle} (${book.pages.length})`,
- onRemove: () => onRemoveBookReference(book.bookId),
- }),
- ),
- ...notebookReferenceGroups.map(
- (group): ContextTreeItem => ({
- key: `nb-${group.notebookId}`,
- icon: BookOpen,
- kind: t("Notebook"),
- label: `${group.notebookName} (${group.count})`,
- onRemove: () => onRemoveNotebook(group.notebookId),
- }),
- ),
- ...selectedHistorySessions.map(
- (session): ContextTreeItem => ({
- key: `hist-${session.sessionId}`,
- icon: MessageSquare,
- kind: t("Chat History"),
- label: session.title,
- onRemove: () => onRemoveHistory(session.sessionId),
- }),
- ),
- ...selectedAgentSessions.map(
- (session): ContextTreeItem => ({
- key: `agent-${session.sessionId}`,
- icon: Bot,
- kind: t("My Agents"),
- label: session.title,
- onRemove: () => onRemoveAgent(session.sessionId),
- }),
- ),
- ...selectedQuestionEntries.map(
- (entry): ContextTreeItem => ({
- key: `q-${entry.id}`,
- icon: ClipboardList,
- kind: t("Question Bank"),
- label: entry.question,
- onRemove: () => onRemoveQuestion(entry.id),
- }),
- ),
+ ...selectedBookReferences.map((book): ContextTreeItem => ({
+ key: `book-${book.bookId}`,
+ icon: BookOpen,
+ kind: t("Book"),
+ label: `${book.bookTitle} (${book.pages.length})`,
+ onRemove: () => onRemoveBookReference(book.bookId),
+ })),
+ ...selectedReadingReferences.map((material): ContextTreeItem => ({
+ key: `reading-${material.materialId}`,
+ icon: BookMarked,
+ kind: t("Reading"),
+ label: `${material.materialTitle} (${material.units.length})`,
+ onRemove: onRemoveReadingReference
+ ? () => onRemoveReadingReference(material.materialId)
+ : undefined,
+ })),
+ ...notebookReferenceGroups.map((group): ContextTreeItem => ({
+ key: `nb-${group.notebookId}`,
+ icon: BookOpen,
+ kind: t("Notebook"),
+ label: `${group.notebookName} (${group.count})`,
+ onRemove: () => onRemoveNotebook(group.notebookId),
+ })),
+ ...selectedHistorySessions.map((session): ContextTreeItem => ({
+ key: `hist-${session.sessionId}`,
+ icon: MessageSquare,
+ kind: t("Chat History"),
+ label: session.title,
+ onRemove: () => onRemoveHistory(session.sessionId),
+ })),
+ ...selectedAgentSessions.map((session): ContextTreeItem => ({
+ key: `agent-${session.sessionId}`,
+ icon: Bot,
+ kind: t("My Agents"),
+ label: session.title,
+ onRemove: () => onRemoveAgent(session.sessionId),
+ })),
+ ...selectedQuestionEntries.map((entry): ContextTreeItem => ({
+ key: `q-${entry.id}`,
+ icon: ClipboardList,
+ kind: t("Question Bank"),
+ label: entry.question,
+ onRemove: () => onRemoveQuestion(entry.id),
+ })),
...(selectedPersona
? [
{
@@ -622,15 +635,13 @@ export default memo(function ChatComposer({
} satisfies ContextTreeItem,
]
: []),
- ...selectedMemoryFiles.map(
- (file): ContextTreeItem => ({
- key: `mem-${file}`,
- icon: Brain,
- kind: t("Memory"),
- label: file === "summary" ? t("Summary") : t("Profile"),
- onRemove: () => onToggleMemoryFile(file),
- }),
- ),
+ ...selectedMemoryFiles.map((file): ContextTreeItem => ({
+ key: `mem-${file}`,
+ icon: Brain,
+ kind: t("Memory"),
+ label: file === "summary" ? t("Summary") : t("Profile"),
+ onRemove: () => onToggleMemoryFile(file),
+ })),
];
const handleManualSend = useCallback(() => {
@@ -752,6 +763,7 @@ export default memo(function ChatComposer({
agentsAvailable={agentsAvailable}
onSelectNotebookPicker={onSelectNotebookPicker}
onSelectBookPicker={onSelectBookPicker}
+ onSelectReadingPicker={onSelectReadingPicker}
onSelectHistoryPicker={onSelectHistoryPicker}
onSelectAgentsPicker={onSelectAgentsPicker}
onSelectQuestionBankPicker={onSelectQuestionBankPicker}
@@ -1033,6 +1045,7 @@ export default memo(function ChatComposer({
knowledgeAvailable={false}
personaAvailable={!onPersonaSelectionChange}
agentsAvailable={agentsAvailable}
+ readingAvailable={Boolean(onSelectReadingPicker)}
onSelectItem={(key) => {
onSetSpaceMenuOpen(false);
if (key === "attach") handlePickFiles();
@@ -1040,6 +1053,7 @@ export default memo(function ChatComposer({
onSelectHistoryPicker();
else if (key === "my_agents") onSelectAgentsPicker();
else if (key === "books") onSelectBookPicker();
+ else if (key === "reading") onSelectReadingPicker?.();
else if (key === "notebooks")
onSelectNotebookPicker();
else if (key === "question_bank")
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index f27b0c811..023f26d0b 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -3,6 +3,7 @@
import dynamic from "next/dynamic";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
+ BookMarked,
BookOpen,
Bot,
Brain,
@@ -1004,45 +1005,43 @@ const UserMessage = memo(function UserMessage({
label: name,
};
}),
- ...(snap?.bookReferences ?? []).map(
- (ref): ContextTreeItem => ({
- key: `book-${ref.book_id}`,
- icon: BookOpen,
- kind: t("Book"),
- label: `${ref.page_ids.length} ${t("chapters")}`,
- }),
- ),
- ...(snap?.notebookReferences ?? []).map(
- (ref): ContextTreeItem => ({
- key: `nb-${ref.notebook_id}`,
- icon: BookOpen,
- kind: t("Notebook"),
- label: `${ref.record_ids.length} ${t("records")}`,
- }),
- ),
+ ...(snap?.bookReferences ?? []).map((ref): ContextTreeItem => ({
+ key: `book-${ref.book_id}`,
+ icon: BookOpen,
+ kind: t("Book"),
+ label: `${ref.page_ids.length} ${t("chapters")}`,
+ })),
+ ...(snap?.readingReferences ?? []).map((ref): ContextTreeItem => ({
+ key: `reading-${ref.material_id}`,
+ icon: BookMarked,
+ kind: t("Reading"),
+ label: `${ref.locators.length} ${t("reading sections")}`,
+ })),
+ ...(snap?.notebookReferences ?? []).map((ref): ContextTreeItem => ({
+ key: `nb-${ref.notebook_id}`,
+ icon: BookOpen,
+ kind: t("Notebook"),
+ label: `${ref.record_ids.length} ${t("records")}`,
+ })),
// Imported agent conversations are folded into the same history_references
// payload but carry the `imported_` id prefix — split them back out so they
// read as "My Agents" rather than "Chat History" (mirrors the composer).
...(snap?.historyReferences ?? [])
.filter((sid) => !sid.startsWith("imported_"))
- .map(
- (sid): ContextTreeItem => ({
- key: `hist-${sid}`,
- icon: MessageSquare,
- kind: t("Chat History"),
- label: "",
- }),
- ),
+ .map((sid): ContextTreeItem => ({
+ key: `hist-${sid}`,
+ icon: MessageSquare,
+ kind: t("Chat History"),
+ label: "",
+ })),
...(snap?.historyReferences ?? [])
.filter((sid) => sid.startsWith("imported_"))
- .map(
- (sid): ContextTreeItem => ({
- key: `agent-${sid}`,
- icon: Bot,
- kind: t("My Agents"),
- label: "",
- }),
- ),
+ .map((sid): ContextTreeItem => ({
+ key: `agent-${sid}`,
+ icon: Bot,
+ kind: t("My Agents"),
+ label: "",
+ })),
...(snap?.questionNotebookReferences?.length
? [
{
@@ -1063,14 +1062,12 @@ const UserMessage = memo(function UserMessage({
} satisfies ContextTreeItem,
]
: []),
- ...(snap?.memoryReferences ?? []).map(
- (file): ContextTreeItem => ({
- key: `mem-${file}`,
- icon: Brain,
- kind: t("Memory"),
- label: file === "summary" ? t("Summary") : t("Profile"),
- }),
- ),
+ ...(snap?.memoryReferences ?? []).map((file): ContextTreeItem => ({
+ key: `mem-${file}`,
+ icon: Brain,
+ kind: t("Memory"),
+ label: file === "summary" ? t("Summary") : t("Profile"),
+ })),
];
return (
@@ -1447,8 +1444,7 @@ export const ChatMessageList = memo(function ChatMessageList({
const resultEv = msg.events?.find((e) => e.type === "result");
if (!resultEv) return null;
const meta = resultEv.metadata?.metadata as
- | Record<string, unknown>
- | undefined;
+ Record<string, unknown> | undefined;
const cs = meta?.cost_summary as
| {
total_cost_usd?: number;
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 697317a4d..3a526e600 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -53,6 +53,7 @@ interface ComposerInputProps {
onSelectKnowledge?: () => void;
onSelectNotebookPicker: () => void;
onSelectBookPicker: () => void;
+ onSelectReadingPicker?: () => void;
onSelectHistoryPicker: () => void;
onSelectAgentsPicker?: () => void;
/** Hide the My Agents entry (e.g. the quiz follow-up surface). */
@@ -144,6 +145,7 @@ export const ComposerInput = memo(
onSelectKnowledge,
onSelectNotebookPicker,
onSelectBookPicker,
+ onSelectReadingPicker,
onSelectHistoryPicker,
onSelectAgentsPicker,
agentsAvailable = true,
@@ -338,6 +340,7 @@ export const ComposerInput = memo(
| "chat_history"
| "my_agents"
| "books"
+ | "reading"
| "notebooks"
| "question_bank"
| "persona"
@@ -350,6 +353,7 @@ export const ComposerInput = memo(
else if (key === "chat_history") onSelectHistoryPicker();
else if (key === "my_agents") onSelectAgentsPicker?.();
else if (key === "books") onSelectBookPicker();
+ else if (key === "reading") onSelectReadingPicker?.();
else if (key === "notebooks") onSelectNotebookPicker();
else if (key === "question_bank") onSelectQuestionBankPicker();
else if (key === "persona") onSelectPersonaPicker();
@@ -362,6 +366,7 @@ export const ComposerInput = memo(
onSelectHistoryPicker,
onSelectAgentsPicker,
onSelectBookPicker,
+ onSelectReadingPicker,
onSelectNotebookPicker,
onSelectQuestionBankPicker,
onSelectPersonaPicker,
@@ -460,6 +465,7 @@ export const ComposerInput = memo(
knowledgeAvailable={knowledgeAvailable}
personaAvailable={personaAvailable}
agentsAvailable={agentsAvailable}
+ readingAvailable={Boolean(onSelectReadingPicker)}
onSelectItem={handleSelectSpaceItem}
/>
</div>
diff --git a/web/components/chat/space/ChatSpaceMenu.tsx b/web/components/chat/space/ChatSpaceMenu.tsx
index 053d64cc4..2f5e59a4f 100644
--- a/web/components/chat/space/ChatSpaceMenu.tsx
+++ b/web/components/chat/space/ChatSpaceMenu.tsx
@@ -2,6 +2,7 @@
import { Fragment, memo, useEffect, useRef, useState } from "react";
import {
+ BookMarked,
BookOpen,
Bot,
ChevronRight,
@@ -19,6 +20,7 @@ type SelectableSpaceKey =
| "chat_history"
| "my_agents"
| "books"
+ | "reading"
| "notebooks"
| "question_bank"
| "persona"
@@ -30,6 +32,7 @@ export interface ChatSpaceSelectionCounts {
chatHistory: number;
myAgents: number;
books: number;
+ reading: number;
notebooks: number;
questionBank: number;
persona: number;
@@ -50,6 +53,8 @@ interface ChatSpaceMenuProps {
personaAvailable?: boolean;
/** Hide the My Agents entry (e.g. the quiz follow-up surface). */
agentsAvailable?: boolean;
+ /** Show imported Reading materials on surfaces that wire its picker. */
+ readingAvailable?: boolean;
onSelectItem: (key: SelectableSpaceKey) => void;
}
@@ -59,6 +64,7 @@ const ITEM_ORDER: SelectableSpaceKey[] = [
"chat_history",
"my_agents",
"books",
+ "reading",
"notebooks",
"question_bank",
"persona",
@@ -80,6 +86,8 @@ function countFor(
return counts.myAgents;
case "books":
return counts.books;
+ case "reading":
+ return counts.reading;
case "notebooks":
return counts.notebooks;
case "question_bank":
@@ -99,6 +107,7 @@ export default memo(function ChatSpaceMenu({
knowledgeAvailable = true,
personaAvailable = true,
agentsAvailable = true,
+ readingAvailable = false,
onSelectItem,
}: ChatSpaceMenuProps) {
const { t } = useTranslation();
@@ -111,6 +120,7 @@ export default memo(function ChatSpaceMenu({
if (key === "knowledge") return knowledgeAvailable;
if (key === "persona") return personaAvailable;
if (key === "my_agents") return agentsAvailable;
+ if (key === "reading") return readingAvailable;
return true;
})
.map((key) => {
@@ -148,6 +158,14 @@ export default memo(function ChatSpaceMenu({
icon: BookOpen,
};
}
+ if (key === "reading") {
+ return {
+ key,
+ label: "Reading",
+ description: "Reference imported reading sections in chat.",
+ icon: BookMarked,
+ };
+ }
if (key === "persona") {
return {
key,
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index d459a9a9b..4d9710d19 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -46,14 +46,13 @@ import {
normalizeBookReferences,
type BookReferencePayload,
} from "@/lib/book-references";
+import {
+ normalizeReadingReferences,
+ type ReadingReferencePayload,
+} from "@/lib/reading-references";
type SessionRuntimeStatus =
- | "idle"
- | "running"
- | "completed"
- | "failed"
- | "cancelled"
- | "rejected";
+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";
interface OutgoingAttachment {
type: string;
@@ -79,6 +78,7 @@ export interface SendMessageOptions {
persistUserMessage?: boolean;
requestSnapshotOverride?: MessageRequestSnapshot;
bookReferences?: BookReferencePayload[];
+ readingReferences?: ReadingReferencePayload[];
/** Edit-branching: when set, the new user message is inserted as a
* sibling under this parent rather than appended to the session tail.
* ``null`` means "explicitly attach to the session root". */
@@ -144,6 +144,7 @@ export interface MessageRequestSnapshot {
historyReferences?: HistoryReferencePayload;
questionNotebookReferences?: QuestionNotebookReferencePayload;
bookReferences?: BookReferencePayload[];
+ readingReferences?: ReadingReferencePayload[];
masteryPathId?: string;
persona?: string;
memoryReferences?: MemoryReferencePayload;
@@ -1008,6 +1009,9 @@ function hydrateRequestSnapshot(
: "";
const memoryReferences = asMemoryReferences(stored.memoryReferences);
const bookReferences = normalizeBookReferences(stored.bookReferences);
+ const readingReferences = normalizeReadingReferences(
+ stored.readingReferences,
+ );
const llmSelection = asLLMSelection(stored.llmSelection);
const masteryPathId =
typeof (stored.masteryPathId ?? stored.mastery_path_id) === "string"
@@ -1022,6 +1026,9 @@ function hydrateRequestSnapshot(
snapshot.questionNotebookReferences = questionNotebookReferences;
}
if (bookReferences.length) snapshot.bookReferences = bookReferences;
+ if (readingReferences.length) {
+ snapshot.readingReferences = readingReferences;
+ }
if (persona) snapshot.persona = persona;
if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;
if (llmSelection) snapshot.llmSelection = llmSelection;
@@ -1154,8 +1161,7 @@ export function UnifiedChatProvider({
// so applying it here only catches the open client up to what a
// reload would already show.
const meta = event.metadata as
- | { title?: string; mastery_path_id?: string }
- | undefined;
+ { title?: string; mastery_path_id?: string } | undefined;
// The tutor can move a conversation between mastery paths mid-turn;
// without this the composer would keep naming the path it started on.
if (typeof meta?.mastery_path_id === "string") {
@@ -1593,6 +1599,8 @@ export function UnifiedChatProvider({
replaySnapshot?.memoryReferences ?? memoryReferences;
const effectiveBookReferences =
replaySnapshot?.bookReferences ?? options?.bookReferences;
+ const effectiveReadingReferences =
+ replaySnapshot?.readingReferences ?? options?.readingReferences;
const effectiveAttachments =
replaySnapshot?.attachments?.map((a) => ({
type: a.type,
@@ -1637,6 +1645,9 @@ export function UnifiedChatProvider({
...(effectiveBookReferences?.length
? { bookReferences: effectiveBookReferences }
: {}),
+ ...(effectiveReadingReferences?.length
+ ? { readingReferences: effectiveReadingReferences }
+ : {}),
...(effectiveMasteryPathId
? { masteryPathId: effectiveMasteryPathId }
: {}),
@@ -1708,6 +1719,9 @@ export function UnifiedChatProvider({
...(effectiveBookReferences?.length
? { book_references: effectiveBookReferences }
: {}),
+ ...(effectiveReadingReferences?.length
+ ? { reading_references: effectiveReadingReferences }
+ : {}),
...(effectiveMasteryPathId
? { mastery_path_id: effectiveMasteryPathId }
: {}),
diff --git a/web/lib/reading-references.ts b/web/lib/reading-references.ts
new file mode 100644
index 000000000..cf4011cb6
--- /dev/null
+++ b/web/lib/reading-references.ts
@@ -0,0 +1,87 @@
+"use client";
+
+import type { UnitKind } from "@/lib/reading-api";
+
+export const MAX_READING_REFERENCE_MATERIALS = 8;
+export const MAX_READING_REFERENCE_UNITS = 24;
+
+export interface SelectedReadingUnit {
+ locator: number;
+ title: string;
+}
+
+export interface SelectedReadingReference {
+ materialId: string;
+ materialTitle: string;
+ unit: UnitKind;
+ units: SelectedReadingUnit[];
+}
+
+export interface ReadingReferencePayload {
+ material_id: string;
+ locators: number[];
+}
+
+export function selectedReadingsToPayload(
+ references: SelectedReadingReference[],
+): ReadingReferencePayload[] {
+ return normalizeReadingReferences(
+ references.map((reference) => ({
+ material_id: reference.materialId,
+ locators: reference.units.map((unit) => unit.locator),
+ })),
+ );
+}
+
+export function countSelectedReadingUnits(
+ references: SelectedReadingReference[],
+): number {
+ return references.reduce(
+ (total, reference) => total + reference.units.length,
+ 0,
+ );
+}
+
+export function normalizeReadingReferences(
+ value: unknown,
+): ReadingReferencePayload[] {
+ if (!Array.isArray(value)) return [];
+ const byMaterial = new Map<string, number[]>();
+ let total = 0;
+
+ for (const item of value) {
+ if (!item || typeof item !== "object") continue;
+ const record = item as Record<string, unknown>;
+ const materialId =
+ typeof record.material_id === "string"
+ ? record.material_id.trim().toLowerCase()
+ : "";
+ if (!/^[0-9a-f]{8,64}$/.test(materialId)) continue;
+ if (!Array.isArray(record.locators)) continue;
+ let locators = byMaterial.get(materialId);
+ if (!locators && byMaterial.size >= MAX_READING_REFERENCE_MATERIALS) {
+ continue;
+ }
+ for (const raw of record.locators) {
+ if (
+ typeof raw !== "number" ||
+ !Number.isSafeInteger(raw) ||
+ raw <= 0 ||
+ locators?.includes(raw)
+ ) {
+ continue;
+ }
+ if (total >= MAX_READING_REFERENCE_UNITS) break;
+ if (!locators) {
+ locators = [];
+ byMaterial.set(materialId, locators);
+ }
+ locators.push(raw);
+ total += 1;
+ }
+ }
+
+ return [...byMaterial.entries()]
+ .filter(([, locators]) => locators.length > 0)
+ .map(([material_id, locators]) => ({ material_id, locators }));
+}
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index 87b0e309f..9921b91f0 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -75,6 +75,12 @@ export interface StartTurnMessage {
book_id: string;
page_ids: string[];
}[];
+ /** Explicit units from imported Reading materials. The server resolves the
+ * text from the current user's store; clients never send trusted content. */
+ reading_references?: {
+ material_id: string;
+ locators: number[];
+ }[];
/** Persistent mastery state to use independently of this chat session. */
mastery_path_id?: string;
/** Immersive reading: the document open in the reader pane, if any. Its
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index bc6f28b3f..a03b77f51 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1547,6 +1547,27 @@
"pages": "pages",
"{{count}} chapters selected": "{{count}} chapters selected",
"No chapters selected": "No chapters selected",
+ "Reading": "Reading",
+ "Reference imported reading sections in chat.": "Reference imported reading sections in chat.",
+ "Select Reading Sections": "Select Reading Sections",
+ "Choose sections from imported reading materials to ground the next answer.": "Choose sections from imported reading materials to ground the next answer.",
+ "Search reading materials": "Search reading materials",
+ "Unable to load reading materials.": "Unable to load reading materials.",
+ "Unable to load reading sections.": "Unable to load reading sections.",
+ "No reading materials found.": "No reading materials found.",
+ "Select a reading material to view sections.": "Select a reading material to view sections.",
+ "Clear material": "Clear material",
+ "sections": "sections",
+ "slide": "slide",
+ "chapter": "chapter",
+ "page": "page",
+ "{{unit}} {{locator}}": "{{unit}} {{locator}}",
+ "{{count}} reading sections selected": "{{count}} reading sections selected",
+ "No reading sections selected": "No reading sections selected",
+ "reading sections": "reading sections",
+ "You can reference up to {{count}} reading materials at once.": "You can reference up to {{count}} reading materials at once.",
+ "You can reference up to {{count}} reading sections at once.": "You can reference up to {{count}} reading sections at once.",
+ "Only the first {{count}} available sections were selected.": "Only the first {{count}} available sections were selected.",
"Books": "Books",
"Generate, browse and study your AI-authored books.": "Generate, browse and study your AI-authored books.",
"Search books": "Search books",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index cca26990d..34f31515f 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1666,6 +1666,27 @@
"pages": "页",
"{{count}} chapters selected": "已选 {{count}} 个章节",
"No chapters selected": "尚未选择章节",
+ "Reading": "精读材料",
+ "Reference imported reading sections in chat.": "在对话中引用已导入的精读材料章节。",
+ "Select Reading Sections": "选择精读章节",
+ "Choose sections from imported reading materials to ground the next answer.": "选择已导入精读材料中的章节,作为下一次回答的依据。",
+ "Search reading materials": "搜索精读材料",
+ "Unable to load reading materials.": "无法加载精读材料。",
+ "Unable to load reading sections.": "无法加载精读章节。",
+ "No reading materials found.": "未找到精读材料。",
+ "Select a reading material to view sections.": "选择一份精读材料以查看章节。",
+ "Clear material": "清除此材料",
+ "sections": "节",
+ "slide": "页幻灯片",
+ "chapter": "章",
+ "page": "页",
+ "{{unit}} {{locator}}": "第 {{locator}} {{unit}}",
+ "{{count}} reading sections selected": "已选 {{count}} 个精读章节",
+ "No reading sections selected": "尚未选择精读章节",
+ "reading sections": "个精读章节",
+ "You can reference up to {{count}} reading materials at once.": "一次最多可引用 {{count}} 份精读材料。",
+ "You can reference up to {{count}} reading sections at once.": "一次最多可引用 {{count}} 个精读章节。",
+ "Only the first {{count}} available sections were selected.": "仅选择了前 {{count}} 个可用章节。",
"Books": "书籍",
"Generate, browse and study your AI-authored books.": "生成、浏览并学习你的 AI 编写书籍。",
"Search books": "搜索书籍",
diff --git a/web/tests/reading-references.test.ts b/web/tests/reading-references.test.ts
new file mode 100644
index 000000000..5243de9f1
--- /dev/null
+++ b/web/tests/reading-references.test.ts
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ MAX_READING_REFERENCE_UNITS,
+ normalizeReadingReferences,
+ selectedReadingsToPayload,
+} from "@/lib/reading-references";
+
+test("selected reading units become a compact id-only payload", () => {
+ assert.deepEqual(
+ selectedReadingsToPayload([
+ {
+ materialId: "abcdef0123456789",
+ materialTitle: "Attention",
+ unit: "chapter",
+ units: [
+ { locator: 2, title: "Mechanism" },
+ { locator: 2, title: "Duplicate" },
+ { locator: 3, title: "Training" },
+ ],
+ },
+ ]),
+ [{ material_id: "abcdef0123456789", locators: [2, 3] }],
+ );
+});
+
+test("malformed ids and locators are dropped at the client boundary", () => {
+ assert.deepEqual(
+ normalizeReadingReferences([
+ { material_id: "../../etc", locators: [1] },
+ {
+ material_id: "ABCDEF0123456789",
+ locators: [0, -1, 1.5, "2", 2],
+ },
+ ]),
+ [{ material_id: "abcdef0123456789", locators: [2] }],
+ );
+});
+
+test("reference payloads are bounded before they reach the websocket", () => {
+ const refs = normalizeReadingReferences([
+ {
+ material_id: "abcdef0123456789",
+ locators: Array.from({ length: 100 }, (_, index) => index + 1),
+ },
+ ]);
+
+ assert.equal(refs[0].locators.length, MAX_READING_REFERENCE_UNITS);
+});
+
+test("empty rows do not consume the material limit", () => {
+ const emptyRows = Array.from({ length: 20 }, (_, index) => ({
+ material_id: index.toString(16).padStart(16, "0"),
+ locators: [],
+ }));
+
+ assert.deepEqual(
+ normalizeReadingReferences([
+ ...emptyRows,
+ { material_id: "abcdef0123456789", locators: [1] },
+ ]),
+ [{ material_id: "abcdef0123456789", locators: [1] }],
+ );
+});