mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 17:40:18 +08:00
Merge pull request #1036 from Zuan0/reading-citation-grounding
# Conflicts: # web/components/chat/home/ChatMessages.tsx # web/components/common/AssistantResponse.tsx # web/components/reading/ReaderPane.tsx # web/context/ReadingContext.tsx # web/context/UnifiedChatContext.tsx # web/lib/reading-turn-state.ts # web/tests/e2e/reading-citation-material.audit.ts # web/tests/reading-citations.test.ts # web/tests/reading-turn-state.test.ts
This commit is contained in:
@@ -301,7 +301,11 @@ class SearchMaterialTool(_ReadingToolBase):
|
||||
f'No match for "{query}". Try fewer or different words, or '
|
||||
f"call material_outline to see what the document covers."
|
||||
),
|
||||
metadata={"material_id": material_id, "hits": []},
|
||||
metadata={
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"hits": [],
|
||||
},
|
||||
)
|
||||
|
||||
lines = [
|
||||
@@ -339,6 +343,7 @@ class SearchMaterialTool(_ReadingToolBase):
|
||||
{
|
||||
"type": "reading",
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"title": manifest.filename,
|
||||
"page": hit.locator,
|
||||
"content": hit.snippet,
|
||||
@@ -347,6 +352,7 @@ class SearchMaterialTool(_ReadingToolBase):
|
||||
],
|
||||
metadata={
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"mode": result.mode,
|
||||
"hits": [hit.to_dict() for hit in result.hits],
|
||||
},
|
||||
@@ -400,7 +406,11 @@ class ReadMaterialTool(_ReadingToolBase):
|
||||
f"Those {manifest.unit}s contain no extractable text "
|
||||
"(they may be images or scans)."
|
||||
),
|
||||
metadata={"material_id": material_id, "locators": list(rendered.locators)},
|
||||
metadata={
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"locators": list(rendered.locators),
|
||||
},
|
||||
)
|
||||
refs = {
|
||||
row.locator: row
|
||||
@@ -432,6 +442,7 @@ class ReadMaterialTool(_ReadingToolBase):
|
||||
{
|
||||
"type": "reading",
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"title": manifest.filename,
|
||||
"page": locator,
|
||||
}
|
||||
@@ -439,6 +450,7 @@ class ReadMaterialTool(_ReadingToolBase):
|
||||
],
|
||||
metadata={
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"locators": list(rendered.locators),
|
||||
"truncated": rendered.truncated,
|
||||
},
|
||||
@@ -649,6 +661,7 @@ def _goto_result(
|
||||
content=f"Reader moved to {manifest.unit} {locator}{note}.",
|
||||
metadata={
|
||||
"material_id": material_id,
|
||||
"material_revision": manifest.revision,
|
||||
"reader_action": "goto",
|
||||
"locator": locator,
|
||||
"quote": quote,
|
||||
|
||||
@@ -440,6 +440,15 @@ def _reading_material_id(value: Any) -> str:
|
||||
return candidate if _READING_ID_RE.match(candidate) else ""
|
||||
|
||||
|
||||
def _reading_material_revision(value: Any) -> int | None:
|
||||
"""Normalize the immutable content revision displayed for this turn."""
|
||||
try:
|
||||
revision = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return revision if revision >= 1 else None
|
||||
|
||||
|
||||
def _reading_workspace_id(value: Any) -> str:
|
||||
"""Normalize the owner-scoped reading workspace bound to this turn."""
|
||||
candidate = str(value or "").strip()
|
||||
@@ -661,6 +670,11 @@ def _request_snapshot_metadata(
|
||||
reading_material_id = _reading_material_id(payload.get("reading_material_id"))
|
||||
if reading_material_id:
|
||||
snapshot["readingMaterialId"] = reading_material_id
|
||||
reading_material_revision = _reading_material_revision(
|
||||
payload.get("reading_material_revision")
|
||||
)
|
||||
if reading_material_revision is not None:
|
||||
snapshot["readingMaterialRevision"] = reading_material_revision
|
||||
reading_workspace_id = _reading_workspace_id(payload.get("reading_workspace_id"))
|
||||
if reading_workspace_id:
|
||||
snapshot["readingWorkspaceId"] = reading_workspace_id
|
||||
@@ -1585,6 +1599,9 @@ class TurnRuntimeManager:
|
||||
}
|
||||
reading_workspace_id = _reading_workspace_id(payload.get("reading_workspace_id"))
|
||||
reading_material_id = _reading_material_id(payload.get("reading_material_id"))
|
||||
reading_material_revision = _reading_material_revision(
|
||||
payload.get("reading_material_revision")
|
||||
)
|
||||
if workspace_mode == WORKSPACE_MODE_READING and reading_workspace_id:
|
||||
from deeptutor.reading import ReadingCatalogStore
|
||||
|
||||
@@ -1609,6 +1626,7 @@ class TurnRuntimeManager:
|
||||
**payload,
|
||||
"reading_workspace_id": reading_workspace_id,
|
||||
"reading_material_id": reading_material_id,
|
||||
"reading_material_revision": reading_material_revision,
|
||||
}
|
||||
# A mastery path has a longer lifetime than any one conversation.
|
||||
# Persist the explicit association on the session, and restore it on
|
||||
@@ -2078,6 +2096,11 @@ class TurnRuntimeManager:
|
||||
if "reading_material_id" in overrides
|
||||
else snapshot.get("readingMaterialId")
|
||||
),
|
||||
"reading_material_revision": _reading_material_revision(
|
||||
overrides.get("reading_material_revision")
|
||||
if "reading_material_revision" in overrides
|
||||
else snapshot.get("readingMaterialRevision")
|
||||
),
|
||||
"reading_workspace_id": _reading_workspace_id(
|
||||
overrides.get("reading_workspace_id")
|
||||
if "reading_workspace_id" in overrides
|
||||
@@ -2890,6 +2913,9 @@ class TurnRuntimeManager:
|
||||
# capability and binds its tools; the viewport tells the
|
||||
# model where the user is actually looking.
|
||||
"reading_material_id": _reading_material_id(payload.get("reading_material_id")),
|
||||
"reading_material_revision": _reading_material_revision(
|
||||
payload.get("reading_material_revision")
|
||||
),
|
||||
"reading_workspace_id": _reading_workspace_id(
|
||||
payload.get("reading_workspace_id")
|
||||
),
|
||||
|
||||
@@ -352,6 +352,8 @@ const AssistantMessage = memo(function AssistantMessage({
|
||||
}) {
|
||||
const events = useMemo(() => msg.events ?? [], [msg.events]);
|
||||
const readingMaterialId = researchRequestSnapshot?.readingMaterialId;
|
||||
const readingMaterialRevision =
|
||||
researchRequestSnapshot?.readingMaterialRevision;
|
||||
const resultEvent = useMemo(
|
||||
() => msg.events?.find((event) => event.type === "result") ?? null,
|
||||
[msg.events],
|
||||
@@ -531,6 +533,7 @@ const AssistantMessage = memo(function AssistantMessage({
|
||||
content={msg.content}
|
||||
isStreaming={isStreaming}
|
||||
readingMaterialId={readingMaterialId}
|
||||
readingMaterialRevision={readingMaterialRevision}
|
||||
events={events}
|
||||
/>
|
||||
) : null}
|
||||
@@ -555,6 +558,7 @@ const AssistantMessage = memo(function AssistantMessage({
|
||||
content={msg.content}
|
||||
isStreaming={isStreaming}
|
||||
readingMaterialId={readingMaterialId}
|
||||
readingMaterialRevision={readingMaterialRevision}
|
||||
events={events}
|
||||
/>
|
||||
) : null}
|
||||
@@ -577,6 +581,7 @@ const AssistantMessage = memo(function AssistantMessage({
|
||||
content={seg.text}
|
||||
isStreaming={isStreaming}
|
||||
readingMaterialId={readingMaterialId}
|
||||
readingMaterialRevision={readingMaterialRevision}
|
||||
events={events}
|
||||
/>
|
||||
) : seg.kind === "trace" ? (
|
||||
@@ -603,6 +608,7 @@ const AssistantMessage = memo(function AssistantMessage({
|
||||
content={body}
|
||||
isStreaming={isStreaming}
|
||||
readingMaterialId={readingMaterialId}
|
||||
readingMaterialRevision={readingMaterialRevision}
|
||||
events={events}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -34,6 +34,7 @@ interface AssistantResponseProps {
|
||||
*/
|
||||
isStreaming?: boolean;
|
||||
readingMaterialId?: string;
|
||||
readingMaterialRevision?: number;
|
||||
events?: StreamEvent[];
|
||||
}
|
||||
|
||||
@@ -42,6 +43,7 @@ function AssistantResponseImpl({
|
||||
className = "text-[16px] leading-[1.75]",
|
||||
isStreaming = false,
|
||||
readingMaterialId,
|
||||
readingMaterialRevision,
|
||||
events,
|
||||
}: AssistantResponseProps) {
|
||||
const displayContent = useSmoothStreamText(content, isStreaming);
|
||||
@@ -52,8 +54,13 @@ function AssistantResponseImpl({
|
||||
const { material } = useReading();
|
||||
const watching = useWatching();
|
||||
const verifiedLocators = useMemo(
|
||||
() => verifiedReadingLocators(events, readingMaterialId),
|
||||
[events, readingMaterialId],
|
||||
() =>
|
||||
verifiedReadingLocators(
|
||||
events,
|
||||
readingMaterialId,
|
||||
readingMaterialRevision,
|
||||
),
|
||||
[events, readingMaterialId, readingMaterialRevision],
|
||||
);
|
||||
const citedContent = useMemo(() => {
|
||||
if (watching.active && watching.material) {
|
||||
@@ -61,15 +68,20 @@ function AssistantResponseImpl({
|
||||
}
|
||||
if (
|
||||
material?.unit === "segment" &&
|
||||
(!readingMaterialId || material.material_id === readingMaterialId)
|
||||
(!readingMaterialId || material.material_id === readingMaterialId) &&
|
||||
(!readingMaterialRevision ||
|
||||
material.revision === readingMaterialRevision)
|
||||
) {
|
||||
return linkifyMediaTimestamps(displayContent);
|
||||
}
|
||||
return readingMaterialId && verifiedLocators.size > 0
|
||||
? linkifyLocatorCitations(displayContent, {
|
||||
materialId: readingMaterialId,
|
||||
materialRevision: readingMaterialRevision,
|
||||
allowedLocators: verifiedLocators,
|
||||
...(material?.material_id === readingMaterialId
|
||||
...(material?.material_id === readingMaterialId &&
|
||||
(!readingMaterialRevision ||
|
||||
material.revision === readingMaterialRevision)
|
||||
? { maxLocator: material.unit_count }
|
||||
: {}),
|
||||
})
|
||||
@@ -78,6 +90,7 @@ function AssistantResponseImpl({
|
||||
displayContent,
|
||||
material,
|
||||
readingMaterialId,
|
||||
readingMaterialRevision,
|
||||
verifiedLocators,
|
||||
watching.active,
|
||||
watching.material,
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { citationTargetFromHref } from "@/lib/reading-citations";
|
||||
import {
|
||||
fetchExport,
|
||||
getMaterial,
|
||||
type AnnotationColor,
|
||||
type AnnotationItem,
|
||||
} from "@/lib/reading-api";
|
||||
@@ -168,13 +169,46 @@ export function ReaderPane({
|
||||
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;
|
||||
try {
|
||||
const candidate = await getMaterial(target.materialId);
|
||||
if (
|
||||
target.materialRevision &&
|
||||
candidate.revision !== target.materialRevision
|
||||
) {
|
||||
setError(
|
||||
"This citation points to an older material revision that is not available in the reader.",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
const opened = await openMaterial(candidate);
|
||||
if (!opened) return true;
|
||||
} catch (caught) {
|
||||
setError(
|
||||
caught instanceof Error
|
||||
? caught.message
|
||||
: "This citation's material could not be opened.",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} else if (
|
||||
target.materialRevision &&
|
||||
material?.revision !== target.materialRevision
|
||||
) {
|
||||
setError(
|
||||
"This citation points to an older material revision that is not available in the reader.",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
requestJump(target.locator);
|
||||
return true;
|
||||
},
|
||||
[material?.material_id, openMaterial, requestJump],
|
||||
[
|
||||
material?.material_id,
|
||||
material?.revision,
|
||||
openMaterial,
|
||||
requestJump,
|
||||
setError,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -100,7 +100,10 @@ export function ReadingProvider({ children }: { children: ReactNode }) {
|
||||
// reads when it sends. One effect rather than writes scattered through the
|
||||
// mutators, so the two can never disagree.
|
||||
useEffect(() => {
|
||||
setReadingMaterial(material?.material_id ?? null);
|
||||
setReadingMaterial(
|
||||
material?.material_id ?? null,
|
||||
material?.revision ?? null,
|
||||
);
|
||||
}, [material]);
|
||||
|
||||
const openMaterial = useCallback(
|
||||
|
||||
@@ -47,6 +47,7 @@ import { notify } from "@/lib/notifications";
|
||||
import { forwardReaderAction } from "@/lib/reading-reader-action";
|
||||
import {
|
||||
normalizeReadingMaterialId,
|
||||
normalizeReadingMaterialRevision,
|
||||
readingTurnFields,
|
||||
} from "@/lib/reading-turn-state";
|
||||
import { watchingTurnFields } from "@/lib/watching-turn-state";
|
||||
@@ -183,6 +184,8 @@ export interface MessageRequestSnapshot {
|
||||
llmSelection?: LLMSelection | null;
|
||||
/** Stable identity of the material open for this turn. */
|
||||
readingMaterialId?: string;
|
||||
/** Immutable content revision open when the turn was submitted. */
|
||||
readingMaterialRevision?: number;
|
||||
}
|
||||
|
||||
export interface MessageItem {
|
||||
@@ -1162,6 +1165,9 @@ function hydrateRequestSnapshot(
|
||||
const readingMaterialId = normalizeReadingMaterialId(
|
||||
stored.readingMaterialId ?? stored.reading_material_id,
|
||||
);
|
||||
const readingMaterialRevision = normalizeReadingMaterialRevision(
|
||||
stored.readingMaterialRevision ?? stored.reading_material_revision,
|
||||
);
|
||||
const timedMediaId =
|
||||
typeof (stored.timedMediaId ?? stored.timed_media_id) === "string"
|
||||
? String(stored.timedMediaId ?? stored.timed_media_id).trim()
|
||||
@@ -1184,6 +1190,9 @@ function hydrateRequestSnapshot(
|
||||
if (masteryPathId) snapshot.masteryPathId = masteryPathId;
|
||||
if (readingMaterialId) {
|
||||
snapshot.readingMaterialId = readingMaterialId;
|
||||
if (readingMaterialRevision) {
|
||||
snapshot.readingMaterialRevision = readingMaterialRevision;
|
||||
}
|
||||
}
|
||||
if (timedMediaId) snapshot.timedMediaId = timedMediaId;
|
||||
return snapshot;
|
||||
@@ -1816,6 +1825,9 @@ export function UnifiedChatProvider({
|
||||
const effectiveReadingMaterialId =
|
||||
replaySnapshot?.readingMaterialId ??
|
||||
liveReadingFields.reading_material_id;
|
||||
const effectiveReadingMaterialRevision =
|
||||
replaySnapshot?.readingMaterialRevision ??
|
||||
liveReadingFields.reading_material_revision;
|
||||
const liveWatchingFields = watchingTurnFields(effectiveCapability);
|
||||
const effectiveTimedMediaId =
|
||||
replaySnapshot?.timedMediaId ?? liveWatchingFields.timed_media_id;
|
||||
@@ -1864,6 +1876,9 @@ export function UnifiedChatProvider({
|
||||
...(effectiveReadingMaterialId
|
||||
? { readingMaterialId: effectiveReadingMaterialId }
|
||||
: {}),
|
||||
...(effectiveReadingMaterialId && effectiveReadingMaterialRevision
|
||||
? { readingMaterialRevision: effectiveReadingMaterialRevision }
|
||||
: {}),
|
||||
...(effectiveTimedMediaId
|
||||
? { timedMediaId: effectiveTimedMediaId }
|
||||
: {}),
|
||||
@@ -1945,7 +1960,15 @@ export function UnifiedChatProvider({
|
||||
// Read from a module cell rather than context state so scrolling the
|
||||
// reader never re-renders the chat.
|
||||
...(replaySnapshot?.readingMaterialId
|
||||
? { reading_material_id: replaySnapshot.readingMaterialId }
|
||||
? {
|
||||
reading_material_id: replaySnapshot.readingMaterialId,
|
||||
...(replaySnapshot.readingMaterialRevision
|
||||
? {
|
||||
reading_material_revision:
|
||||
replaySnapshot.readingMaterialRevision,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: liveReadingFields),
|
||||
...(replaySnapshot?.timedMediaId
|
||||
? { timed_media_id: replaySnapshot.timedMediaId }
|
||||
|
||||
@@ -43,6 +43,7 @@ const READING_EVIDENCE_TOOLS = new Set([
|
||||
|
||||
export interface ReadingCitationTarget {
|
||||
materialId?: string;
|
||||
materialRevision?: number;
|
||||
locator: number;
|
||||
}
|
||||
|
||||
@@ -224,12 +225,13 @@ export function linkifyLocatorCitations(
|
||||
options: {
|
||||
maxLocator?: number;
|
||||
materialId?: string;
|
||||
materialRevision?: number;
|
||||
allowedLocators?: Iterable<number>;
|
||||
} = {},
|
||||
): string {
|
||||
const citations = findLocatorCitations(text);
|
||||
if (!citations.length) return text;
|
||||
const { maxLocator, materialId } = options;
|
||||
const { maxLocator, materialId, materialRevision } = options;
|
||||
const allowed = options.allowedLocators
|
||||
? new Set(options.allowedLocators)
|
||||
: null;
|
||||
@@ -253,8 +255,12 @@ export function linkifyLocatorCitations(
|
||||
continue;
|
||||
}
|
||||
|
||||
const revisionAddress =
|
||||
Number.isSafeInteger(materialRevision) && Number(materialRevision) >= 1
|
||||
? `-revision-${materialRevision}`
|
||||
: "";
|
||||
const href = materialId
|
||||
? `${MATERIAL_LOCATOR_HREF_PREFIX}${encodeURIComponent(materialId)}-locator-${locators[0]}`
|
||||
? `${MATERIAL_LOCATOR_HREF_PREFIX}${encodeURIComponent(materialId)}${revisionAddress}-locator-${locators[0]}`
|
||||
: `${LOCATOR_HREF_PREFIX}${locators[0]}`;
|
||||
const absorbed =
|
||||
locators.length === citation.locators.length
|
||||
@@ -297,25 +303,33 @@ export function citationTargetFromHref(
|
||||
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);
|
||||
const match =
|
||||
/^#dt-material-([0-9a-f]{8,64})(?:-revision-(\d+))?-locator-(\d+)$/i.exec(
|
||||
href,
|
||||
);
|
||||
if (!match) return null;
|
||||
const locator = Number(match[2]);
|
||||
let materialId = "";
|
||||
try {
|
||||
materialId = decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
const materialRevision = match[2] ? Number(match[2]) : undefined;
|
||||
const locator = Number(match[3]);
|
||||
const materialId = match[1];
|
||||
if (!Number.isSafeInteger(locator) || locator < 1) return null;
|
||||
if (
|
||||
materialRevision !== undefined &&
|
||||
(!Number.isSafeInteger(materialRevision) || materialRevision < 1)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (!/^[0-9a-f]{8,64}$/i.test(materialId)) return null;
|
||||
return Number.isInteger(locator) && locator >= 1
|
||||
? { materialId: materialId.toLowerCase(), locator }
|
||||
: null;
|
||||
return {
|
||||
materialId: materialId.toLowerCase(),
|
||||
...(materialRevision !== undefined ? { materialRevision } : {}),
|
||||
locator,
|
||||
};
|
||||
}
|
||||
|
||||
/** Locators grounded by successful reading-tool results for one turn. */
|
||||
export function verifiedReadingLocators(
|
||||
events: ReadingEvidenceEvent[] | null | undefined,
|
||||
materialId: string | null | undefined,
|
||||
materialRevision?: number | null,
|
||||
): Set<number> {
|
||||
const verified = new Set<number>();
|
||||
if (!materialId) return verified;
|
||||
@@ -331,6 +345,10 @@ export function verifiedReadingLocators(
|
||||
if (!nested || typeof nested !== "object") continue;
|
||||
const metadata = nested as Record<string, unknown>;
|
||||
if (String(metadata.material_id ?? "").toLowerCase() !== expected) continue;
|
||||
if (materialRevision) {
|
||||
const evidenceRevision = Number(metadata.material_revision);
|
||||
if (evidenceRevision !== materialRevision) continue;
|
||||
}
|
||||
const add = (value: unknown) => {
|
||||
const locator = Number(value);
|
||||
if (Number.isInteger(locator) && locator >= 1) verified.add(locator);
|
||||
|
||||
@@ -22,6 +22,7 @@ export { READING_WORKSPACE_MODE };
|
||||
export interface ReadingTurnState {
|
||||
workspaceId: string | null;
|
||||
materialId: string | null;
|
||||
materialRevision: number | null;
|
||||
locator: number;
|
||||
selection: string;
|
||||
timeSeconds: number | null;
|
||||
@@ -30,6 +31,7 @@ export interface ReadingTurnState {
|
||||
const state: ReadingTurnState = {
|
||||
workspaceId: null,
|
||||
materialId: null,
|
||||
materialRevision: null,
|
||||
locator: 0,
|
||||
selection: "",
|
||||
timeSeconds: null,
|
||||
@@ -42,18 +44,33 @@ export function normalizeReadingMaterialId(value: unknown): string | null {
|
||||
return /^[0-9a-f]{8,64}$/.test(normalized) ? normalized : null;
|
||||
}
|
||||
|
||||
/** Normalize an immutable ReadingStore content revision from wire/storage. */
|
||||
export function normalizeReadingMaterialRevision(
|
||||
value: unknown,
|
||||
): number | null {
|
||||
const revision = typeof value === "number" ? value : Number(value);
|
||||
return Number.isSafeInteger(revision) && revision >= 1 ? revision : null;
|
||||
}
|
||||
|
||||
export function setReadingWorkspace(workspaceId: string | null): void {
|
||||
state.workspaceId = workspaceId;
|
||||
if (!workspaceId) {
|
||||
state.materialId = null;
|
||||
state.materialRevision = null;
|
||||
state.locator = 0;
|
||||
state.selection = "";
|
||||
state.timeSeconds = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setReadingMaterial(materialId: string | null): void {
|
||||
export function setReadingMaterial(
|
||||
materialId: string | null,
|
||||
materialRevision: number | null = null,
|
||||
): void {
|
||||
state.materialId = materialId;
|
||||
state.materialRevision = materialId
|
||||
? normalizeReadingMaterialRevision(materialRevision)
|
||||
: null;
|
||||
if (!materialId) {
|
||||
// Closing a document must not leave its viewport behind: the next turn
|
||||
// would tell the model the user is looking at a page of a closed file.
|
||||
@@ -108,6 +125,7 @@ export function readingTurnFields(
|
||||
): {
|
||||
reading_workspace_id?: string;
|
||||
reading_material_id?: string;
|
||||
reading_material_revision?: number;
|
||||
reading_viewport?: {
|
||||
locator?: number;
|
||||
selection?: string;
|
||||
@@ -126,6 +144,9 @@ export function readingTurnFields(
|
||||
return {
|
||||
...(state.workspaceId ? { reading_workspace_id: state.workspaceId } : {}),
|
||||
...(state.materialId ? { reading_material_id: state.materialId } : {}),
|
||||
...(state.materialId && state.materialRevision
|
||||
? { reading_material_revision: state.materialRevision }
|
||||
: {}),
|
||||
...(Object.keys(viewport).length ? { reading_viewport: viewport } : {}),
|
||||
};
|
||||
}
|
||||
@@ -134,6 +155,7 @@ export function readingTurnFields(
|
||||
export function resetReadingTurnState(): void {
|
||||
state.workspaceId = null;
|
||||
state.materialId = null;
|
||||
state.materialRevision = null;
|
||||
state.locator = 0;
|
||||
state.selection = "";
|
||||
state.timeSeconds = null;
|
||||
|
||||
@@ -95,6 +95,8 @@ export interface StartTurnMessage {
|
||||
/** Immersive reading: the document open in the reader pane, if any. Its
|
||||
* presence is what activates the reading capability for the turn. */
|
||||
reading_material_id?: string;
|
||||
/** Immutable content revision displayed when this turn was submitted. */
|
||||
reading_material_revision?: number;
|
||||
/** What the reader is showing right now — the locator on screen and any text
|
||||
* the user has selected. Advisory context, not a citation. */
|
||||
reading_viewport?: {
|
||||
|
||||
@@ -17,6 +17,7 @@ function material(materialId: string, title: string) {
|
||||
created_at: 1,
|
||||
has_raw_view: false,
|
||||
render_mode: "text",
|
||||
revision: 4,
|
||||
annotation_count: 0,
|
||||
outline: [],
|
||||
outline_text: "",
|
||||
@@ -83,6 +84,7 @@ test.beforeEach(async ({ page }) => {
|
||||
knowledgeBases: [],
|
||||
language: "en",
|
||||
readingMaterialId: MATERIAL_A,
|
||||
readingMaterialRevision: 4,
|
||||
},
|
||||
},
|
||||
created_at: 1,
|
||||
@@ -108,6 +110,7 @@ test.beforeEach(async ({ page }) => {
|
||||
tool: "read_material",
|
||||
tool_metadata: {
|
||||
material_id: MATERIAL_A,
|
||||
material_revision: 4,
|
||||
locators: [2],
|
||||
},
|
||||
},
|
||||
@@ -159,7 +162,7 @@ test("historical citation reopens its turn material and unsupported locator stay
|
||||
|
||||
await expect(page.getByRole("link", { name: "p.2" })).toHaveAttribute(
|
||||
"href",
|
||||
`#dt-material-${MATERIAL_A}-locator-2`,
|
||||
`#dt-material-${MATERIAL_A}-revision-4-locator-2`,
|
||||
);
|
||||
await expect(page.getByRole("link", { name: "p.1" })).toHaveCount(0);
|
||||
|
||||
|
||||
@@ -191,6 +191,16 @@ test("locatorFromHref only accepts the reader's own anchors", () => {
|
||||
});
|
||||
|
||||
test("citationTargetFromHref restores material-aware and legacy targets", () => {
|
||||
assert.deepEqual(
|
||||
citationTargetFromHref(
|
||||
"#dt-material-0123456789ABCDEF-revision-4-locator-12",
|
||||
),
|
||||
{
|
||||
materialId: "0123456789abcdef",
|
||||
materialRevision: 4,
|
||||
locator: 12,
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
citationTargetFromHref("#dt-material-0123456789ABCDEF-locator-12"),
|
||||
{ materialId: "0123456789abcdef", locator: 12 },
|
||||
@@ -202,6 +212,23 @@ test("citationTargetFromHref restores material-aware and legacy targets", () =>
|
||||
citationTargetFromHref("#dt-material-not-an-id-locator-3"),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
citationTargetFromHref(
|
||||
"#dt-material-0123456789abcdef-revision-0-locator-3",
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("linkify binds material-aware citations to an immutable revision", () => {
|
||||
assert.equal(
|
||||
linkifyLocatorCitations("Grounded [p.12].", {
|
||||
materialId: "0123456789abcdef",
|
||||
materialRevision: 4,
|
||||
allowedLocators: [12],
|
||||
}),
|
||||
"Grounded [p.12](#dt-material-0123456789abcdef-revision-4-locator-12).",
|
||||
);
|
||||
});
|
||||
|
||||
test("verifiedReadingLocators uses only matching reading-tool evidence", () => {
|
||||
@@ -213,6 +240,7 @@ test("verifiedReadingLocators uses only matching reading-tool evidence", () => {
|
||||
tool: "search_material",
|
||||
tool_metadata: {
|
||||
material_id: materialId,
|
||||
material_revision: 4,
|
||||
hits: [{ locator: 12 }, { locator: 17 }],
|
||||
},
|
||||
},
|
||||
@@ -221,14 +249,22 @@ test("verifiedReadingLocators uses only matching reading-tool evidence", () => {
|
||||
type: "tool_result",
|
||||
metadata: {
|
||||
tool: "read_material",
|
||||
tool_metadata: { material_id: materialId, locators: [12, 13] },
|
||||
tool_metadata: {
|
||||
material_id: materialId,
|
||||
material_revision: 4,
|
||||
locators: [12, 13],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "tool_result",
|
||||
metadata: {
|
||||
tool: "reader_goto",
|
||||
tool_metadata: { material_id: materialId, locator: 14 },
|
||||
tool_metadata: {
|
||||
material_id: materialId,
|
||||
material_revision: 4,
|
||||
locator: 14,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -250,9 +286,10 @@ test("verifiedReadingLocators uses only matching reading-tool evidence", () => {
|
||||
},
|
||||
];
|
||||
assert.deepEqual(
|
||||
[...verifiedReadingLocators(events, materialId)].sort((a, b) => a - b),
|
||||
[...verifiedReadingLocators(events, materialId, 4)].sort((a, b) => a - b),
|
||||
[12, 13, 14, 17],
|
||||
);
|
||||
assert.deepEqual([...verifiedReadingLocators(events, materialId, 3)], []);
|
||||
assert.deepEqual([...verifiedReadingLocators([], materialId)], []);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
READING_WORKSPACE_MODE,
|
||||
getReadingTurnState,
|
||||
normalizeReadingMaterialId,
|
||||
normalizeReadingMaterialRevision,
|
||||
readingTurnFields,
|
||||
resetReadingTurnState,
|
||||
setReadingMaterial,
|
||||
@@ -23,12 +24,21 @@ test("normalizes persisted reading material ids and rejects unsafe values", () =
|
||||
assert.equal(normalizeReadingMaterialId(null), null);
|
||||
});
|
||||
|
||||
test("normalizes immutable material revisions", () => {
|
||||
assert.equal(normalizeReadingMaterialRevision(3), 3);
|
||||
assert.equal(normalizeReadingMaterialRevision("4"), 4);
|
||||
assert.equal(normalizeReadingMaterialRevision(0), null);
|
||||
assert.equal(normalizeReadingMaterialRevision(1.5), null);
|
||||
assert.equal(normalizeReadingMaterialRevision("nope"), null);
|
||||
});
|
||||
|
||||
test("carries the document and viewport for every action inside reading", () => {
|
||||
setReadingMaterial("d138eacaad029843");
|
||||
setReadingMaterial("d138eacaad029843", 4);
|
||||
setReadingViewport({ locator: 3, selection: "attention" });
|
||||
|
||||
assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {
|
||||
reading_material_id: "d138eacaad029843",
|
||||
reading_material_revision: 4,
|
||||
reading_viewport: { locator: 3, selection: "attention" },
|
||||
});
|
||||
});
|
||||
@@ -86,6 +96,7 @@ test("closing the document clears its viewport too", () => {
|
||||
assert.deepEqual(getReadingTurnState(), {
|
||||
workspaceId: null,
|
||||
materialId: null,
|
||||
materialRevision: null,
|
||||
locator: 0,
|
||||
selection: "",
|
||||
timeSeconds: null,
|
||||
@@ -106,6 +117,7 @@ test("carries the private workspace and clears it independently", () => {
|
||||
assert.deepEqual(getReadingTurnState(), {
|
||||
workspaceId: null,
|
||||
materialId: null,
|
||||
materialRevision: null,
|
||||
locator: 0,
|
||||
selection: "",
|
||||
timeSeconds: null,
|
||||
|
||||
Reference in New Issue
Block a user