Skip to content

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

fix(reading): bind citations to turn materials and verified locators

XZHd5d381650fde
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 9aa6da566..8c87153ae 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -345,6 +345,7 @@ const AssistantMessage = memo(function AssistantMessage({
) => void;
}) {
const events = useMemo(() => msg.events ?? [], [msg.events]);
+ const readingMaterialId = researchRequestSnapshot?.readingMaterialId;
const resultEvent = useMemo(
() => msg.events?.find((event) => event.type === "result") ?? null,
[msg.events],
@@ -521,6 +522,8 @@ const AssistantMessage = memo(function AssistantMessage({
<AssistantResponse
content={msg.content}
isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ events={events}
/>
) : null}
</>
@@ -543,6 +546,8 @@ const AssistantMessage = memo(function AssistantMessage({
<AssistantResponse
content={msg.content}
isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ events={events}
/>
) : null}
<QuizViewer
@@ -563,6 +568,8 @@ const AssistantMessage = memo(function AssistantMessage({
key={seg.key}
content={seg.text}
isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ events={events}
/>
) : seg.kind === "trace" ? (
// What DeepTutor worked out after the user answered — shown
@@ -584,7 +591,12 @@ const AssistantMessage = memo(function AssistantMessage({
),
)
) : (
- <AssistantResponse content={body} isStreaming={isStreaming} />
+ <AssistantResponse
+ content={body}
+ isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ events={events}
+ />
)}
{/* Non-default branches (quiz, math animator, visualize) keep
ask_user below the body. The default branch inlines the card
diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsx
index 19d4d44ee..3d463c3dd 100644
--- a/web/components/common/AssistantResponse.tsx
+++ b/web/components/common/AssistantResponse.tsx
@@ -5,12 +5,16 @@ import { Fragment, memo, useMemo } from "react";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import ModelThinkingCard from "@/components/common/ModelThinkingCard";
import { useReading } from "@/context/ReadingContext";
+import type { StreamEvent } from "@/lib/unified-ws";
import {
hasVisibleMarkdownContent,
repairMalformedStrongEmphasis,
stripArtifactAnnotations,
} from "@/lib/markdown-display";
-import { linkifyLocatorCitations } from "@/lib/reading-citations";
+import {
+ linkifyLocatorCitations,
+ verifiedReadingLocators,
+} from "@/lib/reading-citations";
import { linkifyMediaTimestamps } from "@/lib/reading-media-citations";
import { parseModelThinkingSegments } from "@/lib/think-segments";
import { useSmoothStreamText } from "@/hooks/useSmoothStreamText";
@@ -27,29 +31,46 @@ interface AssistantResponseProps {
* in that case.
*/
isStreaming?: boolean;
+ readingMaterialId?: string;
+ events?: StreamEvent[];
}
function AssistantResponseImpl({
content,
className = "text-[16px] leading-[1.75]",
isStreaming = false,
+ readingMaterialId,
+ events,
}: AssistantResponseProps) {
const displayContent = useSmoothStreamText(content, isStreaming);
- // Immersive reading only: turn `[p.12]` citations into anchors the reader
- // pane intercepts. Outside that mode `material` is null (there is no
- // provider on most surfaces, and none when no document is open), so this is a
- // no-op and every other chat surface renders byte-identically to before.
+ // A locator becomes interactive only when this turn's persisted reading-tool
+ // events prove it belongs to the material that was open for the turn. The
+ // currently open material is used only for an extra range check; it never
+ // supplies identity for a historical answer.
const { material } = useReading();
+ const verifiedLocators = useMemo(
+ () => verifiedReadingLocators(events, readingMaterialId),
+ [events, readingMaterialId],
+ );
const citedContent = useMemo(
- () =>
- material?.unit === "segment"
- ? linkifyMediaTimestamps(displayContent)
- : material
- ? linkifyLocatorCitations(displayContent, {
- maxLocator: material.unit_count,
- })
- : displayContent,
- [displayContent, material],
+ () => {
+ if (
+ material?.unit === "segment" &&
+ (!readingMaterialId || material.material_id === readingMaterialId)
+ ) {
+ return linkifyMediaTimestamps(displayContent);
+ }
+ return readingMaterialId && verifiedLocators.size > 0
+ ? linkifyLocatorCitations(displayContent, {
+ materialId: readingMaterialId,
+ allowedLocators: verifiedLocators,
+ ...(material?.material_id === readingMaterialId
+ ? { maxLocator: material.unit_count }
+ : {}),
+ })
+ : displayContent;
+ },
+ [displayContent, material, readingMaterialId, verifiedLocators],
);
const segments = useMemo(
() => parseModelThinkingSegments(stripArtifactAnnotations(citedContent)),
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 5a04addda..0ddd7c384 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -18,7 +18,9 @@ import {
READER_TURN_END_EVENT,
type ReaderActionPayload,
} from "@/lib/reading-reader-action";
-import { locatorFromHref } from "@/lib/reading-citations";
+import {
+ citationTargetFromHref,
+} from "@/lib/reading-citations";
import {
fetchExport,
type AnnotationColor,
@@ -158,6 +160,23 @@ export function ReaderPane({
setJump({ locator, quote, nonce: nonceRef.current });
}, []);
+ const navigateCitation = useCallback(
+ async (href: string | null | undefined) => {
+ const target = citationTargetFromHref(href);
+ if (!target) return false;
+ if (
+ target.materialId &&
+ target.materialId !== material?.material_id
+ ) {
+ const opened = await openMaterial(target.materialId);
+ if (!opened) return true;
+ }
+ requestJump(target.locator);
+ return true;
+ },
+ [material?.material_id, openMaterial, requestJump],
+ );
+
useEffect(() => {
if (!externalJump) return;
requestJump(externalJump.locator, externalJump.quote);
@@ -209,16 +228,15 @@ export function ReaderPane({
const answers = document.querySelectorAll('[role="article"]');
const last = answers[answers.length - 1];
const anchor = last?.querySelector<HTMLAnchorElement>(
- 'a[href^="#dt-locator-"]',
+ 'a[href^="#dt-locator-"], a[href^="#dt-material-"]',
);
- const locator = locatorFromHref(anchor?.getAttribute("href"));
- if (locator) requestJump(locator);
+ void navigateCitation(anchor?.getAttribute("href"));
}, 120);
return () => window.clearTimeout(timer);
};
window.addEventListener(READER_TURN_END_EVENT, onTurnEnd);
return () => window.removeEventListener(READER_TURN_END_EVENT, onTurnEnd);
- }, [autoJump, material, requestJump]);
+ }, [autoJump, material, navigateCitation]);
/**
* Citation clicks in assistant prose, intercepted in the CAPTURE phase.
@@ -238,17 +256,17 @@ export function ReaderPane({
if (event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
return;
- const target = event.target as HTMLElement | null;
- const anchor = target?.closest?.("a[href]") as HTMLAnchorElement | null;
- const locator = locatorFromHref(anchor?.getAttribute("href"));
- if (!locator) return;
+ const element = event.target as HTMLElement | null;
+ const anchor = element?.closest?.("a[href]") as HTMLAnchorElement | null;
+ const citation = citationTargetFromHref(anchor?.getAttribute("href"));
+ if (!citation) return;
event.preventDefault();
event.stopPropagation();
- requestJump(locator);
+ void navigateCitation(anchor?.getAttribute("href"));
};
document.addEventListener("click", onClick, true);
return () => document.removeEventListener("click", onClick, true);
- }, [requestJump]);
+ }, [navigateCitation]);
// -- annotations ---------------------------------------------------------
diff --git a/web/context/ReadingContext.tsx b/web/context/ReadingContext.tsx
index 7f53d12be..7a40833c7 100644
--- a/web/context/ReadingContext.tsx
+++ b/web/context/ReadingContext.tsx
@@ -48,7 +48,9 @@ export interface ReadingContextValue {
loading: boolean;
/** Last failure worth showing the user; cleared by `dismissError`. */
error: string | null;
- openMaterial: (candidate: MaterialDetail | MaterialInfo) => Promise<void>;
+ openMaterial: (
+ candidate: MaterialDetail | MaterialInfo | string,
+ ) => Promise<boolean>;
closeMaterial: () => void;
/** Insert or update an annotation, optimistically. */
saveMark: (
@@ -76,7 +78,7 @@ const ReadingContext = createContext<ReadingContextValue>({
annotations: [],
loading: false,
error: null,
- openMaterial: async () => {},
+ openMaterial: async () => false,
closeMaterial: noop,
saveMark: async () => {},
removeMark: async () => {},
@@ -102,26 +104,30 @@ export function ReadingProvider({ children }: { children: ReactNode }) {
}, [material]);
const openMaterial = useCallback(
- async (candidate: MaterialDetail | MaterialInfo) => {
+ async (candidate: MaterialDetail | MaterialInfo | string) => {
const token = ++openTokenRef.current;
setLoading(true);
setErrorState(null);
try {
const detail =
- "outline" in candidate
+ typeof candidate === "string"
+ ? await getMaterial(candidate)
+ : "outline" in candidate
? (candidate as MaterialDetail)
: await getMaterial(candidate.material_id);
const marks = await listAnnotations(detail.material_id);
- if (token !== openTokenRef.current) return;
+ if (token !== openTokenRef.current) return false;
setMaterial(detail);
setAnnotations(marks);
+ return true;
} catch (caught) {
- if (token !== openTokenRef.current) return;
+ if (token !== openTokenRef.current) return false;
setErrorState(
caught instanceof Error
? caught.message
: "This document could not be opened.",
);
+ return false;
} finally {
if (token === openTokenRef.current) setLoading(false);
}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index b4647c7b2..5784d1a2a 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -45,7 +45,10 @@ import {
import { hasPendingAskUserInMessages } from "@/lib/ask-user-state";
import { notify } from "@/lib/notifications";
import { forwardReaderAction } from "@/lib/reading-reader-action";
-import { readingTurnFields } from "@/lib/reading-turn-state";
+import {
+ normalizeReadingMaterialId,
+ readingTurnFields,
+} from "@/lib/reading-turn-state";
import i18n from "i18next";
import {
normalizeBookReferences,
@@ -165,6 +168,8 @@ export interface MessageRequestSnapshot {
persona?: string;
memoryReferences?: MemoryReferencePayload;
llmSelection?: LLMSelection | null;
+ /** Stable identity of the material open for this turn. */
+ readingMaterialId?: string;
}
export interface MessageItem {
@@ -1112,6 +1117,9 @@ function hydrateRequestSnapshot(
typeof (stored.masteryPathId ?? stored.mastery_path_id) === "string"
? String(stored.masteryPathId ?? stored.mastery_path_id).trim()
: "";
+ const readingMaterialId = normalizeReadingMaterialId(
+ stored.readingMaterialId ?? stored.reading_material_id,
+ );
if (config && Object.keys(config).length) snapshot.config = config;
if (notebookReferences.length)
@@ -1125,6 +1133,9 @@ function hydrateRequestSnapshot(
if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;
if (llmSelection) snapshot.llmSelection = llmSelection;
if (masteryPathId) snapshot.masteryPathId = masteryPathId;
+ if (readingMaterialId) {
+ snapshot.readingMaterialId = readingMaterialId;
+ }
return snapshot;
}
@@ -1715,6 +1726,9 @@ export function UnifiedChatProvider({
const effectiveQuestionNotebookReferences =
replaySnapshot?.questionNotebookReferences ??
questionNotebookReferences;
+ const liveReadingFields = readingTurnFields(effectiveCapability);
+ const effectiveReadingMaterialId =
+ replaySnapshot?.readingMaterialId ?? liveReadingFields.reading_material_id;
const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {
content,
capability: effectiveCapability,
@@ -1753,6 +1767,9 @@ export function UnifiedChatProvider({
...(effectiveLLMSelection
? { llmSelection: effectiveLLMSelection }
: {}),
+ ...(effectiveReadingMaterialId
+ ? { readingMaterialId: effectiveReadingMaterialId }
+ : {}),
};
// Default the new message's parent to the tip of the currently-
// visible path so the local chat tree stays connected during
@@ -1822,7 +1839,9 @@ export function UnifiedChatProvider({
// without the capability check every later turn would still carry it.
// Read from a module cell rather than context state so scrolling the
// reader never re-renders the chat.
- ...readingTurnFields(effectiveCapability),
+ ...(effectiveReadingMaterialId
+ ? { reading_material_id: effectiveReadingMaterialId }
+ : liveReadingFields),
// Always sent (possibly ""): an explicit key is the backend's signal
// to persist the value into session.preferences — "" clears back to
// Default. Omitting the key would make the backend fall back to the
diff --git a/web/lib/reading-citations.ts b/web/lib/reading-citations.ts
index 9fb91fc7b..75f84e6c9 100644
--- a/web/lib/reading-citations.ts
+++ b/web/lib/reading-citations.ts
@@ -34,6 +34,22 @@ export interface LocatorCitation {
/** Anchor prefix the reader listens for. */
export const LOCATOR_HREF_PREFIX = "#dt-locator-";
+const MATERIAL_LOCATOR_HREF_PREFIX = "#dt-material-";
+const READING_EVIDENCE_TOOLS = new Set([
+ "search_material",
+ "read_material",
+ "reader_goto",
+]);
+
+export interface ReadingCitationTarget {
+ materialId?: string;
+ locator: number;
+}
+
+interface ReadingEvidenceEvent {
+ type?: string;
+ metadata?: unknown;
+}
/** Largest locator span a single `[p.a-b]` may expand to. */
const MAX_RANGE_SPAN = 40;
@@ -205,16 +221,28 @@ export function findLocatorCitations(text: string): LocatorCitation[] {
*/
export function linkifyLocatorCitations(
text: string,
- options: { maxLocator?: number } = {},
+ options: {
+ maxLocator?: number;
+ materialId?: string;
+ allowedLocators?: Iterable<number>;
+ } = {},
): string {
const citations = findLocatorCitations(text);
if (!citations.length) return text;
- const { maxLocator } = options;
+ const { maxLocator, materialId } = options;
+ const allowed = options.allowedLocators
+ ? new Set(options.allowedLocators)
+ : null;
const skip = codeRanges(text);
let out = "";
let cursor = 0;
for (const citation of citations) {
+ if (allowed && citation.locators.some((locator) => !allowed.has(locator))) {
+ out += text.slice(cursor, citation.end);
+ cursor = citation.end;
+ continue;
+ }
const locators =
typeof maxLocator === "number" && maxLocator > 0
? citation.locators.filter((n) => n <= maxLocator)
@@ -225,7 +253,9 @@ export function linkifyLocatorCitations(
continue;
}
- const href = `${LOCATOR_HREF_PREFIX}${locators[0]}`;
+ const href = materialId
+ ? `${MATERIAL_LOCATOR_HREF_PREFIX}${encodeURIComponent(materialId)}-locator-${locators[0]}`
+ : `${LOCATOR_HREF_PREFIX}${locators[0]}`;
const absorbed =
locators.length === citation.locators.length
? findAbsorbablePhrase(text, citation, skip)
@@ -254,9 +284,69 @@ export function linkifyLocatorCitations(
export function locatorFromHref(
href: string | null | undefined,
): number | null {
- if (!href || !href.startsWith(LOCATOR_HREF_PREFIX)) return null;
- const parsed = Number(href.slice(LOCATOR_HREF_PREFIX.length));
- return Number.isInteger(parsed) && parsed >= 1 ? parsed : null;
+ return citationTargetFromHref(href)?.locator ?? null;
+}
+
+/** Material-aware reader address, with support for legacy locator-only links. */
+export function citationTargetFromHref(
+ href: string | null | undefined,
+): ReadingCitationTarget | null {
+ if (!href) return null;
+ if (href.startsWith(LOCATOR_HREF_PREFIX)) {
+ const locator = Number(href.slice(LOCATOR_HREF_PREFIX.length));
+ return Number.isInteger(locator) && locator >= 1 ? { locator } : null;
+ }
+ if (!href.startsWith(MATERIAL_LOCATOR_HREF_PREFIX)) return null;
+ const match = /^#dt-material-(.+)-locator-(\d+)$/.exec(href);
+ if (!match) return null;
+ const locator = Number(match[2]);
+ let materialId = "";
+ try {
+ materialId = decodeURIComponent(match[1]);
+ } catch {
+ return null;
+ }
+ if (!/^[0-9a-f]{8,64}$/i.test(materialId)) return null;
+ return Number.isInteger(locator) && locator >= 1
+ ? { materialId: materialId.toLowerCase(), locator }
+ : null;
+}
+
+/** Locators grounded by successful reading-tool results for one turn. */
+export function verifiedReadingLocators(
+ events: ReadingEvidenceEvent[] | null | undefined,
+ materialId: string | null | undefined,
+): Set<number> {
+ const verified = new Set<number>();
+ if (!materialId) return verified;
+ const expected = materialId.toLowerCase();
+ for (const event of events ?? []) {
+ if (event.type !== "tool_result" || !event.metadata) continue;
+ const outer = event.metadata as Record<string, unknown>;
+ const tool = String(outer.tool ?? outer.tool_name ?? "");
+ if (!READING_EVIDENCE_TOOLS.has(tool)) {
+ continue;
+ }
+ const nested = outer.tool_metadata;
+ if (!nested || typeof nested !== "object") continue;
+ const metadata = nested as Record<string, unknown>;
+ if (String(metadata.material_id ?? "").toLowerCase() !== expected) continue;
+ const add = (value: unknown) => {
+ const locator = Number(value);
+ if (Number.isInteger(locator) && locator >= 1) verified.add(locator);
+ };
+ if (Array.isArray(metadata.locators)) metadata.locators.forEach(add);
+ if (Array.isArray(metadata.hits)) {
+ metadata.hits.forEach((hit) => {
+ if (hit && typeof hit === "object") {
+ add((hit as Record<string, unknown>).locator);
+ }
+ });
+ }
+ add(metadata.locator);
+ add(metadata.found_locator);
+ }
+ return verified;
}
/** Human label for a locator, using the material's own unit word. */
diff --git a/web/lib/reading-turn-state.ts b/web/lib/reading-turn-state.ts
index eab0196a3..f2a84f6e6 100644
--- a/web/lib/reading-turn-state.ts
+++ b/web/lib/reading-turn-state.ts
@@ -29,6 +29,13 @@ const state: ReadingTurnState = {
timeSeconds: null,
};
+/** Validate persisted/wire material ids before they become reader addresses. */
+export function normalizeReadingMaterialId(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const normalized = value.trim().toLowerCase();
+ return /^[0-9a-f]{8,64}$/.test(normalized) ? normalized : null;
+}
+
export function setReadingWorkspace(workspaceId: string | null): void {
state.workspaceId = workspaceId;
if (!workspaceId) {
diff --git a/web/tests/e2e/reading-citation-material.audit.ts b/web/tests/e2e/reading-citation-material.audit.ts
new file mode 100644
index 000000000..25fa1534c
--- /dev/null
+++ b/web/tests/e2e/reading-citation-material.audit.ts
@@ -0,0 +1,166 @@
+import { expect, test } from "@playwright/test";
+
+const MATERIAL_A = "aaaaaaaaaaaaaaaa";
+const MATERIAL_B = "bbbbbbbbbbbbbbbb";
+const SESSION_ID = "citation-material-regression";
+
+function material(materialId: string, title: string) {
+ return {
+ material_id: materialId,
+ filename: `${title}.md`,
+ unit: "section",
+ unit_count: 2,
+ mime: "text/markdown",
+ title,
+ byte_size: 256,
+ char_count: 128,
+ created_at: 1,
+ has_raw_view: false,
+ render_mode: "text",
+ annotation_count: 0,
+ outline: [],
+ outline_text: "",
+ unit_refs: [],
+ };
+}
+
+const materialA = material(MATERIAL_A, "Source material A");
+const materialB = material(MATERIAL_B, "Current material B");
+
+test.beforeEach(async ({ page }) => {
+ await page.route("**/api/v1/**", async (route) => {
+ const path = new URL(route.request().url()).pathname;
+ const json = (payload: unknown, status = 200) =>
+ route.fulfill({ status, json: payload });
+
+ if (path === "/api/v1/auth/status") {
+ return json({ enabled: false, authenticated: true });
+ }
+ if (path === "/api/v1/settings/ui") return json({ language: "en" });
+ if (path === "/api/v1/dashboard/suggestions") {
+ return json({ suggestions: [], stale: false });
+ }
+ if (path === "/api/v1/settings/llm-options") {
+ return json({
+ active: { profile_id: "p", model_id: "m" },
+ options: [
+ {
+ profile_id: "p",
+ model_id: "m",
+ profile_name: "Profile",
+ model_name: "Model",
+ model: "model",
+ provider: "provider",
+ is_active_default: true,
+ },
+ ],
+ });
+ }
+ if (path === `/api/v1/sessions/${SESSION_ID}`) {
+ return json({
+ id: SESSION_ID,
+ session_id: SESSION_ID,
+ title: "Citation material regression",
+ created_at: 1,
+ updated_at: 2,
+ status: "idle",
+ preferences: { capability: "immersive_reading" },
+ active_turns: [],
+ messages: [
+ {
+ id: 1,
+ session_id: SESSION_ID,
+ role: "user",
+ content: "Where is the source passage?",
+ capability: "immersive_reading",
+ events: [],
+ attachments: [],
+ metadata: {
+ request_snapshot: {
+ content: "Where is the source passage?",
+ capability: "immersive_reading",
+ enabledTools: [],
+ knowledgeBases: [],
+ language: "en",
+ readingMaterialId: MATERIAL_A,
+ },
+ },
+ created_at: 1,
+ parent_message_id: null,
+ },
+ {
+ id: 2,
+ session_id: SESSION_ID,
+ role: "assistant",
+ content: "The grounded passage is here [p.2]. A guess is [p.1].",
+ capability: "immersive_reading",
+ attachments: [],
+ created_at: 2,
+ parent_message_id: 1,
+ events: [
+ {
+ type: "tool_result",
+ source: "chat",
+ stage: "responding",
+ content: "Read section 2",
+ timestamp: 1,
+ metadata: {
+ tool: "read_material",
+ tool_metadata: {
+ material_id: MATERIAL_A,
+ locators: [2],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ });
+ }
+ if (path === "/api/v1/sessions") return json({ sessions: [] });
+ if (path === "/api/v1/reading/supported-formats") {
+ return json({ extensions: [".md"], max_bytes: 1024, raw_view_extensions: [] });
+ }
+ if (path === "/api/v1/reading/extensions") return json([]);
+ if (path === "/api/v1/reading/materials") {
+ return json([materialB, materialA]);
+ }
+ if (path === `/api/v1/reading/materials/${MATERIAL_A}`) return json(materialA);
+ if (path === `/api/v1/reading/materials/${MATERIAL_B}`) return json(materialB);
+ if (path.endsWith("/annotations")) return json([]);
+ const unit = /\/api\/v1\/reading\/materials\/([^/]+)\/units\/(\d+)/.exec(path);
+ if (unit) {
+ const [, materialId, locator] = unit;
+ return json({
+ locator: Number(locator),
+ unit: "section",
+ text:
+ materialId === MATERIAL_A
+ ? `# Source A section ${locator}\n\nVerified source material text.`
+ : `# Current B section ${locator}\n\nWrong material text.`,
+ });
+ }
+ return json({});
+ });
+});
+
+test("historical citation reopens its turn material and unsupported locator stays plain", async ({
+ page,
+}) => {
+ await page.goto(`/home/${SESSION_ID}`);
+
+ await expect(page.getByRole("link", { name: "p.2" })).toHaveAttribute(
+ "href",
+ `#dt-material-${MATERIAL_A}-locator-2`,
+ );
+ await expect(page.getByRole("link", { name: "p.1" })).toHaveCount(0);
+
+ await page.getByRole("button", { name: /Immersive Reading/ }).last().click();
+ await page.getByRole("button", { name: "Open a document to read" }).click();
+ await page.getByText("Current material B.md").click();
+ await expect(page.getByText("Wrong material text.")).toBeVisible();
+
+ await page.getByRole("link", { name: "p.2" }).click();
+ await expect(page.getByText("Verified source material text.")).toBeVisible();
+ await expect(page.getByText("Wrong material text.")).toHaveCount(0);
+});
diff --git a/web/tests/reading-citations.test.ts b/web/tests/reading-citations.test.ts
index b102828dd..0f17da233 100644
--- a/web/tests/reading-citations.test.ts
+++ b/web/tests/reading-citations.test.ts
@@ -2,11 +2,13 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
LOCATOR_HREF_PREFIX,
+ citationTargetFromHref,
codeRanges,
findLocatorCitations,
linkifyLocatorCitations,
locatorFromHref,
locatorLabel,
+ verifiedReadingLocators,
} from "../lib/reading-citations";
test("parses a single locator citation", () => {
@@ -115,6 +117,33 @@ test("linkify rewrites to an anchor the reader can intercept", () => {
);
});
+test("linkify binds a citation to its turn material", () => {
+ assert.equal(
+ linkifyLocatorCitations("Grounded [p.12] claim.", {
+ materialId: "0123456789abcdef",
+ allowedLocators: [12],
+ }),
+ "Grounded [p.12](#dt-material-0123456789abcdef-locator-12) claim.",
+ );
+});
+
+test("unsupported citations remain plain text instead of blind links", () => {
+ assert.equal(
+ linkifyLocatorCitations("Grounded [p.12], guessed [p.13].", {
+ materialId: "0123456789abcdef",
+ allowedLocators: [12],
+ }),
+ "Grounded [p.12](#dt-material-0123456789abcdef-locator-12), guessed [p.13].",
+ );
+ assert.equal(
+ linkifyLocatorCitations("Mixed [p.12,13].", {
+ materialId: "0123456789abcdef",
+ allowedLocators: [12],
+ }),
+ "Mixed [p.12,13].",
+ );
+});
+
test("linkify keeps a multi-locator label but targets the first", () => {
assert.equal(
linkifyLocatorCitations("Both [p.12,17] agree."),
@@ -161,6 +190,69 @@ test("locatorFromHref only accepts the reader's own anchors", () => {
assert.equal(locatorFromHref(undefined), null);
});
+test("citationTargetFromHref restores material-aware and legacy targets", () => {
+ assert.deepEqual(
+ citationTargetFromHref("#dt-material-0123456789ABCDEF-locator-12"),
+ { materialId: "0123456789abcdef", locator: 12 },
+ );
+ assert.deepEqual(citationTargetFromHref(`${LOCATOR_HREF_PREFIX}3`), {
+ locator: 3,
+ });
+ assert.equal(citationTargetFromHref("#dt-material-not-an-id-locator-3"), null);
+});
+
+test("verifiedReadingLocators uses only matching reading-tool evidence", () => {
+ const materialId = "0123456789abcdef";
+ const events = [
+ {
+ type: "tool_result",
+ metadata: {
+ tool: "search_material",
+ tool_metadata: {
+ material_id: materialId,
+ hits: [{ locator: 12 }, { locator: 17 }],
+ },
+ },
+ },
+ {
+ type: "tool_result",
+ metadata: {
+ tool: "read_material",
+ tool_metadata: { material_id: materialId, locators: [12, 13] },
+ },
+ },
+ {
+ type: "tool_result",
+ metadata: {
+ tool: "reader_goto",
+ tool_metadata: { material_id: materialId, locator: 14 },
+ },
+ },
+ {
+ type: "tool_result",
+ metadata: {
+ tool: "read_material",
+ tool_metadata: {
+ material_id: "fedcba9876543210",
+ locators: [99],
+ },
+ },
+ },
+ {
+ type: "tool_result",
+ metadata: {
+ tool: "web_search",
+ tool_metadata: { material_id: materialId, locators: [88] },
+ },
+ },
+ ];
+ assert.deepEqual(
+ [...verifiedReadingLocators(events, materialId)].sort((a, b) => a - b),
+ [12, 13, 14, 17],
+ );
+ assert.deepEqual([...verifiedReadingLocators([], materialId)], []);
+});
+
test("locatorLabel uses the material's own unit word", () => {
assert.equal(locatorLabel("page", 12), "page 12");
assert.equal(locatorLabel("chapter", 3), "chapter 3");
diff --git a/web/tests/reading-turn-state.test.ts b/web/tests/reading-turn-state.test.ts
index 5c9d34f2b..fdefb093e 100644
--- a/web/tests/reading-turn-state.test.ts
+++ b/web/tests/reading-turn-state.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import {
READING_CAPABILITY,
getReadingTurnState,
+ normalizeReadingMaterialId,
readingTurnFields,
resetReadingTurnState,
setReadingMaterial,
@@ -12,6 +13,16 @@ import {
test.beforeEach(() => resetReadingTurnState());
+test("normalizes persisted reading material ids and rejects unsafe values", () => {
+ assert.equal(
+ normalizeReadingMaterialId(" 0123456789ABCDEF "),
+ "0123456789abcdef",
+ );
+ assert.equal(normalizeReadingMaterialId("../../etc/passwd"), null);
+ assert.equal(normalizeReadingMaterialId("0123"), null);
+ assert.equal(normalizeReadingMaterialId(null), null);
+});
+
test("carries the document and viewport on a reading turn", () => {
setReadingMaterial("d138eacaad029843");
setReadingViewport({ locator: 3, selection: "attention" });