mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 13:19:44 +08:00
A course held the right model — the syllabus that gives progress a
denominator, resources as references, conventions apart from the
assistant's own notes — but almost nothing crossed the edges between it
and the surfaces it was supposed to contain.
Getting in. Course Study was offered in the composer's mode menu while
the only way to bind a course was a link on the course page, so choosing
it there produced a conversation identical to an inert one, and the mode
advised pressing a button that did not exist. The composer now carries
the binding next to the mode: shown whenever there is one, and offered
as an unfinished field in Course Study when there is not. `_course_id`
rides every turn, so detaching detaches and the pill can never drift
from what the turn actually saw.
What a conversation inherits. `default_capability` and `default_persona`
were stored, validated and returned by the API while changing nothing:
`_apply_course_defaults` only fills fields a payload *omits*, and this
composer always sent all of them. They are applied client-side now,
along with the course's knowledge bases, where the learner can watch the
mode and material become the course's before they type. The dialog grows
the editor they never had.
Conventions. "Every conversation in this course starts knowing these" was
true only if the model happened to call `course_overview`. They ride in
the per-turn summary now, and — because the promise is not scoped to one
mode — in the system prompt of any course-bound turn.
Coming back. Mastery Path and Immersive Reading now read `?course=`,
scope themselves to it, and attach whatever is built there; the tiles and
hand-offs pass it; the picker offers to start one. A course could only
ever reference what already existed, so filling a new one meant leaving,
building, and remembering to return.
Hand-offs. A target with no ref stored an opening line for an index that
never consumes it, which then surfaced weeks later in an unrelated path.
An unresolvable ref was passed straight through: observed live, a
syllabus unit id ("u2") sent as a mastery path, producing a card pointing
at a page that does not exist. Refs are checked against the subsystem
that owns them — existence, not membership, since a path built outside
this course routes perfectly well.
Also: the sidebar groups conversations by course, so filing them is
finally readable; a course-scoped notebook console no longer shows
another course's notes beside a list saying there are none (the clear
raced an in-flight detail fetch that landed after it); a hand-off the
model also printed as prose is not rendered twice; a provider error is no
longer stored as a conversation's permanent title; `/space/courses` goes,
having been an unreferenced copy of `/courses`; and the Visualize mode
description gets its missing Chinese.
317 lines
9.1 KiB
TypeScript
317 lines
9.1 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import {
|
|
createNotebook,
|
|
deleteNotebook,
|
|
deleteNotebookRecord,
|
|
getNotebook,
|
|
listNotebooks,
|
|
relocateNotebookRecord,
|
|
updateNotebook,
|
|
updateNotebookRecord,
|
|
type NotebookRecordItem,
|
|
type NotebookSummary,
|
|
} from "@/lib/notebook-api";
|
|
|
|
/**
|
|
* Every notebook read/write the console needs, in one place.
|
|
*
|
|
* The UI components below stay presentational: they render what this hook
|
|
* exposes and call back into it. Mutations update local state optimistically
|
|
* where the server response is predictable (rename, delete) and re-fetch
|
|
* where it is not (create, move), so the list never shows a stale count.
|
|
*/
|
|
|
|
export interface NotebookLibrary {
|
|
notebooks: NotebookSummary[];
|
|
selectedId: string | null;
|
|
selected: NotebookDetailState | null;
|
|
loading: boolean;
|
|
detailLoading: boolean;
|
|
error: string | null;
|
|
detailError: string | null;
|
|
select: (notebookId: string | null) => void;
|
|
reload: () => Promise<void>;
|
|
create: (name: string, description: string) => Promise<string | null>;
|
|
rename: (
|
|
notebookId: string,
|
|
changes: { name?: string; description?: string; color?: string },
|
|
) => Promise<void>;
|
|
remove: (notebookId: string) => Promise<void>;
|
|
editRecord: (
|
|
recordId: string,
|
|
changes: { title?: string; summary?: string; output?: string },
|
|
) => Promise<void>;
|
|
removeRecord: (recordId: string) => Promise<void>;
|
|
relocateRecord: (
|
|
recordId: string,
|
|
targetNotebookId: string,
|
|
mode: "move" | "copy",
|
|
) => Promise<void>;
|
|
}
|
|
|
|
export interface NotebookDetailState extends NotebookSummary {
|
|
records: NotebookRecordItem[];
|
|
}
|
|
|
|
function messageOf(error: unknown): string {
|
|
if (error instanceof Error) return error.message;
|
|
return String(error);
|
|
}
|
|
|
|
export function useNotebookLibrary(
|
|
initialId?: string | null,
|
|
/**
|
|
* Ids this visit is allowed to open, or null for the whole library.
|
|
*
|
|
* The scope has to live here rather than being corrected by the caller after
|
|
* the fact: `reload` picks a default whenever the current selection is gone,
|
|
* and a caller-side correction loses that race every time the list refreshes
|
|
* — after creating a notebook, after deleting one — putting an out-of-scope
|
|
* notebook back in the pane each time.
|
|
*/
|
|
scopeIds?: readonly string[] | null,
|
|
): NotebookLibrary {
|
|
// Read through a ref so `reload` stays stable across renders: callers build
|
|
// this list with `useMemo` at best, and a fresh array identity would restart
|
|
// the load effect on every render.
|
|
const scopeRef = useRef<readonly string[] | null>(scopeIds ?? null);
|
|
scopeRef.current = scopeIds ?? null;
|
|
const inScope = useCallback(
|
|
(id: string) => !scopeRef.current || scopeRef.current.includes(id),
|
|
[],
|
|
);
|
|
|
|
const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);
|
|
const [selectedId, setSelectedId] = useState<string | null>(
|
|
initialId ?? null,
|
|
);
|
|
const [selected, setSelected] = useState<NotebookDetailState | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [detailLoading, setDetailLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [detailError, setDetailError] = useState<string | null>(null);
|
|
|
|
// Detail fetches are racy — clicking through the list fires several. Only
|
|
// the newest one is allowed to write state, otherwise a slow earlier
|
|
// response can overwrite the notebook the user is actually looking at.
|
|
const detailRequestRef = useRef(0);
|
|
|
|
const loadDetail = useCallback(async (notebookId: string) => {
|
|
const requestId = ++detailRequestRef.current;
|
|
setDetailLoading(true);
|
|
setDetailError(null);
|
|
try {
|
|
const data = await getNotebook(notebookId);
|
|
if (detailRequestRef.current !== requestId) return;
|
|
setSelected({ ...data, records: data.records ?? [] });
|
|
} catch (err) {
|
|
if (detailRequestRef.current !== requestId) return;
|
|
setSelected(null);
|
|
setDetailError(messageOf(err));
|
|
} finally {
|
|
if (detailRequestRef.current === requestId) setDetailLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const reload = useCallback(async () => {
|
|
setError(null);
|
|
try {
|
|
const next = await listNotebooks();
|
|
setNotebooks(next);
|
|
setSelectedId((current) => {
|
|
const allowed = next.filter((notebook) => inScope(notebook.id));
|
|
if (current && allowed.some((n) => n.id === current)) return current;
|
|
return allowed.length ? allowed[0].id : null;
|
|
});
|
|
} catch (err) {
|
|
setError(messageOf(err));
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [inScope]);
|
|
|
|
useEffect(() => {
|
|
void reload();
|
|
}, [reload]);
|
|
|
|
useEffect(() => {
|
|
if (!selectedId) {
|
|
// Bump the request counter as well as clearing. `loadDetail` stamps each
|
|
// fetch and drops its own result if a *newer* one started — but clearing
|
|
// starts no fetch, so without this an in-flight response lands after the
|
|
// clear and puts the notebook straight back on screen. That is what made
|
|
// a course with no notebooks show some other course's notes beside a list
|
|
// saying it had none.
|
|
detailRequestRef.current += 1;
|
|
setSelected(null);
|
|
setDetailError(null);
|
|
setDetailLoading(false);
|
|
return;
|
|
}
|
|
void loadDetail(selectedId);
|
|
}, [selectedId, loadDetail]);
|
|
|
|
const select = useCallback((notebookId: string | null) => {
|
|
setSelectedId(notebookId);
|
|
}, []);
|
|
|
|
const create = useCallback(
|
|
async (name: string, description: string) => {
|
|
const trimmed = name.trim();
|
|
if (!trimmed) return null;
|
|
const created = await createNotebook({
|
|
name: trimmed,
|
|
description: description.trim(),
|
|
});
|
|
await reload();
|
|
setSelectedId(created.id);
|
|
return created.id;
|
|
},
|
|
[reload],
|
|
);
|
|
|
|
const rename = useCallback(
|
|
async (
|
|
notebookId: string,
|
|
changes: { name?: string; description?: string; color?: string },
|
|
) => {
|
|
const updated = await updateNotebook(notebookId, changes);
|
|
setNotebooks((prev) =>
|
|
prev.map((n) => (n.id === notebookId ? { ...n, ...updated } : n)),
|
|
);
|
|
setSelected((prev) =>
|
|
prev && prev.id === notebookId ? { ...prev, ...updated } : prev,
|
|
);
|
|
},
|
|
[],
|
|
);
|
|
|
|
const remove = useCallback(
|
|
async (notebookId: string) => {
|
|
await deleteNotebook(notebookId);
|
|
setNotebooks((prev) => prev.filter((n) => n.id !== notebookId));
|
|
setSelectedId((current) => {
|
|
if (current !== notebookId) return current;
|
|
const rest = notebooks.filter((n) => n.id !== notebookId);
|
|
return rest.length ? rest[0].id : null;
|
|
});
|
|
},
|
|
[notebooks],
|
|
);
|
|
|
|
// Keep the sidebar's record count honest after any record-level change
|
|
// without paying for a full list refetch.
|
|
const adjustCount = useCallback((notebookId: string, delta: number) => {
|
|
setNotebooks((prev) =>
|
|
prev.map((n) =>
|
|
n.id === notebookId
|
|
? { ...n, record_count: Math.max(0, (n.record_count ?? 0) + delta) }
|
|
: n,
|
|
),
|
|
);
|
|
}, []);
|
|
|
|
const editRecord = useCallback(
|
|
async (
|
|
recordId: string,
|
|
changes: { title?: string; summary?: string; output?: string },
|
|
) => {
|
|
if (!selectedId) return;
|
|
const updated = await updateNotebookRecord(selectedId, recordId, changes);
|
|
setSelected((prev) =>
|
|
prev
|
|
? {
|
|
...prev,
|
|
records: prev.records.map((r) =>
|
|
r.id === recordId ? { ...r, ...updated } : r,
|
|
),
|
|
}
|
|
: prev,
|
|
);
|
|
},
|
|
[selectedId],
|
|
);
|
|
|
|
const removeRecord = useCallback(
|
|
async (recordId: string) => {
|
|
if (!selectedId) return;
|
|
await deleteNotebookRecord(selectedId, recordId);
|
|
setSelected((prev) =>
|
|
prev
|
|
? { ...prev, records: prev.records.filter((r) => r.id !== recordId) }
|
|
: prev,
|
|
);
|
|
adjustCount(selectedId, -1);
|
|
},
|
|
[selectedId, adjustCount],
|
|
);
|
|
|
|
const relocateRecord = useCallback(
|
|
async (
|
|
recordId: string,
|
|
targetNotebookId: string,
|
|
mode: "move" | "copy",
|
|
) => {
|
|
if (!selectedId) return;
|
|
await relocateNotebookRecord(
|
|
selectedId,
|
|
recordId,
|
|
targetNotebookId,
|
|
mode,
|
|
);
|
|
if (mode === "move") {
|
|
setSelected((prev) =>
|
|
prev
|
|
? {
|
|
...prev,
|
|
records: prev.records.filter((r) => r.id !== recordId),
|
|
}
|
|
: prev,
|
|
);
|
|
adjustCount(selectedId, -1);
|
|
}
|
|
adjustCount(targetNotebookId, 1);
|
|
},
|
|
[selectedId, adjustCount],
|
|
);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
notebooks,
|
|
selectedId,
|
|
selected,
|
|
loading,
|
|
detailLoading,
|
|
error,
|
|
detailError,
|
|
select,
|
|
reload,
|
|
create,
|
|
rename,
|
|
remove,
|
|
editRecord,
|
|
removeRecord,
|
|
relocateRecord,
|
|
}),
|
|
[
|
|
notebooks,
|
|
selectedId,
|
|
selected,
|
|
loading,
|
|
detailLoading,
|
|
error,
|
|
detailError,
|
|
select,
|
|
reload,
|
|
create,
|
|
rename,
|
|
remove,
|
|
editRecord,
|
|
removeRecord,
|
|
relocateRecord,
|
|
],
|
|
);
|
|
}
|