DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): add session-scoped cross-material navigation history
XZH55bb5f7c1303
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsxindex d16ad6b35..ca9e9aec6 100644--- a/web/components/reading/ReaderPane.tsx+++ b/web/components/reading/ReaderPane.tsx@@ -2,11 +2,13 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {+ ArrowLeft,+ ArrowRight,Crosshair,Download,FileText,- List,Loader2,+ History,PanelRightClose,PanelRightOpen,X,@@ -24,6 +26,7 @@ import {getMaterial,type AnnotationColor,type AnnotationItem,+ type MaterialDetail,} from "@/lib/reading-api";import { AnnotationList } from "./AnnotationList";import { AnnotationPopover } from "./AnnotationPopover";@@ -36,13 +39,42 @@ import {import { ReadingExtensionBar } from "./ReadingExtensionBar";import { TextUnitView, unitLabel } from "./TextUnitView";import type { ReaderHeading } from "@/lib/reading-outline";+import {+ EMPTY_READING_HISTORY,+ loadReadingHistory,+ moveReadingHistory,+ pushReadingLocation,+ replaceCurrentReadingLocation,+ saveReadingHistory,+ selectReadingHistoryIndex,+ type ReadingLocationEntry,+ type ReadingLocationHistory,+} from "@/lib/reading-location-history";/** Event the reader dispatches to prefill the composer from a selection. */export const READER_ASK_EVENT = "dt:reader-ask";const AUTO_JUMP_KEY = "dt.reader.autoJump";+function locationEntry(+ material: MaterialDetail,+ locator: number,+): ReadingLocationEntry {+ return {+ materialId: material.material_id,+ locator,+ title: material.title || material.filename,+ source: {+ filename: material.filename,+ unit: material.unit,+ mime: material.mime,+ renderMode: material.render_mode,+ },+ };+}+export interface ReaderPaneProps {onClose: () => void;+ sessionId?: string | null;/** User-owned navigation from the workspace's source outline. */externalJump?: JumpRequest | null;/**@@ -82,6 +114,7 @@ export interface ReaderPaneProps {*/export function ReaderPane({onClose,+ sessionId,externalJump = null,onHeadingsChange,onActiveHeadingChange,@@ -119,6 +152,29 @@ export function ReaderPane({const [exporting, setExporting] = useState(false);const [currentLocator, setCurrentLocator] = useState(1);const nonceRef = useRef(0);+ const headingLocatorRef = useRef(1);+ const jumpMaterialIdRef = useRef<string | null>(null);+ const [locationHistory, setLocationHistory] =+ useState<ReadingLocationHistory>(EMPTY_READING_HISTORY);+ const [historySessionId, setHistorySessionId] = useState<+ string | null | undefined+ >(undefined);+ const [showHistory, setShowHistory] = useState(false);+ const [unavailableMaterials, setUnavailableMaterials] = useState<Set<string>>(+ new Set(),+ );+ const navigationNonceRef = useRef(0);+ const pendingNavigationRef = useRef<{+ mode: "push" | "replay";+ materialId: string;+ locator: number;+ } | null>(null);+ const historyRestoreAttemptRef = useRef<{+ sessionId: string | null;+ } | null>(null);+ const externalJumpNonceRef = useRef(0);+ const headingJumpNonceRef = useRef(0);+ const historyReady = historySessionId === (sessionId ?? null);// -- persisted auto-jump preference --------------------------------------@@ -149,8 +205,24 @@ export function ReaderPane({(locator: number) => {setCurrentLocator(locator);reportViewport({ locator });+ if (material && historyReady) {+ const pending = pendingNavigationRef.current;+ if (+ pending?.materialId === material.material_id &&+ pending.locator !== locator+ ) {+ return;+ }+ setLocationHistory((current) => {+ const entry = locationEntry(material, locator);+ return current.entries[current.index]?.materialId ===+ material.material_id+ ? replaceCurrentReadingLocation(current, entry)+ : pushReadingLocation(current, entry);+ });+ }},- [reportViewport],+ [historyReady, material, reportViewport],);useEffect(() => {@@ -159,10 +231,142 @@ export function ReaderPane({// -- reader actions from the assistant ------------------------------------ const requestJump = useCallback((locator: number, quote?: string) => {- nonceRef.current += 1;- setJump({ locator, quote, nonce: nonceRef.current });- }, []);+ const requestJump = useCallback(+ (locator: number, quote?: string, targetMaterialId?: string) => {+ nonceRef.current += 1;+ setJump({ locator, quote, nonce: nonceRef.current });+ jumpMaterialIdRef.current =+ targetMaterialId ?? material?.material_id ?? null;+ },+ [material?.material_id],+ );++ const rememberExplicitLocation = useCallback(+ (locator: number) => {+ if (!material || !historyReady) return;+ setLocationHistory((current) =>+ pushReadingLocation(current, locationEntry(material, locator)),+ );+ },+ [historyReady, material],+ );++ const openHistoryEntry = useCallback(+ async (+ entry: ReadingLocationEntry,+ mode: "push" | "replay",+ forceOpen = false,+ candidate?: MaterialDetail,+ ) => {+ const navigationNonce = ++navigationNonceRef.current;+ if (forceOpen || entry.materialId !== material?.material_id) {+ setJump(null);+ pendingNavigationRef.current = {+ mode,+ materialId: entry.materialId,+ locator: entry.locator,+ };+ const opened = await openMaterial(candidate ?? entry.materialId);+ if (navigationNonce !== navigationNonceRef.current) return false;+ if (!opened) {+ setUnavailableMaterials((current) =>+ new Set(current).add(entry.materialId),+ );+ pendingNavigationRef.current = null;+ return false;+ }+ } else {+ pendingNavigationRef.current = null;+ }+ setUnavailableMaterials((current) => {+ if (!current.has(entry.materialId)) return current;+ const next = new Set(current);+ next.delete(entry.materialId);+ return next;+ });+ requestJump(entry.locator, undefined, entry.materialId);+ return true;+ },+ [material?.material_id, openMaterial, requestJump],+ );++ const selectHistoryEntry = useCallback(+ (index: number) => {+ const next = selectReadingHistoryIndex(locationHistory, index);+ const entry = next.entries[next.index];+ if (!entry) return;+ setLocationHistory(next);+ setShowHistory(false);+ void openHistoryEntry(entry, "replay");+ },+ [locationHistory, openHistoryEntry],+ );++ const stepHistory = useCallback(+ (delta: -1 | 1) => {+ const next = moveReadingHistory(locationHistory, delta);+ if (next.index === locationHistory.index) return;+ const entry = next.entries[next.index];+ if (!entry) return;+ setLocationHistory(next);+ void openHistoryEntry(entry, "replay");+ },+ [locationHistory, openHistoryEntry],+ );++ useEffect(() => {+ const scopedSessionId = sessionId ?? null;+ if (loadingMaterial) return;+ if (!material) return;+ if (historyRestoreAttemptRef.current?.sessionId === scopedSessionId) {+ return;+ }+ historyRestoreAttemptRef.current = { sessionId: scopedSessionId };+ const hadPendingNavigation = pendingNavigationRef.current !== null;+ navigationNonceRef.current += 1;+ pendingNavigationRef.current = null;+ const restored = scopedSessionId+ ? loadReadingHistory(scopedSessionId)+ : EMPTY_READING_HISTORY;+ setLocationHistory(restored);+ setUnavailableMaterials(new Set());+ setHistorySessionId(sessionId ?? null);+ const entry = restored.entries[restored.index];+ if (entry) void openHistoryEntry(entry, "replay", hadPendingNavigation);+ else if (hadPendingNavigation) closeMaterial();+ // Restore once per chat id. Material changes caused by the restore must not+ // restart it with a newly-created callback closure.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sessionId, loadingMaterial]);++ useEffect(() => {+ if (!historyReady || !sessionId || historySessionId !== sessionId) return;+ saveReadingHistory(sessionId, locationHistory);+ }, [historyReady, historySessionId, locationHistory, sessionId]);++ useEffect(() => {+ if (!historyReady || !material) return;+ const pending = pendingNavigationRef.current;+ if (pending?.materialId === material.material_id) {+ pendingNavigationRef.current = null;+ setCurrentLocator(pending.locator);+ if (pending.mode === "push") {+ setLocationHistory((current) =>+ pushReadingLocation(+ current,+ locationEntry(material, pending.locator),+ ),+ );+ }+ return;+ }+ if (pending) return;+ setJump(null);+ setCurrentLocator(1);+ setLocationHistory((current) =>+ pushReadingLocation(current, locationEntry(material, 1)),+ );+ }, [historyReady, material]);const navigateCitation = useCallback(async (href: string | null | undefined) => {@@ -180,8 +384,8 @@ export function ReaderPane({);return true;}- const opened = await openMaterial(candidate);- if (!opened) return true;+ const entry = locationEntry(candidate, target.locator);+ await openHistoryEntry(entry, "push", false, candidate);} catch (caught) {setError(caught instanceof Error@@ -199,13 +403,15 @@ export function ReaderPane({);return true;}+ rememberExplicitLocation(target.locator);requestJump(target.locator);return true;},[material?.material_id,material?.revision,- openMaterial,+ openHistoryEntry,+ rememberExplicitLocation,requestJump,setError,],@@ -213,8 +419,22 @@ export function ReaderPane({useEffect(() => {if (!externalJump) return;+ if (externalJumpNonceRef.current === externalJump.nonce) return;+ externalJumpNonceRef.current = externalJump.nonce;+ rememberExplicitLocation(externalJump.locator);requestJump(externalJump.locator, externalJump.quote);- }, [externalJump, requestJump]);+ }, [externalJump, rememberExplicitLocation, requestJump]);++ useEffect(() => {+ headingLocatorRef.current = currentLocator;+ }, [currentLocator]);++ useEffect(() => {+ if (!headingJump) return;+ if (headingJumpNonceRef.current === headingJump.nonce) return;+ headingJumpNonceRef.current = headingJump.nonce;+ rememberExplicitLocation(headingJump.locator ?? headingLocatorRef.current);+ }, [headingJump, rememberExplicitLocation]);useEffect(() => {const onReaderAction = (event: Event) => {@@ -233,12 +453,15 @@ export function ReaderPane({}if (!autoJump) return;const locator = Number(detail.locator ?? 0);- if (locator >= 1) requestJump(locator, detail.quote || undefined);+ if (locator >= 1) {+ rememberExplicitLocation(locator);+ requestJump(locator, detail.quote || undefined);+ }};window.addEventListener(READER_ACTION_EVENT, onReaderAction);return () =>window.removeEventListener(READER_ACTION_EVENT, onReaderAction);- }, [material, autoJump, requestJump, mergeMark]);+ }, [material, autoJump, requestJump, mergeMark, rememberExplicitLocation]);/*** Follow the answer when the model did not move the reader itself.@@ -390,6 +613,10 @@ export function ReaderPane({const showAnnotations = annotationPanel ?? annotations.length > 0;const unitWord = material ? t(unitLabel(material.unit)) : "";+ const materialJump =+ material && jumpMaterialIdRef.current === material.material_id+ ? jump+ : null;return (<div className="relative flex h-full min-w-0 flex-col border-r border-[var(--border)] bg-[var(--background)]">@@ -405,6 +632,32 @@ export function ReaderPane({{material?.filename ?? t("Immersive reading")}</span>+ {locationHistory.entries.length > 0 && (+ <>+ <HeaderButton+ icon={ArrowLeft}+ label={t("Back")}+ disabled={locationHistory.index <= 0}+ onClick={() => stepHistory(-1)}+ />+ <HeaderButton+ icon={ArrowRight}+ label={t("Forward")}+ disabled={+ locationHistory.index < 0 ||+ locationHistory.index >= locationHistory.entries.length - 1+ }+ onClick={() => stepHistory(1)}+ />+ <HeaderButton+ icon={History}+ label={t("History")}+ active={showHistory}+ onClick={() => setShowHistory((current) => !current)}+ />+ </>+ )}+{material && (<><span className="shrink-0 font-mono text-[10.5px] tabular-nums text-[var(--muted-foreground)]">@@ -442,6 +695,43 @@ export function ReaderPane({)}</header>+ {showHistory && locationHistory.entries.length > 0 && (+ <div className="absolute top-11 right-2 z-30 max-h-72 w-72 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl">+ {[...locationHistory.entries]+ .map((entry, index) => ({ entry, index }))+ .reverse()+ .map(({ entry, index }) => {+ const unavailable = unavailableMaterials.has(entry.materialId);+ return (+ <button+ key={`${entry.materialId}:${entry.locator}:${index}`}+ type="button"+ aria-current={+ index === locationHistory.index ? "location" : undefined+ }+ onClick={() => selectHistoryEntry(index)}+ className={`flex w-full items-start gap-2 rounded-lg px-2.5 py-2 text-left transition hover:bg-[var(--muted)] ${+ index === locationHistory.index+ ? "bg-[var(--primary)]/10 text-[var(--primary)]"+ : "text-[var(--foreground)]"+ }`}+ >+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[11.5px] font-medium">+ {entry.title}+ </span>+ <span className="block truncate font-mono text-[10px] text-[var(--muted-foreground)]">+ {t(unitLabel(entry.source?.unit || "section"))}{" "}+ {entry.locator}+ {unavailable ? ` · ${t("Unavailable")}` : ""}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ )}+{notice && (<divrole="alert"@@ -492,11 +782,12 @@ export function ReaderPane({</div>) : material.render_mode === "epub" ? (<EpubDocumentView+ key={material.material_id}materialId={material.material_id}unitCount={material.unit_count}unitRefs={material.unit_refs}annotations={annotations}- jump={jump}+ jump={materialJump}highlightedAnnotationId={activeAnnotationId}onSelection={setSelection}onAnnotationClick={(annotation) =>@@ -509,10 +800,11 @@ export function ReaderPane({/>) : material.has_raw_view ? (<PdfDocumentView+ key={material.material_id}materialId={material.material_id}unitCount={material.unit_count}annotations={annotations}- jump={jump}+ jump={materialJump}highlightedAnnotationId={activeAnnotationId}onSelection={setSelection}onAnnotationClick={(annotation) =>@@ -522,12 +814,13 @@ export function ReaderPane({/>) : (<TextUnitView+ key={material.material_id}materialId={material.material_id}unit={material.unit}unitCount={material.unit_count}contentFormat={material.content_format}annotations={annotations}- jump={jump}+ jump={materialJump}highlightedAnnotationId={activeAnnotationId}onSelection={setSelection}onAnnotationClick={(annotation) =>@@ -579,6 +872,7 @@ function HeaderButton({onClick,active,spinning,+ disabled,className = "",}: {icon: typeof FileText;@@ -586,6 +880,7 @@ function HeaderButton({onClick: () => void;active?: boolean;spinning?: boolean;+ disabled?: boolean;className?: string;}) {return (@@ -594,14 +889,14 @@ function HeaderButton({title={label}aria-label={label}aria-pressed={active}- disabled={spinning}+ disabled={spinning || disabled}onClick={onClick}className={`h-7 w-7 shrink-0 items-center justify-center rounded-lg transition disabled:cursor-default ${className || "inline-flex"} ${active? "bg-[var(--primary)]/12 text-[var(--primary)]"- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-35 disabled:hover:bg-transparent"}`}><Icon size={14} className={spinning ? "animate-spin" : undefined} />diff --git a/web/components/reading/workspace/ReadingWorkspace.tsx b/web/components/reading/workspace/ReadingWorkspace.tsxindex bbc4e599a..5d668b591 100644--- a/web/components/reading/workspace/ReadingWorkspace.tsx+++ b/web/components/reading/workspace/ReadingWorkspace.tsx@@ -592,6 +592,7 @@ export function ReadingWorkspacePage() {) : (<div className="h-full [&>div]:border-r-0"><ReaderPane+ sessionId={state.sessionId ?? sessionIdParam}externalJump={documentJump}onHeadingsChange={setPageHeadings}onActiveHeadingChange={setActiveHeadingId}diff --git a/web/lib/reading-location-history.ts b/web/lib/reading-location-history.tsnew file mode 100644index 000000000..cb32d43b5--- /dev/null+++ b/web/lib/reading-location-history.ts@@ -0,0 +1,203 @@+import type { UnitKind } from "@/lib/reading-api";++export const READING_HISTORY_LIMIT = 50;+const STORAGE_PREFIX = "dt.reader.history.";++export interface ReadingLocationSource {+ filename?: string;+ unit?: UnitKind;+ mime?: string;+ renderMode?: string;+}++export interface ReadingLocationEntry {+ materialId: string;+ locator: number;+ title: string;+ source?: ReadingLocationSource;+}++export interface ReadingLocationHistory {+ entries: ReadingLocationEntry[];+ index: number;+}++export const EMPTY_READING_HISTORY: ReadingLocationHistory = {+ entries: [],+ index: -1,+};++function normalizeEntry(value: unknown): ReadingLocationEntry | null {+ if (!value || typeof value !== "object") return null;+ const row = value as Record<string, unknown>;+ const materialId = String(row.materialId ?? "")+ .trim()+ .toLowerCase();+ const locator = Number(row.locator);+ if (!/^[0-9a-f]{8,64}$/.test(materialId)) return null;+ if (!Number.isInteger(locator) || locator < 1) return null;+ const rawSource =+ row.source && typeof row.source === "object"+ ? (row.source as Record<string, unknown>)+ : null;+ const unit =+ rawSource &&+ typeof rawSource.unit === "string" &&+ ["page", "chapter", "slide", "section"].includes(rawSource.unit)+ ? (rawSource.unit as UnitKind)+ : undefined;+ const source = rawSource+ ? {+ ...(typeof rawSource.filename === "string"+ ? { filename: rawSource.filename }+ : {}),+ ...(unit ? { unit } : {}),+ ...(typeof rawSource.mime === "string" ? { mime: rawSource.mime } : {}),+ ...(typeof rawSource.renderMode === "string"+ ? { renderMode: rawSource.renderMode }+ : {}),+ }+ : undefined;+ return {+ materialId,+ locator,+ title:+ typeof row.title === "string" && row.title.trim()+ ? row.title.trim()+ : source?.filename || materialId,+ ...(source && Object.keys(source).length ? { source } : {}),+ };+}++function sameLocation(+ a: ReadingLocationEntry,+ b: ReadingLocationEntry,+): boolean {+ return a.materialId === b.materialId && a.locator === b.locator;+}++export function pushReadingLocation(+ history: ReadingLocationHistory,+ entry: ReadingLocationEntry,+): ReadingLocationHistory {+ const normalized = normalizeEntry(entry);+ if (!normalized) return history;+ const current = history.entries[history.index];+ if (current && sameLocation(current, normalized)) {+ const entries = [...history.entries];+ entries[history.index] = normalized;+ return { entries, index: history.index };+ }+ const entries = [...history.entries.slice(0, history.index + 1), normalized];+ const trimmed = entries.slice(-READING_HISTORY_LIMIT);+ return { entries: trimmed, index: trimmed.length - 1 };+}++/** Manual scroll updates the current location without creating history noise. */+export function replaceCurrentReadingLocation(+ history: ReadingLocationHistory,+ entry: ReadingLocationEntry,+): ReadingLocationHistory {+ const normalized = normalizeEntry(entry);+ if (!normalized) return history;+ if (history.index < 0 || !history.entries[history.index]) {+ return pushReadingLocation(history, normalized);+ }+ const entries = [...history.entries];+ entries[history.index] = normalized;+ return { entries, index: history.index };+}++export function moveReadingHistory(+ history: ReadingLocationHistory,+ delta: -1 | 1,+): ReadingLocationHistory {+ const index = Math.max(+ 0,+ Math.min(history.entries.length - 1, history.index + delta),+ );+ return history.entries.length ? { ...history, index } : history;+}++export function selectReadingHistoryIndex(+ history: ReadingLocationHistory,+ index: number,+): ReadingLocationHistory {+ if (+ !Number.isInteger(index) ||+ index < 0 ||+ index >= history.entries.length+ ) {+ return history;+ }+ return { ...history, index };+}++export function parseReadingHistory(+ value: string | null,+): ReadingLocationHistory {+ if (!value) return EMPTY_READING_HISTORY;+ try {+ const parsed = JSON.parse(value) as Record<string, unknown>;+ const rawEntries = Array.isArray(parsed.entries) ? parsed.entries : [];+ const normalized: Array<{+ entry: ReadingLocationEntry;+ firstRawIndex: number;+ }> = [];+ rawEntries.forEach((value, rawIndex) => {+ const entry = normalizeEntry(value);+ if (!entry) return;+ const previous = normalized[normalized.length - 1];+ if (previous && sameLocation(previous.entry, entry)) {+ previous.entry = entry;+ return;+ }+ normalized.push({ entry, firstRawIndex: rawIndex });+ });+ if (!normalized.length) return EMPTY_READING_HISTORY;++ const rawIndex = Number(parsed.index);+ const selected = Number.isInteger(rawIndex)+ ? normalized.findLastIndex((row) => row.firstRawIndex <= rawIndex)+ : normalized.length - 1;+ const trimStart = Math.max(0, normalized.length - READING_HISTORY_LIMIT);+ const entries = normalized.slice(trimStart).map(({ entry }) => entry);+ const index = Math.max(+ 0,+ Math.min(entries.length - 1, Math.max(0, selected) - trimStart),+ );+ return { entries, index };+ } catch {+ return EMPTY_READING_HISTORY;+ }+}++export function readingHistoryStorageKey(sessionId: string): string {+ return `${STORAGE_PREFIX}${encodeURIComponent(sessionId)}`;+}++export function loadReadingHistory(sessionId: string): ReadingLocationHistory {+ if (!sessionId || typeof window === "undefined") return EMPTY_READING_HISTORY;+ try {+ return parseReadingHistory(+ window.localStorage.getItem(readingHistoryStorageKey(sessionId)),+ );+ } catch {+ return EMPTY_READING_HISTORY;+ }+}++export function saveReadingHistory(+ sessionId: string,+ history: ReadingLocationHistory,+): void {+ if (!sessionId || typeof window === "undefined") return;+ try {+ window.localStorage.setItem(+ readingHistoryStorageKey(sessionId),+ JSON.stringify(history),+ );+ } catch {+ // Storage may be unavailable or full; navigation still works in memory.+ }+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 9d7d5bd8f..adbe2d688 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1340,6 +1340,8 @@"settingsTour.apply.desc": "Save Draft persists your changes; Apply activates them right away. Both controls live in the top toolbar, always within reach.","Step {{current}} of {{total}}": "Step {{current}} of {{total}}","Back": "Back",+ "Forward": "Forward",+ "Unavailable": "Unavailable","settings.configNote": "Save Draft persists all profiles to model_catalog.json, which DeepTutor reads at runtime. Apply activates the selected profile and refreshes runtime clients. You can keep multiple profiles in the catalog and switch between them anytime.","Unsupported file type": "Unsupported file type","No extension": "No extension",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 923536e82..d3ff2d9d9 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1370,6 +1370,8 @@"settingsTour.tools.desc": "在此开关用户可自选的工具;锁定工具会在 chat agent 需要时自动挂载。","Step {{current}} of {{total}}": "第 {{current}} / {{total}} 步","Back": "上一步",+ "Forward": "下一步",+ "Unavailable": "不可用","Switch user-toggleable tools on or off. Locked tools are mounted automatically when the chat agent needs them.": "在此开关用户可自选的工具;锁定工具会在 chat agent 需要时自动挂载。","Always on": "始终启用","Auto-mounted by the agent when needed. Not user-toggleable.": "由 agent 在需要时自动挂载,用户无需手动开关。",diff --git a/web/tests/e2e/reading-citation-material.audit.ts b/web/tests/e2e/reading-citation-material.audit.tsindex 149acf962..61763cf2f 100644--- a/web/tests/e2e/reading-citation-material.audit.ts+++ b/web/tests/e2e/reading-citation-material.audit.ts@@ -3,6 +3,7 @@ import { expect, test } from "@playwright/test";const MATERIAL_A = "aaaaaaaaaaaaaaaa";const MATERIAL_B = "bbbbbbbbbbbbbbbb";const SESSION_ID = "citation-material-regression";+const WORKSPACE_ID = "citation-material-workspace";function material(materialId: string, title: string) {return {@@ -28,6 +29,56 @@ function material(materialId: string, title: string) {const materialA = material(MATERIAL_A, "Source material A");const materialB = material(MATERIAL_B, "Current material B");+function libraryMaterial(materialId: string, title: string) {+ return {+ material_id: materialId,+ content_id: materialId,+ filename: `${title}.md`,+ title,+ source_kind: "file",+ source_url: "",+ mime: "text/markdown",+ render_mode: "text",+ cover_url: "",+ duration_seconds: 0,+ status: "ready",+ progress: 0,+ error_code: "",+ error_detail: "",+ created_at: 1,+ updated_at: 2,+ last_opened_at: 2,+ size_bytes: 256,+ unit_count: 2,+ collections: [],+ };+}++const workspace = {+ workspace_id: WORKSPACE_ID,+ title: "Citation material regression",+ description: "",+ active_material_id: MATERIAL_B,+ created_at: 1,+ updated_at: 2,+ tabs: [+ {+ material: libraryMaterial(MATERIAL_A, "Source material A"),+ tab_order: 0,+ pinned: false,+ opened: true,+ added_at: 1,+ },+ {+ material: libraryMaterial(MATERIAL_B, "Current material B"),+ tab_order: 1,+ pinned: false,+ opened: true,+ added_at: 2,+ },+ ],+};+test.beforeEach(async ({ page }) => {await page.route("**/api/v1/**", async (route) => {const path = new URL(route.request().url()).pathname;@@ -129,6 +180,12 @@ test.beforeEach(async ({ page }) => {});}if (path === "/api/v1/reading/extensions") return json([]);+ if (path === `/api/v1/reading/workspaces/${WORKSPACE_ID}`) {+ return json({ workspace, sessions: [] });+ }+ if (path === `/api/v1/reading/workspaces/${WORKSPACE_ID}/sessions`) {+ return json({ sessions: [] });+ }if (path === "/api/v1/reading/materials") {return json([materialB, materialA]);}@@ -158,7 +215,7 @@ test.beforeEach(async ({ page }) => {test("historical citation reopens its turn material and unsupported locator stays plain", async ({page,}) => {- await page.goto(`/home/${SESSION_ID}`);+ await page.goto(`/reading/${WORKSPACE_ID}/${SESSION_ID}`);await expect(page.getByRole("link", { name: "p.2" })).toHaveAttribute("href",@@ -166,12 +223,6 @@ test("historical citation reopens its turn material and unsupported locator stay);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();diff --git a/web/tests/e2e/reading-location-history.audit.ts b/web/tests/e2e/reading-location-history.audit.tsnew file mode 100644index 000000000..6eab7c226--- /dev/null+++ b/web/tests/e2e/reading-location-history.audit.ts@@ -0,0 +1,259 @@+import { expect, test } from "@playwright/test";++const MATERIAL_A = "aaaaaaaaaaaaaaaa";+const MATERIAL_B = "bbbbbbbbbbbbbbbb";+const MATERIAL_MISSING = "cccccccccccccccc";+const SESSION_ONE = "reading-history-one";+const SESSION_TWO = "reading-history-two";+const SESSION_MISSING = "reading-history-missing";+const WORKSPACE_ID = "reading-history-workspace";++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: [+ { title: `${title} first`, locator: 1, level: 1 },+ { title: `${title} second`, locator: 2, level: 1 },+ ],+ outline_text: "",+ unit_refs: [],+ };+}++const materialA = material(MATERIAL_A, "History material A");+const materialB = material(MATERIAL_B, "History material B");++function libraryMaterial(materialId: string, title: string) {+ return {+ material_id: materialId,+ content_id: materialId,+ filename: `${title}.md`,+ title,+ source_kind: "file",+ source_url: "",+ mime: "text/markdown",+ render_mode: "text",+ cover_url: "",+ duration_seconds: 0,+ status: "ready",+ progress: 0,+ error_code: "",+ error_detail: "",+ created_at: 1,+ updated_at: 2,+ last_opened_at: 2,+ size_bytes: 256,+ unit_count: 2,+ collections: [],+ };+}++function workspace(activeMaterialId: string) {+ return {+ workspace_id: WORKSPACE_ID,+ title: "Reading history regression",+ description: "",+ active_material_id: activeMaterialId,+ created_at: 1,+ updated_at: 2,+ tabs: [+ {+ material: libraryMaterial(MATERIAL_A, "History material A"),+ tab_order: 0,+ pinned: false,+ opened: true,+ added_at: 1,+ },+ {+ material: libraryMaterial(MATERIAL_B, "History material B"),+ tab_order: 1,+ pinned: false,+ opened: true,+ added_at: 2,+ },+ ],+ };+}++function session(sessionId: string) {+ return {+ id: sessionId,+ session_id: sessionId,+ title: "Reading history regression",+ created_at: 1,+ updated_at: 2,+ status: "idle",+ preferences: { capability: "immersive_reading" },+ active_turns: [],+ messages: [],+ };+}++test.beforeEach(async ({ page }) => {+ let activeMaterialId = MATERIAL_A;+ 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_ONE}` ||+ path === `/api/v1/sessions/${SESSION_TWO}` ||+ path === `/api/v1/sessions/${SESSION_MISSING}`+ ) {+ return json(session(path.split("/").at(-1) || ""));+ }+ 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/workspaces/${WORKSPACE_ID}`) {+ return json({+ workspace: workspace(activeMaterialId),+ sessions: [],+ });+ }+ if (path === `/api/v1/reading/workspaces/${WORKSPACE_ID}/sessions`) {+ return json({ sessions: [] });+ }+ const activate = /\/api\/v1\/reading\/workspaces\/[^/]+\/materials\/([^/]+)\/active$/.exec(+ path,+ );+ // The workspace API activates an existing tab with PUT.+ if (activate && route.request().method() === "PUT") {+ activeMaterialId = activate[1] || MATERIAL_A;+ return json({ workspace: workspace(activeMaterialId) });+ }+ if (path === "/api/v1/reading/materials") {+ return json([materialA, materialB]);+ }+ if (path === `/api/v1/reading/materials/${MATERIAL_A}`) {+ return json(materialA);+ }+ if (path === `/api/v1/reading/materials/${MATERIAL_B}`) {+ return json(materialB);+ }+ if (path === `/api/v1/reading/materials/${MATERIAL_MISSING}`) {+ return json({ detail: "Material is no longer available" }, 404);+ }+ if (path.endsWith("/annotations")) return json([]);+ const unit = /\/api\/v1\/reading\/materials\/([^/]+)\/units\/(\d+)/.exec(+ path,+ );+ if (unit) {+ const [, materialId, locator] = unit;+ const title = materialId === MATERIAL_A ? "A" : "B";+ return json({+ locator: Number(locator),+ unit: "section",+ text: `# ${title} section ${locator}\n\nHistory ${title}${locator} text.`,+ });+ }+ return json({});+ });+});++test("back and forward cross materials, survive reload, and stay session-scoped", async ({+ page,+}) => {+ await page.goto(`/reading/${WORKSPACE_ID}/${SESSION_ONE}`);+ await expect(page.getByText("History A1 text.")).toBeVisible();++ await page.getByRole("button", { name: "History material A second" }).click();+ await expect(page.getByText("History A2 text.")).toBeVisible();++ await page.getByRole("button", { name: "History material B" }).click();+ await expect(page.getByText("History B1 text.")).toBeVisible();++ await page.getByRole("button", { name: "Back", exact: true }).click();+ await expect(page.getByText("History A2 text.")).toBeVisible();+ await page.getByRole("button", { name: "Forward", exact: true }).click();+ await expect(page.getByText("History B1 text.")).toBeVisible();++ await page.reload();+ await expect(page.getByText("History B1 text.")).toBeVisible();++ await page.goto(`/reading/${WORKSPACE_ID}/${SESSION_TWO}`);+ await page.getByRole("button", { name: "History material B" }).click();+ await expect(+ page.getByRole("button", { name: "Back", exact: true }),+ ).toBeDisabled();+});++test("a deleted material remains identifiable and does not block older history", async ({+ page,+}) => {+ await page.addInitScript(+ ({ key, value }) => window.localStorage.setItem(key, value),+ {+ key: `dt.reader.history.${encodeURIComponent(SESSION_MISSING)}`,+ value: JSON.stringify({+ entries: [+ {+ materialId: MATERIAL_A,+ locator: 1,+ title: "History material A",+ },+ {+ materialId: MATERIAL_MISSING,+ locator: 2,+ title: "Deleted reading material",+ },+ ],+ index: 1,+ }),+ },+ );++ await page.goto(`/reading/${WORKSPACE_ID}/${SESSION_MISSING}`);+ await expect(+ page+ .getByRole("alert")+ .filter({ hasText: "Material is no longer available" }),+ ).toBeVisible();+ await page.getByRole("button", { name: "History", exact: true }).click();+ await expect(page.getByText("Deleted reading material")).toBeVisible();+ await expect(page.getByText("Section 2 · Unavailable")).toBeVisible();++ await page.getByRole("button", { name: "Back", exact: true }).click();+ await expect(page.getByText("History A1 text.")).toBeVisible();+});diff --git a/web/tests/reading-location-history.test.ts b/web/tests/reading-location-history.test.tsnew file mode 100644index 000000000..0b3dc64a3--- /dev/null+++ b/web/tests/reading-location-history.test.ts@@ -0,0 +1,179 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ EMPTY_READING_HISTORY,+ READING_HISTORY_LIMIT,+ moveReadingHistory,+ parseReadingHistory,+ pushReadingLocation,+ readingHistoryStorageKey,+ replaceCurrentReadingLocation,+ selectReadingHistoryIndex,+} from "../lib/reading-location-history";++const entry = (materialId: string, locator: number, title = materialId) => ({+ materialId,+ locator,+ title,+});++test("pushes cross-material locations and removes the forward branch", () => {+ let history = pushReadingLocation(+ EMPTY_READING_HISTORY,+ entry("aaaaaaaaaaaaaaaa", 1),+ );+ history = pushReadingLocation(history, entry("bbbbbbbbbbbbbbbb", 2));+ history = moveReadingHistory(history, -1);+ history = pushReadingLocation(history, entry("cccccccccccccccc", 3));++ assert.deepEqual(+ history.entries.map(({ materialId }) => materialId),+ ["aaaaaaaaaaaaaaaa", "cccccccccccccccc"],+ );+ assert.equal(history.index, 1);+});++test("manual scrolling replaces current instead of adding entries", () => {+ const first = pushReadingLocation(+ EMPTY_READING_HISTORY,+ entry("aaaaaaaaaaaaaaaa", 1, "A"),+ );+ const scrolled = replaceCurrentReadingLocation(+ first,+ entry("aaaaaaaaaaaaaaaa", 8, "A"),+ );++ assert.equal(scrolled.entries.length, 1);+ assert.equal(scrolled.entries[0].locator, 8);+});++test("consecutive duplicate pushes refresh metadata without growing", () => {+ const first = pushReadingLocation(+ EMPTY_READING_HISTORY,+ entry("aaaaaaaaaaaaaaaa", 2, "Old"),+ );+ const duplicate = pushReadingLocation(+ first,+ entry("aaaaaaaaaaaaaaaa", 2, "New"),+ );++ assert.equal(duplicate.entries.length, 1);+ assert.equal(duplicate.entries[0].title, "New");+});++test("caps history at fifty entries", () => {+ let history = EMPTY_READING_HISTORY;+ for (let locator = 1; locator <= READING_HISTORY_LIMIT + 7; locator += 1) {+ history = pushReadingLocation(history, entry("aaaaaaaaaaaaaaaa", locator));+ }+ assert.equal(history.entries.length, READING_HISTORY_LIMIT);+ assert.equal(history.entries[0].locator, 8);+ assert.equal(history.index, READING_HISTORY_LIMIT - 1);+});++test("parsing corrupt storage degrades to empty and filters unsafe entries", () => {+ assert.deepEqual(parseReadingHistory("not json"), EMPTY_READING_HISTORY);+ const parsed = parseReadingHistory(+ JSON.stringify({+ entries: [+ entry("../../etc", 1),+ entry("AAAAAAAAAAAAAAAA", 2, "A"),+ entry("bbbbbbbbbbbbbbbb", 0),+ ],+ index: 2,+ }),+ );+ assert.deepEqual(parsed, {+ entries: [entry("aaaaaaaaaaaaaaaa", 2, "A")],+ index: 0,+ });+});++test("parsing preserves the selected valid entry when later rows are corrupt", () => {+ const parsed = parseReadingHistory(+ JSON.stringify({+ entries: [+ entry("aaaaaaaaaaaaaaaa", 1, "A"),+ entry("bbbbbbbbbbbbbbbb", 2, "B"),+ entry("not-a-material-id", 3),+ ],+ index: 1,+ }),+ );++ assert.equal(parsed.index, 1);+ assert.equal(parsed.entries[parsed.index].title, "B");+});++test("parsing collapses persisted consecutive duplicates", () => {+ const parsed = parseReadingHistory(+ JSON.stringify({+ entries: [+ entry("aaaaaaaaaaaaaaaa", 1, "Old"),+ entry("aaaaaaaaaaaaaaaa", 1, "New"),+ entry("bbbbbbbbbbbbbbbb", 2, "B"),+ ],+ index: 1,+ }),+ );++ assert.deepEqual(parsed.entries, [+ entry("aaaaaaaaaaaaaaaa", 1, "New"),+ entry("bbbbbbbbbbbbbbbb", 2, "B"),+ ]);+ assert.equal(parsed.index, 0);+});++test("back, forward and direct selection stay bounded", () => {+ let history = pushReadingLocation(+ EMPTY_READING_HISTORY,+ entry("aaaaaaaaaaaaaaaa", 1),+ );+ history = pushReadingLocation(history, entry("bbbbbbbbbbbbbbbb", 1));+ assert.equal(moveReadingHistory(history, 1).index, 1);+ assert.equal(moveReadingHistory(history, -1).index, 0);+ assert.equal(selectReadingHistoryIndex(history, 0).index, 0);+ assert.equal(selectReadingHistoryIndex(history, 99), history);+});++test("storage keys are isolated by chat session", () => {+ assert.notEqual(+ readingHistoryStorageKey("session-a"),+ readingHistoryStorageKey("session-b"),+ );+});++test("navigation state preserves PDF, EPUB, and Markdown material metadata", () => {+ let history = EMPTY_READING_HISTORY;+ history = pushReadingLocation(history, {+ ...entry("aaaaaaaaaaaaaaaa", 4, "PDF"),+ source: { mime: "application/pdf", renderMode: "pdf", unit: "page" },+ });+ history = pushReadingLocation(history, {+ ...entry("bbbbbbbbbbbbbbbb", 2, "EPUB"),+ source: {+ mime: "application/epub+zip",+ renderMode: "epub",+ unit: "chapter",+ },+ });+ history = pushReadingLocation(history, {+ ...entry("cccccccccccccccc", 7, "Markdown"),+ source: { mime: "text/markdown", renderMode: "text", unit: "section" },+ });++ history = moveReadingHistory(history, -1);+ assert.deepEqual(history.entries[history.index], {+ ...entry("bbbbbbbbbbbbbbbb", 2, "EPUB"),+ source: {+ mime: "application/epub+zip",+ renderMode: "epub",+ unit: "chapter",+ },+ });+ history = moveReadingHistory(history, -1);+ assert.equal(history.entries[history.index].source?.renderMode, "pdf");+ history = moveReadingHistory(history, 1);+ history = moveReadingHistory(history, 1);+ assert.equal(history.entries[history.index].source?.mime, "text/markdown");+});