Files
DeepTutor/web/context/ReadingContext.tsx
Bingxi Zhao (Frank) 31bf66b5e1 release: v1.5.15
Self-hostable PageIndex, a fileable question bank, and third-party plugins.

- PageIndex: adds PageIndex OSS as its own knowledge-base type, bound to
  the base's local library and driven by the configured LLM rather than a
  PageIndex API key. Retrieval moves off the built-in MCP server (removed)
  onto a workflow-owned reading loop that walks the document tree.
- Question bank: addEntryToCategory shipped in v1.3.6 and was never called
  from the frontend, so categories could be created but never filled. The
  quiz card now uses the shared CategoryMenu, the page is rebuilt around
  search / batch selection / an unfiled inbox, and a new question_bank tool
  lets the tutor file questions instead of misrouting them to write_note.
- Plugins: deeptutor.plugins was imported behind a try/except but the
  module never existed — implemented, plus a deeptutor.loop_capabilities
  group so third-party packages can register chat-loop capabilities.
  Builtins win on name collisions; broken entry points are skipped.
- Parsing: remote Apache Tika engine (TIKA_SERVER_URL), with no local
  package and no model download.
- LightRAG: the three indexing knobs from #877 get inputs under their own
  Indexing divider; unsupported keywords are dropped with a warning.
- Knowledge bases: uploads take a destination folder, same-named documents
  from different subtrees stop dropping one another, and linked folders
  keep their source-relative structure — closing #866.
- Book: a learning-capture inbox with an explicit status lifecycle, and
  drift warnings scoped to the KB documents that actually changed.
- Whisper: /whisper moves out of the primary nav into Learning Space →
  More Projects, credited to its contributor; the room needs its own
  capability package. The reusable half is CAPABILITY_COMPLETE forwarding
  of a capability-declared body and its declared extras.
- README: a Collaborate badge beside the Docs badge, in all twelve
  languages.
- Lint: nosec B608 on four false-positive question-bank queries (literal
  fragments only, every value bound), and three mypy fixes.

Release notes: assets/releases/ver1-5-15.md
2026-08-20 14:15:53 +08:00

248 lines
7.3 KiB
TypeScript

"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import {
deleteAnnotation as deleteAnnotationApi,
getMaterial,
listAnnotations,
saveAnnotation,
type AnnotationDraft,
type AnnotationItem,
type MaterialDetail,
type MaterialInfo,
} from "@/lib/reading-api";
import {
setReadingMaterial,
setReadingViewport,
} from "@/lib/reading-turn-state";
/**
* The open document and its annotations, owned above the chat page.
*
* This provider lives in the workspace layout, NOT inside the chat page, and
* that placement is the whole point: sending the first message of a session
* changes the URL from `/home` to `/home/<id>`, which remounts the page
* component. State held inside the reader pane died with it, so the document
* vanished the moment the user asked their first question. The layout persists
* across that navigation — which is exactly why `UnifiedChatProvider` sits there
* too.
*
* The viewport (scroll position, selection) is deliberately NOT state: it
* changes on every scroll tick and nothing renders from it, so it goes straight
* into the module cell in `reading-turn-state` and is read once when a turn is
* sent. Keeping it out of here is what stops scrolling the PDF from re-rendering
* the message list.
*/
export interface ReadingContextValue {
material: MaterialDetail | null;
annotations: AnnotationItem[];
loading: boolean;
/** Last failure worth showing the user; cleared by `dismissError`. */
error: string | null;
openMaterial: (candidate: MaterialDetail | MaterialInfo) => Promise<void>;
closeMaterial: () => void;
/** Insert or update an annotation, optimistically. */
saveMark: (
draft: AnnotationDraft,
optimistic: AnnotationItem,
) => Promise<void>;
/** Remove an annotation, optimistically. */
removeMark: (annotation: AnnotationItem) => Promise<void>;
/** Accept a mark the assistant just made (arrives via a tool result). */
mergeMark: (annotation: AnnotationItem) => void;
dismissError: () => void;
setError: (message: string) => void;
/** Report scroll position / selection. Does not trigger a render. */
reportViewport: (next: { locator?: number; selection?: string }) => void;
}
const noop = () => {};
const ReadingContext = createContext<ReadingContextValue>({
material: null,
annotations: [],
loading: false,
error: null,
openMaterial: async () => {},
closeMaterial: noop,
saveMark: async () => {},
removeMark: async () => {},
mergeMark: noop,
dismissError: noop,
setError: noop,
reportViewport: noop,
});
export function ReadingProvider({ children }: { children: ReactNode }) {
const [material, setMaterial] = useState<MaterialDetail | null>(null);
const [annotations, setAnnotations] = useState<AnnotationItem[]>([]);
const [loading, setLoading] = useState(false);
const [error, setErrorState] = useState<string | null>(null);
// Guards against a slow open landing after the user opened something else.
const openTokenRef = useRef(0);
// Mirror the open document into the turn-state cell, which is what the chat
// 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);
}, [material]);
const openMaterial = useCallback(
async (candidate: MaterialDetail | MaterialInfo) => {
const token = ++openTokenRef.current;
setLoading(true);
setErrorState(null);
try {
const detail =
"outline" in candidate
? (candidate as MaterialDetail)
: await getMaterial(candidate.material_id);
const marks = await listAnnotations(detail.material_id);
if (token !== openTokenRef.current) return;
setMaterial(detail);
setAnnotations(marks);
} catch (caught) {
if (token !== openTokenRef.current) return;
setErrorState(
caught instanceof Error
? caught.message
: "This document could not be opened.",
);
} finally {
if (token === openTokenRef.current) setLoading(false);
}
},
[],
);
const closeMaterial = useCallback(() => {
// Bump the token so an open still in flight cannot resurrect the document.
openTokenRef.current += 1;
setMaterial(null);
setAnnotations([]);
setErrorState(null);
setReadingViewport({ locator: 0, selection: "" });
}, []);
const saveMark = useCallback(
async (draft: AnnotationDraft, optimistic: AnnotationItem) => {
const materialId = material?.material_id;
if (!materialId) return;
// Shown immediately: waiting for a round trip before any ink appears
// makes highlighting feel broken.
setAnnotations((current) => [...current, optimistic]);
try {
const saved = await saveAnnotation(materialId, draft);
setAnnotations((current) =>
current.map((row) =>
row.annotation_id === optimistic.annotation_id ? saved : row,
),
);
} catch (caught) {
setAnnotations((current) =>
current.filter(
(row) => row.annotation_id !== optimistic.annotation_id,
),
);
setErrorState(
caught instanceof Error
? caught.message
: "That annotation could not be saved.",
);
}
},
[material],
);
const removeMark = useCallback(
async (annotation: AnnotationItem) => {
const materialId = material?.material_id;
if (!materialId) return;
let previous: AnnotationItem[] = [];
setAnnotations((current) => {
previous = current;
return current.filter(
(row) => row.annotation_id !== annotation.annotation_id,
);
});
try {
await deleteAnnotationApi(materialId, annotation.annotation_id);
} catch {
// Put it back: pretending a failed delete succeeded would lose the mark
// on the next reload.
setAnnotations(previous);
setErrorState("That annotation could not be removed.");
}
},
[material],
);
const mergeMark = useCallback((annotation: AnnotationItem) => {
if (!annotation?.annotation_id) return;
setAnnotations((current) => [
...current.filter(
(row) => row.annotation_id !== annotation.annotation_id,
),
annotation,
]);
}, []);
const reportViewport = useCallback(
(next: { locator?: number; selection?: string }) =>
setReadingViewport(next),
[],
);
const dismissError = useCallback(() => setErrorState(null), []);
const setError = useCallback((message: string) => setErrorState(message), []);
const value = useMemo<ReadingContextValue>(
() => ({
material,
annotations,
loading,
error,
openMaterial,
closeMaterial,
saveMark,
removeMark,
mergeMark,
dismissError,
setError,
reportViewport,
}),
[
material,
annotations,
loading,
error,
openMaterial,
closeMaterial,
saveMark,
removeMark,
mergeMark,
dismissError,
setError,
reportViewport,
],
);
return (
<ReadingContext.Provider value={value}>{children}</ReadingContext.Provider>
);
}
export function useReading(): ReadingContextValue {
return useContext(ReadingContext);
}