Skip to content

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

fix(learner): restore course access (#1228)

XZHbf4b55e926a7
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 444079025..f99b7c5cf 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -405,6 +405,7 @@ def _learning_surface_for_path(path: str) -> str:
normalized = "/" + str(path or "").lstrip("/")
for root, surface in (
("/api/reading", "reading"),
+ ("/api/courses", "reading"),
("/api/chat", "chat"),
("/api/question", "chat"),
("/api/question-notebook", "chat"),
diff --git a/tests/multi_user/test_account_presets.py b/tests/multi_user/test_account_presets.py
index 17fa5f7c0..476083f78 100644
--- a/tests/multi_user/test_account_presets.py
+++ b/tests/multi_user/test_account_presets.py
@@ -36,6 +36,7 @@ def test_learning_surface_routing_matches_complete_path_segments():
from deeptutor.api.routers.auth import _learning_surface_for_path
assert _learning_surface_for_path("/api/reading/materials") == "reading"
+ assert _learning_surface_for_path("/api/courses/course/state") == "reading"
assert _learning_surface_for_path("/api/question-notebook/entries") == "chat"
assert _learning_surface_for_path("/api/reading-private") == ""
assert _learning_surface_for_path("/api/questions") == ""
diff --git a/web/components/courses/CoursesShelf.tsx b/web/components/courses/CoursesShelf.tsx
index ab04b6cf4..611ada393 100644
--- a/web/components/courses/CoursesShelf.tsx
+++ b/web/components/courses/CoursesShelf.tsx
@@ -6,6 +6,7 @@ import {
Archive,
ArrowRight,
BookOpen,
+ CircleAlert,
Layers,
MessagesSquare,
Plus,
@@ -36,6 +37,7 @@ export default function CoursesShelf() {
const [courses, setCourses] = useState<StudyCourse[]>([]);
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [loading, setLoading] = useState(true);
+ const [loadError, setLoadError] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
useEffect(() => {
@@ -49,6 +51,10 @@ export default function CoursesShelf() {
setCourses(nextCourses);
setSessions(nextSessions);
})
+ .catch((error: unknown) => {
+ if (cancelled) return;
+ setLoadError(error instanceof Error ? error.message : "");
+ })
.finally(() => {
if (!cancelled) setLoading(false);
});
@@ -134,6 +140,21 @@ export default function CoursesShelf() {
/>
))}
</div>
+ ) : loadError !== null ? (
+ <div
+ role="alert"
+ className="flex min-h-32 items-center gap-3 rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 text-[12.5px] text-[var(--muted-foreground)]"
+ >
+ <CircleAlert size={16} strokeWidth={1.8} aria-hidden />
+ <span>
+ <span className="block font-medium text-[var(--foreground)]">
+ {t("Courses could not load")}
+ </span>
+ <span className="mt-1 block leading-relaxed">
+ {loadError || t("Courses could not load")}
+ </span>
+ </span>
+ </div>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{active.map((course) => (
diff --git a/web/lib/courses-api.ts b/web/lib/courses-api.ts
index ccc32be36..671db6f98 100644
--- a/web/lib/courses-api.ts
+++ b/web/lib/courses-api.ts
@@ -1,5 +1,6 @@
import { apiFetch, apiUrl } from "@/lib/api";
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
+import { ApiError } from "@/shared/api/errors";
/**
* Kinds of resource a course may reference.
@@ -128,8 +129,24 @@ export const DEFAULT_COURSE_COLORS = [
];
async function expectJson<T>(response: Response): Promise<T> {
- if (!response.ok) throw new Error(`Request failed: ${response.status}`);
- return response.json() as Promise<T>;
+ const payload = await response.json().catch(() => null);
+ if (!response.ok) {
+ const detail =
+ payload && typeof payload === "object"
+ ? String((payload as { detail?: unknown }).detail ?? "").trim()
+ : "";
+ throw new ApiError({
+ code: `http_${response.status}`,
+ message: detail || `Request failed (${response.status})`,
+ retryable:
+ response.status === 408 ||
+ response.status === 429 ||
+ response.status >= 500,
+ scope: "network",
+ status: response.status,
+ });
+ }
+ return payload as T;
}
/** Fill in fields absent from courses created before the container existed. */
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 264b5bd32..00d9edb11 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3729,6 +3729,7 @@
"Selected text": "Selected text",
"Ask anything about the selected text.": "Ask anything about the selected text.",
"My courses": "My courses",
+ "Courses could not load": "Courses could not load",
"Create a course": "Create a course",
"Create your first course": "Create your first course",
"Course name": "Course name",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 0d74a1abd..1043266e4 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3729,6 +3729,7 @@
"Selected text": "选中内容",
"Ask anything about the selected text.": "可以针对这段选中内容继续提问。",
"My courses": "我的课程",
+ "Courses could not load": "课程加载失败",
"Create a course": "创建课程",
"Create your first course": "创建第一门课程",
"Course name": "课程名称",
diff --git a/web/tests/course-organization-api.test.ts b/web/tests/course-organization-api.test.ts
index 37ffcc6c6..d881294f1 100644
--- a/web/tests/course-organization-api.test.ts
+++ b/web/tests/course-organization-api.test.ts
@@ -1,9 +1,11 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { listCourses } from "../lib/courses-api";
import { listAllSessions, updateSessionOrganization } from "../lib/session-api";
import { organizeSessionTree } from "../lib/session-organization";
import type { SessionSummary } from "../lib/session-api";
+import { ApiError } from "../shared/api/errors";
function session(
id: string,
@@ -55,6 +57,34 @@ test("course organization fetches every session page", async () => {
}
});
+test("course policy failures preserve the server denial", async () => {
+ const original = globalThis.fetch;
+ (globalThis as { fetch: typeof fetch }).fetch = async () =>
+ new Response(
+ JSON.stringify({
+ detail: "This learning account cannot use the reading surface."
+ }),
+ { status: 403, headers: { "Content-Type": "application/json" } },
+ );
+
+ try {
+ await assert.rejects(
+ listCourses({ force: true }),
+ (error: unknown) => {
+ assert.ok(error instanceof ApiError);
+ assert.equal(error.status, 403);
+ assert.equal(
+ error.message,
+ "This learning account cannot use the reading surface."
+ );
+ return true;
+ },
+ );
+ } finally {
+ (globalThis as { fetch: typeof fetch }).fetch = original;
+ }
+});
+
test("course organization patch sends only the requested metadata", async () => {
const original = globalThis.fetch;
let capturedUrl = "";
diff --git a/web/tests/courses-shelf.spec.tsx b/web/tests/courses-shelf.spec.tsx
new file mode 100644
index 000000000..7b2a451a1
--- /dev/null
+++ b/web/tests/courses-shelf.spec.tsx
@@ -0,0 +1,35 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import CoursesShelf from "@/components/courses/CoursesShelf";
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+vi.mock("@/lib/courses-api", () => ({
+ DEFAULT_COURSE_COLORS: ["#C65D2E"],
+ listCourses: vi.fn(() =>
+ Promise.reject(
+ new Error("This learning account cannot use the reading surface.")
+ )
+ ),
+ createCourse: vi.fn(),
+}));
+
+vi.mock("@/lib/session-api", () => ({
+ listAllSessions: vi.fn(() => Promise.resolve([])),
+}));
+
+describe("courses shelf", () => {
+ it("shows an authorization failure instead of an empty shelf", async () => {
+ render(<CoursesShelf />);
+
+ const alert = await screen.findByRole("alert");
+ expect(alert).toHaveTextContent(
+ "This learning account cannot use the reading surface."
+ );
+ expect(
+ screen.queryByRole("button", { name: "Create your first course" })
+ ).not.toBeInTheDocument();
+ });
+});