DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(courses): preserve handoff course scope (#1099)
XZH2c06318fe443
diff --git a/web/app/(utility)/mastery/[pathId]/study/[[...sessionId]]/page.tsx b/web/app/(utility)/mastery/[pathId]/study/[[...sessionId]]/page.tsxindex 6a37e3fd6..ddab71d05 100644--- a/web/app/(utility)/mastery/[pathId]/study/[[...sessionId]]/page.tsx+++ b/web/app/(utility)/mastery/[pathId]/study/[[...sessionId]]/page.tsx@@ -1,11 +1,12 @@"use client";-import { useParams } from "next/navigation";+import { useParams, useSearchParams } from "next/navigation";import { MasteryStudy } from "@/components/space/learning/MasteryStudy";export default function MasteryStudyPage() {const params = useParams<{ pathId: string; sessionId?: string[] }>();+ const courseId = useSearchParams().get("course")?.trim() ?? "";const routeSessionId = Array.isArray(params.sessionId)? params.sessionId[0]: undefined;@@ -14,6 +15,7 @@ export default function MasteryStudyPage() {<MasteryStudypathId={String(params.pathId || "")}routeSessionId={routeSessionId}+ courseId={courseId}/>);}diff --git a/web/components/reading/workspace/ReadingWorkspace.tsx b/web/components/reading/workspace/ReadingWorkspace.tsxindex 745e8a397..890afa040 100644--- a/web/components/reading/workspace/ReadingWorkspace.tsx+++ b/web/components/reading/workspace/ReadingWorkspace.tsx@@ -1,7 +1,7 @@"use client";import Link from "next/link";-import { useParams, useRouter } from "next/navigation";+import { useParams, useRouter, useSearchParams } from "next/navigation";import {ArrowLeft,ChevronDown,@@ -87,6 +87,7 @@ export function ReadingWorkspacePage() {const params = useParams<{ workspaceId: string; sessionId?: string[] }>();const workspaceId = params.workspaceId;const sessionIdParam = params.sessionId?.[0] ?? null;+ const courseId = useSearchParams().get("course")?.trim() ?? "";const router = useRouter();const { t } = useTranslation();// The shell only needs to *send* (guided one-click prompts). Rendering the@@ -124,7 +125,7 @@ export function ReadingWorkspacePage() {buildMasteryPath,renameWorkspace,reportViewport,- } = useReadingWorkspace(workspaceId, sessionIdParam);+ } = useReadingWorkspace(workspaceId, sessionIdParam, courseId);// View-only state: what the reader is pointing at and which panels are open.const [transcriptSearch, setTranscriptSearch] = useState("");diff --git a/web/components/reading/workspace/useReadingWorkspace.ts b/web/components/reading/workspace/useReadingWorkspace.tsindex 829174c18..7fa802463 100644--- a/web/components/reading/workspace/useReadingWorkspace.ts+++ b/web/components/reading/workspace/useReadingWorkspace.ts@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import { useReading } from "@/context/ReadingContext";import { useUnifiedChat } from "@/context/UnifiedChatContext";+import { courseSessionConfiguration } from "@/lib/course-session-scope";import { getMaterial, getUnitText } from "@/lib/reading-api";import {READER_ACTION_EVENT,@@ -43,6 +44,7 @@ import type { TranscriptRow } from "./types";export function useReadingWorkspace(workspaceId: string,sessionIdParam: string | null,+ courseId = "",) {const router = useRouter();const { t } = useTranslation();@@ -187,7 +189,7 @@ export function useReadingWorkspace(// turn runs (see `turn_runtime`), so opening a collection and walking// away no longer litters it with empty conversations.if (sessionIdParam) await loadSession(sessionIdParam);- else newSession();+ else newSession(courseSessionConfiguration({}, courseId));setCapability(READING_CAPABILITY);} catch (caught) {setError(@@ -198,6 +200,7 @@ export function useReadingWorkspace(}})();}, [+ courseId,loadSession,loading,newSession,diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsxindex 42c0b3469..bfd06ae28 100644--- a/web/components/space/learning/MasteryStudy.tsx+++ b/web/components/space/learning/MasteryStudy.tsx@@ -62,9 +62,11 @@ function currentWaypoint(topic: MasteryTopic, fallback: string, t: Translate) {export function MasteryStudy({pathId,routeSessionId,+ courseId = "",}: {pathId: string;routeSessionId?: string;+ courseId?: string;}) {const { t } = useTranslation();const {@@ -77,7 +79,7 @@ export function MasteryStudy({switchBranch,} = useUnifiedChat();const { topic, topicError, knowledgeBases, sessionError, sessionLoading } =- useMasteryStudySession(pathId, routeSessionId);+ useMasteryStudySession(pathId, routeSessionId, courseId);const hasMessages = state.messages.length > 0;const prefillInputRef = useRef<((text: string) => void) | null>(null);/* ── Transcript scrolling ────────────────────────────────────────────diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex b4647c7b2..0c8245361 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -51,6 +51,7 @@ import {normalizeBookReferences,type BookReferencePayload,} from "@/lib/book-references";+import { courseTurnConfiguration } from "@/lib/course-session-scope";type SessionRuntimeStatus =| "idle"@@ -1787,10 +1788,14 @@ export function UnifiedChatProvider({});}dispatch({ type: "STREAM_START", key });- const effectiveTurnConfig =+ const effectiveTurnConfig = courseTurnConfiguration(+ effectiveConfig,+ session.courseId,+ );+ const finalTurnConfig =options?.persistUserMessage === false- ? { ...(effectiveConfig || {}), _persist_user_message: false }- : effectiveConfig;+ ? { ...effectiveTurnConfig, _persist_user_message: false }+ : effectiveTurnConfig;sendThroughRunner(key, {type: "start_turn",content,@@ -1834,8 +1839,8 @@ export function UnifiedChatProvider({...(effectiveLLMSelection? { llm_selection: effectiveLLMSelection }: {}),- ...(effectiveTurnConfig && Object.keys(effectiveTurnConfig).length > 0- ? { config: effectiveTurnConfig }+ ...(Object.keys(finalTurnConfig).length > 0+ ? { config: finalTurnConfig }: {}),// Send ``parent_message_id`` only when we have a real (positive)// server id to chain under, or when the caller explicitly pinneddiff --git a/web/hooks/useMasteryStudySession.ts b/web/hooks/useMasteryStudySession.tsindex ddaa8339f..e47ac4a43 100644--- a/web/hooks/useMasteryStudySession.ts+++ b/web/hooks/useMasteryStudySession.ts@@ -18,6 +18,7 @@ import {isMasteryDraftSessionReady,type MasteryDraftRouteGuard,} from "@/lib/mastery-study-route";+import { courseSessionConfiguration } from "@/lib/course-session-scope";/*** Resolves which topic and which chat session a study route is showing.@@ -31,6 +32,7 @@ import {export function useMasteryStudySession(pathId: string,routeSessionId?: string,+ courseId = "",) {const router = useRouter();const { t } = useTranslation();@@ -106,7 +108,7 @@ export function useMasteryStudySession(routeKey,previousSessionId: state.sessionId,};- newSession(sessionConfiguration);+ newSession(courseSessionConfiguration(sessionConfiguration, courseId));return;}@@ -146,6 +148,7 @@ export function useMasteryStudySession(});});}, [+ courseId,configureSession,currentRouteKey,loadSession,@@ -173,12 +176,18 @@ export function useMasteryStudySession(}))return;+ const courseQuery = courseId+ ? `?course=${encodeURIComponent(courseId)}`+ : "";router.replace(- `/mastery/${encodeURIComponent(pathId)}/study/${encodeURIComponent(newSessionId)}`,+ `/mastery/${encodeURIComponent(pathId)}/study/${encodeURIComponent(+ newSessionId,+ )}${courseQuery}`,{ scroll: false },);}, [currentRouteKey,+ courseId,pathId,routeSessionId,router,diff --git a/web/lib/course-handoff.ts b/web/lib/course-handoff.tsindex 52e2ba100..b7ed05fb2 100644--- a/web/lib/course-handoff.ts+++ b/web/lib/course-handoff.ts@@ -176,15 +176,17 @@ export function courseHandoffHref(payload: CourseHandoffPayload): string {const ref = encodeURIComponent(payload.ref_id);switch (payload.target) {case "immersive_reading":- // With nothing to open yet, the index is the honest destination — but it- // arrives course-scoped, so whatever the learner makes there attaches- // back here instead of stranding them one manual step from the course.- return payload.ref_id ? `/reading/${ref}` : `/reading?course=${course}`;+ // Every branch stays course-scoped: an existing workspace still opens a+ // conversation that belongs to this course, rather than only the empty+ // index honouring the context that sent the learner here.+ return payload.ref_id+ ? `/reading/${ref}?course=${course}`+ : `/reading?course=${course}`;case "mastery_path":// The study route, not the path overview: the overview has no composer,// so a prepared opening line would have nowhere to land.return payload.ref_id- ? `/mastery/${ref}/study`+ ? `/mastery/${ref}/study?course=${course}`: `/mastery?course=${course}`;case "question_bank":return `/space/questions?course=${course}`;diff --git a/web/lib/course-session-scope.ts b/web/lib/course-session-scope.tsnew file mode 100644index 000000000..82703ef19--- /dev/null+++ b/web/lib/course-session-scope.ts@@ -0,0 +1,18 @@+/** Wire-level course scope shared by the standalone study surfaces. */++export function courseSessionConfiguration<T extends object>(+ configuration: T,+ courseId: string,+): T | (T & { courseId: string }) {+ const cleanCourseId = courseId.trim();+ return cleanCourseId+ ? { ...configuration, courseId: cleanCourseId }+ : configuration;+}++export function courseTurnConfiguration(+ configuration: Record<string, unknown> | undefined,+ courseId: string,+): Record<string, unknown> {+ return { ...(configuration || {}), _course_id: courseId.trim() };+}diff --git a/web/tests/course-handoff.test.ts b/web/tests/course-handoff.test.tsindex 9e5a37073..0067616d7 100644--- a/web/tests/course-handoff.test.ts+++ b/web/tests/course-handoff.test.ts@@ -8,6 +8,10 @@ import {stripLeakedHandoffJson,targetAcceptsPrompt,} from "../lib/course-handoff";+import {+ courseSessionConfiguration,+ courseTurnConfiguration,+} from "../lib/course-session-scope";function toolResult(handoff: Record<string, unknown>, nested = true) {const payload = { course_handoff: handoff };@@ -99,8 +103,44 @@ test("mastery hand-offs land on the study route, which has a composer", () => {label: "",course_id: "c1",}),- "/mastery/path%201%2Fa/study",+ "/mastery/path%201%2Fa/study?course=c1",+ );+});++test("specific reading hand-offs keep the course scope", () => {+ // Opening an existing workspace must not drop the learner back into an+ // unclassified conversation. The course id is already server-owned here.+ assert.equal(+ courseHandoffHref({+ target: "immersive_reading",+ prompt: "",+ reason: "",+ ref_id: "rw 1/a",+ label: "",+ course_id: "course os",+ }),+ "/reading/rw%201%2Fa?course=course%20os",+ );+});++test("study sessions and turns carry the course scope", () => {+ const session = courseSessionConfiguration(+ { capability: "mastery_path", masteryPathId: "path_1" },+ " course_os ",+ );+ assert.deepEqual(session, {+ capability: "mastery_path",+ masteryPathId: "path_1",+ courseId: "course_os",+ });++ assert.deepEqual(+ courseTurnConfiguration({ subagent_consult_budget: 2 }, " course_os "),+ { subagent_consult_budget: 2, _course_id: "course_os" },);+ // An empty id is sent explicitly so the backend clears stale scope rather+ // than silently inheriting a previous session preference.+ assert.deepEqual(courseTurnConfiguration(undefined, " "), { _course_id: "" });});test("a hand-off with no ref falls back to the surface's index, still scoped", () => {