Skip to content

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

feat(reading): add safe extension protocol

XZH27700d4a4809
diff --git a/READING_EXTENSIONS.md b/READING_EXTENSIONS.md
new file mode 100644
index 000000000..1382ba02e
--- /dev/null
+++ b/READING_EXTENSIONS.md
@@ -0,0 +1,58 @@
+# Immersive Reading extensions
+
+Immersive Reading discovers optional server-side packages through the
+`deeptutor.reading_extensions` Python entry-point group. DeepTutor ships no
+extensions in this group by default: when none are installed, the Reader does
+not render an extension toolbar.
+
+An entry point resolves to an object or class with a validated `manifest` and a
+`run_action(action, context)` method. The current protocol version is `1`.
+
+```toml
+[project.entry-points."deeptutor.reading_extensions"]
+example = "example_reading_plugin:ExampleExtension"
+```
+
+```python
+from deeptutor.reading.extensions import (
+ ReadingAction,
+ ReadingExtensionManifest,
+ ReadingExtensionResult,
+)
+
+
+class ExampleExtension:
+ manifest = ReadingExtensionManifest(
+ id="example",
+ version="1.0.0",
+ name="Example",
+ actions=[ReadingAction(id="explain", label="Explain")],
+ result_types=["card"],
+ )
+
+ def run_action(self, action, context):
+ return ReadingExtensionResult(
+ type="card",
+ title="Example",
+ payload={"body": context.visible_text[:500]},
+ )
+```
+
+## Security boundary
+
+- The global Reading API authentication policy protects extension routes.
+- The server resolves the material and locator and supplies the stored unit
+ text; the browser cannot replace it with arbitrary text.
+- A selection is forwarded only when it occurs verbatim in the stored unit.
+- Extensions return one of four validated result types: `card`, `quiz`,
+ `feedback`, or `browser_speech`.
+- Results have a 64 KB serialized ceiling. Quiz and speech payloads receive
+ additional shape and length validation.
+- Result data is rendered as React text. Extensions cannot send JavaScript or
+ raw HTML to the Reader.
+- Discovery and execution failures are isolated. A broken optional package
+ cannot prevent documents or other extensions from opening.
+
+Protocol changes must remain backward-compatible within version `1`. A future
+incompatible contract must use a new protocol version rather than changing the
+meaning of an existing field.
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index 0d7b50b46..bc10bea7d 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -381,6 +381,7 @@ from deeptutor.api.routers import (
question_notebook,
quiz_judge,
reading,
+ reading_extensions,
sessions,
settings,
skills,
@@ -442,6 +443,12 @@ app.include_router(
)
app.include_router(book.router, prefix="/api/v1/book", tags=["book"], dependencies=_auth)
app.include_router(reading.router, prefix="/api/v1/reading", tags=["reading"], dependencies=_auth)
+app.include_router(
+ reading_extensions.router,
+ prefix="/api/v1/reading",
+ tags=["reading-extensions"],
+ dependencies=_auth,
+)
app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"], dependencies=_auth)
app.include_router(
capabilities_settings.router,
diff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.py
new file mode 100644
index 000000000..daf2f58c6
--- /dev/null
+++ b/deeptutor/api/routers/reading_extensions.py
@@ -0,0 +1,93 @@
+"""Authenticated transport for schema-driven Immersive Reading extensions."""
+
+from __future__ import annotations
+
+import inspect
+import re
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from deeptutor.reading import ReadingStore
+from deeptutor.reading.extensions import (
+ ReadingContext,
+ ReadingExtensionResult,
+ get_reading_extension_registry,
+)
+
+router = APIRouter()
+
+
+class ActionPayload(BaseModel):
+ locator: int = Field(ge=1)
+ source_anchor: str = Field(default="", max_length=4096)
+ selection: str = Field(default="", max_length=10_000)
+ locale: str = Field(default="en", max_length=32)
+
+
+def _normal(value: str) -> str:
+ return re.sub(r"\s+", " ", value).strip()
+
+
+def _verified_selection(candidate: str, unit_text: str) -> str:
+ value = _normal(candidate)
+ return value if value and value in _normal(unit_text) else ""
+
+
[email protected]("/extensions")
+async def list_extensions() -> list[dict[str, Any]]:
+ return [extension.manifest.model_dump() for extension in get_reading_extension_registry().all()]
+
+
[email protected]("/materials/{material_id}/extensions/{extension_id}/actions/{action}")
+async def run_extension_action(
+ material_id: str,
+ extension_id: str,
+ action: str,
+ payload: ActionPayload,
+) -> dict[str, Any]:
+ extension = get_reading_extension_registry().get(extension_id)
+ if extension is None:
+ raise HTTPException(status_code=404, detail="Reading extension not found.")
+ declared_action = next((row for row in extension.manifest.actions if row.id == action), None)
+ if declared_action is None:
+ raise HTTPException(status_code=404, detail="Reading extension action not found.")
+ try:
+ unit_text = ReadingStore().unit_text(material_id, payload.locator)
+ except Exception as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ selection = _verified_selection(payload.selection, unit_text)
+ if "selection" in declared_action.requires and not selection:
+ raise HTTPException(status_code=400, detail="Select text from the visible unit first.")
+ context = ReadingContext(
+ material_id=material_id,
+ locator=payload.locator,
+ source_anchor=payload.source_anchor,
+ locale=payload.locale,
+ selection=selection,
+ visible_text=unit_text,
+ )
+ try:
+ value = extension.run_action(action, context)
+ if inspect.isawaitable(value):
+ value = await value
+ result = (
+ value
+ if isinstance(value, ReadingExtensionResult)
+ else ReadingExtensionResult.model_validate(value)
+ )
+ if result.type not in extension.manifest.result_types:
+ raise ValueError(f"Extension returned undeclared result type {result.type!r}.")
+ return result.model_dump()
+ except Exception as exc:
+ raise HTTPException(
+ status_code=503,
+ detail={
+ "message": "This reading action is temporarily unavailable.",
+ "recoverable": True,
+ },
+ ) from exc
+
+
+__all__ = ["router"]
diff --git a/deeptutor/reading/extensions.py b/deeptutor/reading/extensions.py
new file mode 100644
index 000000000..cc66715e3
--- /dev/null
+++ b/deeptutor/reading/extensions.py
@@ -0,0 +1,145 @@
+"""Schema-driven extension protocol for Immersive Reading.
+
+Extensions are Python entry points, never browser JavaScript. They receive a
+server-verified reading context and return one of the small result schemas the
+Reader knows how to render. One broken package is skipped without affecting
+the reader or any other extension.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Literal, Protocol
+
+from pydantic import BaseModel, Field, model_validator
+
+from deeptutor.core.entry_points import load_entry_point_group
+
+logger = logging.getLogger(__name__)
+ENTRY_POINT_GROUP = "deeptutor.reading_extensions"
+PROTOCOL_VERSION = "1"
+RESULT_TYPES = frozenset({"card", "quiz", "feedback", "browser_speech"})
+_ID_PATTERN = r"^[a-z][a-z0-9_-]{0,63}$"
+
+
+class ReadingAction(BaseModel):
+ id: str = Field(pattern=_ID_PATTERN)
+ label: str = Field(min_length=1, max_length=80)
+ trigger: Literal["toolbar"] = "toolbar"
+ requires: list[Literal["selection", "visible_text"]] = Field(default_factory=list)
+
+
+class ReadingExtensionManifest(BaseModel):
+ id: str = Field(pattern=_ID_PATTERN)
+ version: str = Field(min_length=1, max_length=32)
+ name: str = Field(min_length=1, max_length=80)
+ protocol_version: Literal["1"] = PROTOCOL_VERSION
+ actions: list[ReadingAction] = Field(min_length=1, max_length=12)
+ result_types: list[Literal["card", "quiz", "feedback", "browser_speech"]] = Field(min_length=1)
+
+
+class ReadingContext(BaseModel):
+ material_id: str
+ locator: int = Field(ge=1)
+ source_anchor: str = Field(default="", max_length=4096)
+ locale: str = Field(default="en", max_length=32)
+ selection: str = Field(default="", max_length=10_000)
+ visible_text: str = Field(max_length=60_000)
+
+
+class ReadingExtensionResult(BaseModel):
+ type: Literal["card", "quiz", "feedback", "browser_speech"]
+ title: str = Field(default="", max_length=160)
+ message: str = Field(default="", max_length=4000)
+ payload: dict[str, Any] = Field(default_factory=dict)
+
+ @model_validator(mode="after")
+ def validate_payload(self) -> "ReadingExtensionResult":
+ if len(json.dumps(self.payload, ensure_ascii=False, default=str)) > 64_000:
+ raise ValueError("Reading extension result payload exceeds 64 KB.")
+ if self.type == "browser_speech":
+ text = self.payload.get("text")
+ if not isinstance(text, str) or not text.strip() or len(text) > 60_000:
+ raise ValueError("browser_speech requires non-empty text up to 60,000 chars.")
+ if self.type == "quiz":
+ questions = self.payload.get("questions")
+ if not isinstance(questions, list) or not 1 <= len(questions) <= 20:
+ raise ValueError("quiz requires between 1 and 20 questions.")
+ for row in questions:
+ if not isinstance(row, dict):
+ raise ValueError("Each quiz question must be an object.")
+ if not isinstance(row.get("prompt"), str):
+ raise ValueError("Each quiz question requires a prompt.")
+ choices = row.get("choices")
+ if not isinstance(choices, list) or not 2 <= len(choices) <= 8:
+ raise ValueError("Each quiz question requires 2 to 8 choices.")
+ if not all(isinstance(choice, str) for choice in choices):
+ raise ValueError("Quiz choices must be strings.")
+ return self
+
+
+class ReadingExtension(Protocol):
+ manifest: ReadingExtensionManifest
+
+ def run_action(
+ self, action: str, context: ReadingContext
+ ) -> ReadingExtensionResult | dict[str, Any]: ...
+
+
+def _coerce(name: str, loaded: Any) -> ReadingExtension | None:
+ candidate = loaded() if isinstance(loaded, type) else loaded
+ try:
+ manifest = ReadingExtensionManifest.model_validate(getattr(candidate, "manifest", None))
+ except Exception:
+ logger.warning("Reading extension %r has an invalid manifest.", name, exc_info=True)
+ return None
+ if manifest.id != name:
+ logger.warning("Reading extension %r declares a different id.", name)
+ return None
+ if not callable(getattr(candidate, "run_action", None)):
+ logger.warning("Reading extension %r has no run_action method.", name)
+ return None
+ candidate.manifest = manifest
+ return candidate
+
+
+class ReadingExtensionRegistry:
+ def __init__(self, extensions: list[ReadingExtension] | None = None) -> None:
+ rows = (
+ extensions
+ if extensions is not None
+ else load_entry_point_group(ENTRY_POINT_GROUP, _coerce, log=logger)
+ )
+ self._extensions: dict[str, ReadingExtension] = {}
+ for row in rows:
+ self._extensions.setdefault(row.manifest.id, row)
+
+ def all(self) -> list[ReadingExtension]:
+ return sorted(self._extensions.values(), key=lambda row: row.manifest.id)
+
+ def get(self, extension_id: str) -> ReadingExtension | None:
+ return self._extensions.get(extension_id)
+
+
+_registry: ReadingExtensionRegistry | None = None
+
+
+def get_reading_extension_registry(*, refresh: bool = False) -> ReadingExtensionRegistry:
+ global _registry
+ if _registry is None or refresh:
+ _registry = ReadingExtensionRegistry()
+ return _registry
+
+
+__all__ = [
+ "ENTRY_POINT_GROUP",
+ "PROTOCOL_VERSION",
+ "RESULT_TYPES",
+ "ReadingAction",
+ "ReadingContext",
+ "ReadingExtensionManifest",
+ "ReadingExtensionRegistry",
+ "ReadingExtensionResult",
+ "get_reading_extension_registry",
+]
diff --git a/tests/reading/test_extension_router.py b/tests/reading/test_extension_router.py
new file mode 100644
index 000000000..aa7b2219a
--- /dev/null
+++ b/tests/reading/test_extension_router.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+
+from deeptutor.api.routers import reading_extensions
+from deeptutor.reading import ReadingStore
+from deeptutor.reading.extensions import (
+ ReadingAction,
+ ReadingExtensionManifest,
+ ReadingExtensionRegistry,
+ ReadingExtensionResult,
+)
+from deeptutor.services.path_service import PathService
+
+
+def material(monkeypatch, tmp_path: Path):
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
+ PathService.reset_instance()
+ source = tmp_path / "source.txt"
+ source.write_text("Visible passage with a verified phrase.", encoding="utf-8")
+ manifest = ReadingStore().ingest(source)
+ yield manifest
+ PathService.reset_instance()
+
+
+def _client(monkeypatch, extension) -> TestClient:
+ registry = ReadingExtensionRegistry([extension])
+ monkeypatch.setattr(
+ reading_extensions,
+ "get_reading_extension_registry",
+ lambda: registry,
+ )
+ app = FastAPI()
+ app.include_router(reading_extensions.router, prefix="/api/v1/reading")
+ return TestClient(app)
+
+
+def _extension(run_action, *, requires=(), result_types=("card",)):
+ return SimpleNamespace(
+ manifest=ReadingExtensionManifest(
+ id="sample",
+ version="1.0.0",
+ name="Sample",
+ actions=[
+ ReadingAction(
+ id="open",
+ label="Open",
+ requires=list(requires),
+ )
+ ],
+ result_types=list(result_types),
+ ),
+ run_action=run_action,
+ )
+
+
+def test_action_receives_only_server_verified_visible_text(material, monkeypatch):
+ captured = {}
+
+ def run(_action, context):
+ captured.update(context.model_dump())
+ return ReadingExtensionResult(type="card", payload={"body": "ok"})
+
+ client = _client(monkeypatch, _extension(run))
+ response = client.post(
+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",
+ json={"locator": 1, "selection": "forged text", "locale": "en"},
+ )
+ assert response.status_code == 200, response.text
+ assert captured["selection"] == ""
+ assert captured["visible_text"] == "Visible passage with a verified phrase."
+
+
+def test_selection_requirement_rejects_unverified_text(material, monkeypatch):
+ client = _client(
+ monkeypatch,
+ _extension(lambda *_: pytest.fail("must not run"), requires=("selection",)),
+ )
+ response = client.post(
+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",
+ json={"locator": 1, "selection": "not in the material"},
+ )
+ assert response.status_code == 400
+
+
+ "run_action",
+ [
+ lambda *_: (_ for _ in ()).throw(RuntimeError("broken plugin")),
+ lambda *_: ReadingExtensionResult(type="feedback"),
+ ],
+)
+def test_extension_failures_are_isolated(material, monkeypatch, run_action):
+ client = _client(monkeypatch, _extension(run_action))
+ response = client.post(
+ f"/api/v1/reading/materials/{material.material_id}/extensions/sample/actions/open",
+ json={"locator": 1},
+ )
+ assert response.status_code == 503
+ assert response.json()["detail"]["recoverable"] is True
diff --git a/tests/reading/test_extensions.py b/tests/reading/test_extensions.py
new file mode 100644
index 000000000..0e041d6ed
--- /dev/null
+++ b/tests/reading/test_extensions.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from pydantic import ValidationError
+import pytest
+
+from deeptutor.reading.extensions import (
+ ReadingAction,
+ ReadingExtensionManifest,
+ ReadingExtensionRegistry,
+ ReadingExtensionResult,
+)
+
+
+def _extension(identifier: str = "sample"):
+ return SimpleNamespace(
+ manifest=ReadingExtensionManifest(
+ id=identifier,
+ version="1.0.0",
+ name="Sample",
+ actions=[ReadingAction(id="open", label="Open")],
+ result_types=["card"],
+ ),
+ run_action=lambda *_: ReadingExtensionResult(type="card"),
+ )
+
+
+def test_core_has_no_builtin_reading_extensions(monkeypatch):
+ monkeypatch.setattr(
+ "deeptutor.reading.extensions.load_entry_point_group",
+ lambda *_args, **_kwargs: [],
+ )
+ assert ReadingExtensionRegistry().all() == []
+
+
+def test_duplicate_extension_does_not_replace_the_first():
+ first = _extension()
+ duplicate = _extension()
+ registry = ReadingExtensionRegistry([first, duplicate])
+ assert registry.get("sample") is first
+
+
+def test_result_schema_rejects_unsafe_or_unbounded_shapes():
+ with pytest.raises(ValidationError):
+ ReadingExtensionResult(type="browser_speech", payload={"text": ""})
+ with pytest.raises(ValidationError):
+ ReadingExtensionResult(
+ type="quiz",
+ payload={"questions": [{"prompt": "Question", "choices": ["one"]}]},
+ )
+ with pytest.raises(ValidationError):
+ ReadingExtensionResult(type="card", payload={"body": "x" * 70_000})
+
+
+def test_manifest_rejects_non_toolbar_triggers():
+ with pytest.raises(ValidationError):
+ ReadingAction(id="open", label="Open", trigger="javascript") # type: ignore[arg-type]
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 5273ab512..4646103c0 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -34,6 +34,7 @@ import {
type SelectionPayload,
} from "./PdfDocumentView";
import { ReaderResizeHandle } from "./ReaderResizeHandle";
+import { ReadingExtensionBar } from "./ReadingExtensionBar";
import { TextUnitView, unitLabel } from "./TextUnitView";
/** Event the reader dispatches to prefill the composer from a selection. */
@@ -407,6 +408,15 @@ export function ReaderPane({ onClose }: ReaderPaneProps) {
</div>
)}
+ {material && (
+ <ReadingExtensionBar
+ materialId={material.material_id}
+ locator={currentLocator}
+ selection={selection?.quote}
+ onError={setError}
+ />
+ )}
+
{showOutline && material && outlineRows.length > 0 && (
<nav className="dt-reader-scroll max-h-[34%] shrink-0 overflow-y-auto border-b border-[var(--border)] bg-[var(--muted)]/25 px-2 py-1.5">
<ul>
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsx
new file mode 100644
index 000000000..eb1e3a1f5
--- /dev/null
+++ b/web/components/reading/ReadingExtensionBar.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { Loader2, Sparkles, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import {
+ listReadingExtensions,
+ runReadingExtension,
+ type ReadingExtensionManifest,
+ type ReadingExtensionResult,
+} from "@/lib/reading-api";
+
+export function ReadingExtensionBar({
+ materialId,
+ locator,
+ selection,
+ onError,
+}: {
+ materialId: string;
+ locator: number;
+ selection?: string;
+ onError: (message: string) => void;
+}) {
+ const { i18n, t } = useTranslation();
+ const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);
+ const [busy, setBusy] = useState("");
+ const [result, setResult] = useState<ReadingExtensionResult | null>(null);
+
+ useEffect(() => {
+ let active = true;
+ void listReadingExtensions()
+ .then((rows) => {
+ if (active) setExtensions(rows);
+ })
+ .catch((error) => {
+ if (active) onError(error instanceof Error ? error.message : String(error));
+ });
+ return () => {
+ active = false;
+ window.speechSynthesis?.cancel();
+ };
+ }, [materialId, onError]);
+
+ useEffect(() => setResult(null), [locator, materialId]);
+
+ const actions = useMemo(
+ () =>
+ extensions.flatMap((extension) =>
+ extension.actions.map((action) => ({ extension, action })),
+ ),
+ [extensions],
+ );
+
+ async function run(
+ extension: ReadingExtensionManifest,
+ action: ReadingExtensionManifest["actions"][number],
+ ) {
+ const key = `${extension.id}:${action.id}`;
+ setBusy(key);
+ try {
+ const next = await runReadingExtension(
+ materialId,
+ extension.id,
+ action.id,
+ {
+ locator,
+ selection: selection || "",
+ locale: i18n.language,
+ },
+ );
+ setResult(next);
+ if (next.type === "browser_speech") {
+ const text = String(next.payload.text || "");
+ if (!("speechSynthesis" in window) || !text) {
+ onError(t("No speech voice is available in this browser."));
+ return;
+ }
+ window.speechSynthesis.cancel();
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.lang = String(next.payload.locale || i18n.language);
+ window.speechSynthesis.speak(utterance);
+ }
+ } catch (error) {
+ onError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setBusy("");
+ }
+ }
+
+ if (actions.length === 0) return null;
+ return (
+ <>
+ <div className="flex shrink-0 gap-1.5 overflow-x-auto border-b border-[var(--border)] bg-[var(--muted)]/25 px-2.5 py-2">
+ {actions.map(({ extension, action }) => {
+ const key = `${extension.id}:${action.id}`;
+ const disabled =
+ Boolean(busy) ||
+ (action.requires.includes("selection") && !selection?.trim());
+ return (
+ <button
+ key={key}
+ type="button"
+ disabled={disabled}
+ onClick={() => void run(extension, action)}
+ className="inline-flex h-8 min-w-[88px] flex-1 items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-xs font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50"
+ >
+ {busy === key ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <Sparkles size={14} />
+ )}
+ <span className="truncate">{action.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ {result && result.type !== "browser_speech" ? (
+ <ExtensionResult
+ result={result}
+ closeLabel={t("Close")}
+ onClose={() => setResult(null)}
+ />
+ ) : null}
+ </>
+ );
+}
+
+function ExtensionResult({
+ result,
+ closeLabel,
+ onClose,
+}: {
+ result: ReadingExtensionResult;
+ closeLabel: string;
+ onClose: () => void;
+}) {
+ const questions = Array.isArray(result.payload.questions)
+ ? (result.payload.questions as Array<{
+ id?: string;
+ prompt: string;
+ choices: string[];
+ }>)
+ : [];
+ const items = Array.isArray(result.payload.items)
+ ? result.payload.items.map(String)
+ : [];
+ const body = String(result.payload.body || result.payload.overview || "");
+ return (
+ <section className="relative shrink-0 border-b border-[var(--border)] bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)]">
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={closeLabel}
+ className="absolute right-2 top-2 text-[var(--muted-foreground)]"
+ >
+ <X size={14} />
+ </button>
+ <h3 className="pr-6 font-semibold">{result.title}</h3>
+ {result.message ? (
+ <p className="mt-1 text-[var(--muted-foreground)]">{result.message}</p>
+ ) : null}
+ {body ? <p className="mt-2 whitespace-pre-wrap">{body}</p> : null}
+ {items.length ? (
+ <ul className="mt-2 list-disc space-y-1 pl-5">
+ {items.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ ) : null}
+ {questions.map((question, index) => (
+ <div key={question.id || index} className="mt-3">
+ <p className="font-medium">{question.prompt}</p>
+ <ol className="mt-1 list-inside list-[upper-alpha] space-y-0.5 text-[var(--muted-foreground)]">
+ {question.choices.map((choice) => (
+ <li key={choice}>{choice}</li>
+ ))}
+ </ol>
+ </div>
+ ))}
+ </section>
+ );
+}
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index cf52b46b3..70eaa3c50 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -122,6 +122,29 @@ export interface SupportedFormats {
raw_view_extensions: string[];
}
+export interface ReadingExtensionAction {
+ id: string;
+ label: string;
+ trigger: "toolbar";
+ requires: Array<"selection" | "visible_text">;
+}
+
+export interface ReadingExtensionManifest {
+ id: string;
+ version: string;
+ name: string;
+ protocol_version: "1";
+ actions: ReadingExtensionAction[];
+ result_types: Array<"card" | "quiz" | "feedback" | "browser_speech">;
+}
+
+export interface ReadingExtensionResult {
+ type: "card" | "quiz" | "feedback" | "browser_speech";
+ title: string;
+ message: string;
+ payload: Record<string, unknown>;
+}
+
const BASE = "/api/v1/reading";
/** Surface the server's own message — it explains what the user can do next. */
@@ -131,6 +154,13 @@ async function unwrap<T>(response: Response): Promise<T> {
try {
const body = (await response.json()) as { detail?: unknown };
if (typeof body?.detail === "string" && body.detail) detail = body.detail;
+ else if (
+ typeof body?.detail === "object" &&
+ body.detail !== null &&
+ "message" in body.detail
+ ) {
+ detail = String((body.detail as { message: unknown }).message);
+ }
} catch {
// Non-JSON error body (a proxy page, say) — keep the status line.
}
@@ -182,6 +212,39 @@ export async function getUnitText(
);
}
+export async function listReadingExtensions(): Promise<
+ ReadingExtensionManifest[]
+> {
+ return unwrap(
+ await apiFetch(apiUrl(`${BASE}/extensions`), { cache: "no-store" }),
+ );
+}
+
+export async function runReadingExtension(
+ materialId: string,
+ extensionId: string,
+ action: string,
+ context: {
+ locator: number;
+ source_anchor?: string;
+ selection?: string;
+ locale?: string;
+ },
+): Promise<ReadingExtensionResult> {
+ return unwrap(
+ await apiFetch(
+ apiUrl(
+ `${BASE}/materials/${materialId}/extensions/${extensionId}/actions/${action}`,
+ ),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(context),
+ },
+ ),
+ );
+}
+
/** URL of the original bytes. Served with Range support so pdf.js can stream. */
export function rawMaterialUrl(materialId: string): string {
return apiUrl(`${BASE}/materials/${materialId}/raw`);
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ba5e1e40f..e608b5d1e 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -431,6 +431,7 @@
"Continue": "Continue",
"View": "View",
"Close": "Close",
+ "No speech voice is available in this browser.": "No speech voice is available in this browser.",
"messages": "messages",
"Failed to load session": "Failed to load session",
"Added Successfully!": "Added Successfully!",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 17624414f..37ec3a456 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -431,6 +431,7 @@
"Continue": "继续",
"View": "查看",
"Close": "关闭",
+ "No speech voice is available in this browser.": "此浏览器没有可用的语音。",
"messages": "条消息",
"Failed to load session": "加载会话失败",
"Added Successfully!": "保存成功!",
diff --git a/web/tests/reading-extensions.test.ts b/web/tests/reading-extensions.test.ts
new file mode 100644
index 000000000..6b61a584e
--- /dev/null
+++ b/web/tests/reading-extensions.test.ts
@@ -0,0 +1,32 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+
+const component = readFileSync(
+ path.resolve(process.cwd(), "components/reading/ReadingExtensionBar.tsx"),
+ "utf8",
+);
+const pane = readFileSync(
+ path.resolve(process.cwd(), "components/reading/ReaderPane.tsx"),
+ "utf8",
+);
+const api = readFileSync(
+ path.resolve(process.cwd(), "lib/reading-api.ts"),
+ "utf8",
+);
+
+test("the Reader toolbar is empty when no extension is installed", () => {
+ assert.match(component, /if \(actions\.length === 0\) return null/);
+ assert.match(pane, /<ReadingExtensionBar/);
+});
+
+test("extension results never inject browser JavaScript or raw HTML", () => {
+ assert.doesNotMatch(component, /dangerouslySetInnerHTML|eval\(|new Function/);
+ assert.match(component, /String\(result\.payload\.body/);
+});
+
+test("the browser sends a locator and selection, not trusted visible text", () => {
+ assert.match(api, /runReadingExtension/);
+ assert.doesNotMatch(api, /visible_text\?: string/);
+});