DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(ci): stabilize current dependency and reading gates (#1210)
Bingxi Zhao97cb143cbc36
diff --git a/tests/api/route_introspection.py b/tests/api/route_introspection.pynew file mode 100644index 000000000..40c415daa--- /dev/null+++ b/tests/api/route_introspection.py@@ -0,0 +1,45 @@+"""Compatibility helpers for assertions over FastAPI's registered routes."""++from collections.abc import Iterator++from fastapi import FastAPI+from fastapi.routing import APIWebSocketRoute+++def iter_effective_route_paths(app: FastAPI) -> Iterator[str]:+ """Yield registered paths across flat and nested FastAPI releases."""+ for route in app.routes:+ path = getattr(route, "path", None)+ if isinstance(path, str):+ yield path+ continue++ effective_contexts = getattr(route, "effective_route_contexts", None)+ if not callable(effective_contexts):+ continue+ for context in effective_contexts():+ compiled_route = getattr(context, "starlette_route", None)+ effective_path = getattr(compiled_route, "path", None) or getattr(context, "path", None)+ if isinstance(effective_path, str):+ yield effective_path+++def iter_effective_websocket_routes(app: FastAPI) -> Iterator[APIWebSocketRoute]:+ """Yield compiled WebSocket routes across flat and nested FastAPI releases.++ FastAPI 0.141 stopped flattening included routers into ``app.routes``.+ Included-router entries expose their compiled routes through+ ``effective_route_contexts()``; older releases expose the routes directly.+ """+ for route in app.routes:+ if isinstance(route, APIWebSocketRoute):+ yield route+ continue++ effective_contexts = getattr(route, "effective_route_contexts", None)+ if not callable(effective_contexts):+ continue+ for context in effective_contexts():+ compiled_route = getattr(context, "starlette_route", None)+ if isinstance(compiled_route, APIWebSocketRoute):+ yield compiled_routediff --git a/tests/api/test_canonical_route_surface.py b/tests/api/test_canonical_route_surface.pyindex 955fd2239..6aebed2b7 100644--- a/tests/api/test_canonical_route_surface.py+++ b/tests/api/test_canonical_route_surface.py@@ -3,10 +3,11 @@ from types import SimpleNamespaceimport pytestfrom deeptutor.api.main import app, health_live, health_ready+from tests.api.route_introspection import iter_effective_route_pathsdef test_only_canonical_transport_and_resource_routes_are_registered() -> None:- paths = {route.path for route in app.routes}+ paths = set(iter_effective_route_paths(app))required = {"/api/books",diff --git a/tests/api/test_websocket_routing.py b/tests/api/test_websocket_routing.pyindex da7ef6b02..e40763f1b 100644--- a/tests/api/test_websocket_routing.py+++ b/tests/api/test_websocket_routing.py@@ -1,9 +1,8 @@"""WebSocket routes must not inherit HTTP-only application dependencies."""-from fastapi.routing import APIWebSocketRoute-from deeptutor.api.main import appfrom deeptutor.api.routers.auth import require_learning_surface+from tests.api.route_introspection import iter_effective_websocket_routesdef test_websocket_routes_share_one_canonical_namespace() -> None:@@ -18,9 +17,7 @@ def test_websocket_routes_share_one_canonical_namespace() -> None:"/ws/partners/{partner_id}","/ws/partner-groups/{group_id}",}- websocket_routes = {- route.path: route for route in app.routes if isinstance(route, APIWebSocketRoute)- }+ websocket_routes = {route.path: route for route in iter_effective_websocket_routes(app)}assert set(websocket_routes) == expected_pathsfor route in websocket_routes.values():diff --git a/web/app/(workspace)/books/components/PageReader.tsx b/web/app/(workspace)/books/components/PageReader.tsxindex 758d47a36..83fdf80e7 100644--- a/web/app/(workspace)/books/components/PageReader.tsx+++ b/web/app/(workspace)/books/components/PageReader.tsx@@ -1,6 +1,7 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";+import { usePathname } from "next/navigation";import {Bookmark,BookmarkCheck,@@ -23,6 +24,7 @@ import {type ChapterScrollPlacement,type SequentialReadDirection,} from "@/lib/book-reader-navigation";+import { browserStorage } from "@/shared/storage";import BlockRenderer from "./blocks/BlockRenderer";import type { QuizAttemptArgs } from "./blocks/QuizBlock";import PageOutlineNav from "./PageOutlineNav";@@ -40,6 +42,41 @@ const INSERTABLE_TYPES: BlockType[] = ["deep_dive","user_note",];+const PENDING_CHAPTER_END_KEY = "deeptutor.book.pendingChapterEnd";+const PENDING_CHAPTER_END_TTL_MS = 30_000;++interface PendingChapterEnd {+ bookId: string;+ pageId: string;+ createdAt: number;+}++function rememberPendingChapterEnd(bookId: string, pageId: string): void {+ browserStorage.writeRaw(+ "session",+ PENDING_CHAPTER_END_KEY,+ JSON.stringify({ bookId, pageId, createdAt: Date.now() }),+ );+}++function hasPendingChapterEnd(bookId: string, pageId: string): boolean {+ const raw = browserStorage.readRaw("session", PENDING_CHAPTER_END_KEY);+ if (!raw) return false;+ try {+ const pending = JSON.parse(raw) as PendingChapterEnd;+ if (+ typeof pending.createdAt !== "number" ||+ Date.now() - pending.createdAt > PENDING_CHAPTER_END_TTL_MS+ ) {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ return false;+ }+ return pending.bookId === bookId && pending.pageId === pageId;+ } catch {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ return false;+ }+}export interface PageReaderProps {page: Page | null;@@ -106,6 +143,7 @@ export default function PageReader({onCaptureSelection,}: PageReaderProps) {const { t } = useTranslation();+ const pathname = usePathname();const [showInsertMenu, setShowInsertMenu] = useState(false);/** The chapter outline starts parked so it never covers the prose unasked. */const [outlineCollapsed, setOutlineCollapsed] = useState(true);@@ -162,10 +200,18 @@ export default function PageReader({const isNewPage = lastSeenPageIdRef.current !== page.id;lastSeenPageIdRef.current = page.id;const requestedPageId = pendingScrollPlacementPageIdRef.current;- const pendingMatchesPage = requestedPageId === page.id;- const placement = pendingMatchesPage+ const targetPath = `/books/${encodeURIComponent(page.book_id)}/pages/${encodeURIComponent(page.id)}`;+ // State changes before App Router finishes updating the URL. Let the+ // destination route consume this cross-mount intent; the departing page+ // must not clear it during that short transition window.+ const persistedEnd =+ pathname === targetPath && hasPendingChapterEnd(page.book_id, page.id);+ const pendingMatchesPage = requestedPageId === page.id || persistedEnd;+ const placement = requestedPageId === page.id? pendingScrollPlacementRef.current- : "start";+ : persistedEnd+ ? "end"+ : "start";if (!pendingMatchesPage) {pendingScrollPlacementRef.current = "start";pendingScrollPlacementPageIdRef.current = null;@@ -181,8 +227,6 @@ export default function PageReader({// from surviving into the hydrated chapter. "End" must wait for content.if (waitingForContent && placement === "end") return;- pendingScrollPlacementRef.current = "start";- pendingScrollPlacementPageIdRef.current = null;const pendingFrames: number[] = [];pendingFrames.push(window.requestAnimationFrame(() => {@@ -191,6 +235,15 @@ export default function PageReader({scrollContainer.scrollTop =placement === "end" ? scrollContainer.scrollHeight : 0;updateReadingProgress();+ // Consume the placement only after it has actually reached the+ // DOM. Hydration can rerun this effect between the two frames;+ // clearing earlier loses an owed "land at end" and resets the+ // previous chapter to its first screen.+ pendingScrollPlacementRef.current = "start";+ pendingScrollPlacementPageIdRef.current = null;+ if (persistedEnd) {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ }}),);}),@@ -201,7 +254,7 @@ export default function PageReader({window.cancelAnimationFrame(frame);}};- }, [scrollContainer, page, loading, updateReadingProgress]);+ }, [scrollContainer, page, loading, pathname, updateReadingProgress]);useEffect(() => {updateReadingProgress();@@ -311,6 +364,8 @@ export default function PageReader({if (direction === "previous" && previousPage) {pendingScrollPlacementRef.current = "end";pendingScrollPlacementPageIdRef.current = previousPage.id;+ const currentBookId = bookId || page?.book_id;+ if (currentBookId) rememberPendingChapterEnd(currentBookId, previousPage.id);onNavigate?.(previousPage.id);return true;}@@ -324,8 +379,10 @@ export default function PageReader({},[loading,+ bookId,nextPage,onNavigate,+ page?.book_id,page?.blocks.length,previousPage,scrollContainer,diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex 7f8b7b260..b66a2a267 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -138,6 +138,26 @@ export interface ReadingPosition {updated_at: number;}+export function parseReadingPosition(payload: unknown): ReadingPosition {+ if (!payload || typeof payload !== "object") {+ throw new Error("Invalid reading position response");+ }+ const position = payload as Record<string, unknown>;+ if (+ typeof position.locator !== "number" ||+ !Number.isFinite(position.locator) ||+ position.locator < 1 ||+ typeof position.source_anchor !== "string" ||+ typeof position.percentage !== "number" ||+ !Number.isFinite(position.percentage) ||+ typeof position.updated_at !== "number" ||+ !Number.isFinite(position.updated_at)+ ) {+ throw new Error("Invalid reading position response");+ }+ return position as unknown as ReadingPosition;+}+/*** A place the reader chose to keep, as opposed to the position above — which* is the single automatic "where I got to", overwritten on every move. These@@ -305,10 +325,12 @@ export function rawMaterialUrl(materialId: string): string {export async function getReadingPosition(materialId: string,): Promise<ReadingPosition> {- return unwrap(- await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {- cache: "no-store",- }),+ return parseReadingPosition(+ await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ cache: "no-store",+ }),+ ),);}@@ -316,12 +338,14 @@ export async function saveReadingPosition(materialId: string,position: Pick<ReadingPosition, "locator" | "source_anchor" | "percentage">,): Promise<ReadingPosition> {- return unwrap(- await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(position),- }),+ return parseReadingPosition(+ await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(position),+ }),+ ),);}diff --git a/web/tests/e2e/book-reader-sequential.audit.ts b/web/tests/e2e/book-reader-sequential.audit.tsindex 382c5a5a8..82334fea7 100644--- a/web/tests/e2e/book-reader-sequential.audit.ts+++ b/web/tests/e2e/book-reader-sequential.audit.ts@@ -134,7 +134,7 @@ test("book arrows read the current chapter before turning chapters", async ({// A hidden reader (for example when the mobile chapter sidebar is expanded)// must not turn the page and skip unread content.await page.keyboard.press("ArrowRight");- await expect(page).toHaveURL(/page=page-2/);+ await expect(page).toHaveURL(/\/pages\/page-2(?:[?#]|$)/);await page.getByRole("button", { name: "Collapse chapters" }).click();await expect(@@ -180,12 +180,14 @@ test("book arrows read the current chapter before turning chapters", async ({).toBe(100);await page.keyboard.press("ArrowRight");+ await expect(page).toHaveURL(/\/pages\/page-3(?:[?#]|$)/);await expect(page.getByRole("heading", { name: "Next chapter" }),).toBeVisible();await expect(await reader.evaluate((element) => element.scrollTop)).toBe(0);await page.keyboard.press("ArrowLeft");+ await expect(page).toHaveURL(/\/pages\/page-2(?:[?#]|$)/);await expect(page.getByRole("heading", { name: "Current long chapter" }),).toBeVisible();diff --git a/web/tests/reading-position.test.ts b/web/tests/reading-position.test.tsnew file mode 100644index 000000000..62028dcd6--- /dev/null+++ b/web/tests/reading-position.test.ts@@ -0,0 +1,32 @@+import assert from "node:assert/strict";+import test from "node:test";++import { parseReadingPosition } from "@/lib/reading-api";++test("reading positions accept the complete API contract", () => {+ const position = {+ locator: 3,+ source_anchor: "chapter-3",+ percentage: 0.5,+ updated_at: 42,+ };++ assert.deepEqual(parseReadingPosition(position), position);+});++test("reading positions reject partial and non-finite responses", () => {+ assert.throws(+ () => parseReadingPosition({}),+ /Invalid reading position response/,+ );+ assert.throws(+ () =>+ parseReadingPosition({+ locator: Number.NaN,+ source_anchor: "",+ percentage: 0,+ updated_at: 0,+ }),+ /Invalid reading position response/,+ );+});