Skip to content

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

feat(video-learning): add timestamped transcript notes (#1137)

XZH4032e37f2625
diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.py
index bdf777ccd..9ca6897e4 100644
--- a/deeptutor/api/routers/notebook.py
+++ b/deeptutor/api/routers/notebook.py
@@ -66,7 +66,14 @@ class AddRecordRequest(BaseModel):
notebook_ids: list[str]
record_type: Literal[
- "solve", "question", "research", "chat", "co_writer", "tutorbot", "reading"
+ "solve",
+ "question",
+ "research",
+ "chat",
+ "co_writer",
+ "tutorbot",
+ "reading",
+ "video_learning",
]
title: str
summary: str = ""
diff --git a/deeptutor/api/routers/video_learning.py b/deeptutor/api/routers/video_learning.py
index 1314403ef..4ae56489a 100644
--- a/deeptutor/api/routers/video_learning.py
+++ b/deeptutor/api/routers/video_learning.py
@@ -12,6 +12,7 @@ import httpx
from pydantic import BaseModel, Field
from starlette.background import BackgroundTask
+from deeptutor.services.notebook.service import NotebookCorruptedError
from deeptutor.video_learning import (
TimedMediaError,
TimedMediaNotFound,
@@ -22,6 +23,7 @@ from deeptutor.video_learning import (
save_video_learning_settings,
test_invidious_connection,
)
+from deeptutor.video_learning import notes as video_notes
router = APIRouter()
settings_router = APIRouter()
@@ -41,6 +43,15 @@ class ProgressRequest(BaseModel):
duration_seconds: float = Field(default=0, ge=0, le=24 * 60 * 60)
+class CreateVideoNoteRequest(BaseModel):
+ body: str = Field(min_length=1, max_length=20_000)
+ time_seconds: float = Field(ge=0, le=24 * 60 * 60)
+
+
+class UpdateVideoNoteRequest(BaseModel):
+ body: str = Field(min_length=1, max_length=20_000)
+
+
class YouTubeSettings(BaseModel):
transcript_provider: str = Field(default="youtube_transcript_api", max_length=64)
@@ -65,6 +76,19 @@ def _http_error(exc: Exception) -> HTTPException:
return HTTPException(status_code=500, detail="Video learning could not complete the request.")
+def _note_error(exc: Exception) -> HTTPException:
+ if isinstance(exc, NotebookCorruptedError):
+ return HTTPException(
+ status_code=409,
+ detail={
+ "code": "notebook_unreadable",
+ "notebook_id": exc.notebook_id,
+ "message": str(exc),
+ },
+ )
+ return _http_error(exc)
+
+
@settings_router.get("")
async def get_video_learning_settings() -> dict[str, Any]:
return load_video_learning_settings()
@@ -126,6 +150,48 @@ async def save_video_progress(material_id: str, payload: ProgressRequest) -> dic
raise _http_error(exc) from exc
[email protected]("/materials/{material_id}/notes")
+async def list_video_notes(material_id: str) -> list[dict[str, Any]]:
+ try:
+ return video_notes.list_notes(video_notes.get_notebook_manager(), material_id)
+ except Exception as exc:
+ raise _note_error(exc) from exc
+
+
[email protected]("/materials/{material_id}/notes")
+async def create_video_note(material_id: str, payload: CreateVideoNoteRequest) -> dict[str, Any]:
+ try:
+ return video_notes.create_note(
+ video_notes.get_notebook_manager(),
+ material_id,
+ payload.body,
+ payload.time_seconds,
+ )
+ except Exception as exc:
+ raise _note_error(exc) from exc
+
+
[email protected]("/materials/{material_id}/notes/{note_id}")
+async def update_video_note(
+ material_id: str, note_id: str, payload: UpdateVideoNoteRequest
+) -> dict[str, Any]:
+ try:
+ return video_notes.update_note(
+ video_notes.get_notebook_manager(), material_id, note_id, payload.body
+ )
+ except Exception as exc:
+ raise _note_error(exc) from exc
+
+
[email protected]("/materials/{material_id}/notes/{note_id}")
+async def delete_video_note(material_id: str, note_id: str) -> dict[str, str]:
+ try:
+ deleted = video_notes.delete_note(video_notes.get_notebook_manager(), material_id, note_id)
+ return {"status": "deleted" if deleted else "missing"}
+ except Exception as exc:
+ raise _note_error(exc) from exc
+
+
def _vtt_timestamp(value: Any) -> str:
milliseconds = int(round(max(0.0, float(value or 0)) * 1000))
hours, remainder = divmod(milliseconds, 3_600_000)
diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.py
index 6cbdc45a5..fb14276bd 100644
--- a/deeptutor/services/notebook/service.py
+++ b/deeptutor/services/notebook/service.py
@@ -36,6 +36,7 @@ class RecordType(str, Enum):
CO_WRITER = "co_writer"
TUTORBOT = "tutorbot"
READING = "reading"
+ VIDEO_LEARNING = "video_learning"
class NotebookRecord(BaseModel):
@@ -257,6 +258,20 @@ class NotebookManager:
self._touch_index_entry(notebook_id, notebook)
return notebook
+ def get_or_create_notebook(
+ self, name: str, description: str = "", color: str = "#3B82F6", icon: str = "book"
+ ) -> dict:
+ """Return an existing notebook with this exact name, or create one."""
+ with self._index_lock:
+ for row in self._load_index().get("notebooks", []):
+ if row.get("name") != name:
+ continue
+ notebook_id = str(row.get("id") or "")
+ notebook = self._load_notebook(notebook_id) if notebook_id else None
+ if notebook:
+ return notebook
+ return self.create_notebook(name=name, description=description, color=color, icon=icon)
+
def list_notebooks(self) -> list[dict]:
"""List every notebook on disk, newest first.
diff --git a/deeptutor/video_learning/notes.py b/deeptutor/video_learning/notes.py
new file mode 100644
index 000000000..fa2483fc8
--- /dev/null
+++ b/deeptutor/video_learning/notes.py
@@ -0,0 +1,205 @@
+"""Persistent notes for timed-media learning materials."""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from deeptutor.services.notebook.service import (
+ NotebookCorruptedError,
+ NotebookManager,
+ RecordType,
+ get_notebook_manager,
+)
+from deeptutor.video_learning.service import (
+ TimedMediaError,
+ TimedMediaNotFound,
+ get_timed_media_store,
+)
+
+NOTEBOOK_NAME = "Video Learning"
+MAX_QUOTE_CHARS = 280
+
+
+def _format_time(seconds: float) -> str:
+ total = max(0, int(seconds))
+ hours, remainder = divmod(total, 3600)
+ minutes, seconds_part = divmod(remainder, 60)
+ if hours:
+ return f"{hours}:{minutes:02d}:{seconds_part:02d}"
+ return f"{minutes}:{seconds_part:02d}"
+
+
+def _clip_text(value: Any, limit: int = MAX_QUOTE_CHARS) -> str:
+ text = " ".join(str(value or "").split())
+ if len(text) <= limit:
+ return text
+ return f"{text[: limit - 3].rstrip()}..."
+
+
+def _segment_at(material: dict[str, Any], time_seconds: float) -> dict[str, Any] | None:
+ segments = [row for row in material.get("segments") or [] if isinstance(row, dict)]
+ if not segments:
+ cues = [
+ row for row in material.get("transcript", {}).get("cues") or [] if isinstance(row, dict)
+ ]
+ segments = [dict(row, locator=index) for index, row in enumerate(cues, start=1)]
+ containing = [
+ row
+ for row in segments
+ if float(row.get("start") or 0) <= time_seconds <= float(row.get("end") or 0)
+ ]
+ if containing:
+ return containing[-1]
+ preceding = [row for row in segments if float(row.get("start") or 0) <= time_seconds]
+ return preceding[-1] if preceding else (segments[0] if segments else None)
+
+
+def _is_material_note(record: dict[str, Any], material_id: str) -> bool:
+ metadata = record.get("metadata") if isinstance(record.get("metadata"), dict) else {}
+ return (
+ str(record.get("type") or "") == RecordType.VIDEO_LEARNING.value
+ and str(metadata.get("material_id") or "") == material_id
+ )
+
+
+def _matching_records(
+ manager: NotebookManager, material_id: str, note_id: str | None = None
+) -> list[tuple[str, dict[str, Any]]]:
+ for notebook in manager.list_notebooks():
+ if notebook.get("unreadable"):
+ manager.get_notebook(str(notebook.get("id") or ""))
+
+ matches: list[tuple[str, dict[str, Any]]] = []
+ for notebook in manager.list_notebooks():
+ if notebook.get("unreadable"):
+ continue
+ notebook_id = str(notebook.get("id") or "")
+ try:
+ records = manager.get_records(notebook_id)
+ except NotebookCorruptedError:
+ continue
+ for record in records:
+ if not _is_material_note(record, material_id):
+ continue
+ if note_id is not None and str(record.get("id") or "") != note_id:
+ continue
+ matches.append((notebook_id, record))
+ return matches
+
+
+def _note(notebook_id: str, record: dict[str, Any]) -> dict[str, Any]:
+ metadata = record.get("metadata") if isinstance(record.get("metadata"), dict) else {}
+ updated_at = float(metadata.get("updated_at") or record.get("created_at") or 0)
+ return {
+ "notebook_id": notebook_id,
+ "note_id": str(record.get("id") or ""),
+ "material_id": str(metadata.get("material_id") or ""),
+ "body": str(record.get("output") or ""),
+ "time_seconds": float(metadata.get("time_seconds") or 0),
+ "locator": int(metadata.get("locator") or 0),
+ "quote": str(metadata.get("quote") or ""),
+ "created_at": float(record.get("created_at") or 0),
+ "updated_at": updated_at,
+ }
+
+
+def list_notes(manager: NotebookManager, material_id: str) -> list[dict[str, Any]]:
+ get_timed_media_store().get(material_id)
+ unique: dict[str, tuple[str, dict[str, Any]]] = {}
+ for notebook_id, record in _matching_records(manager, material_id):
+ unique.setdefault(str(record.get("id") or ""), (notebook_id, record))
+ notes = [_note(notebook_id, record) for notebook_id, record in unique.values()]
+ notes.sort(key=lambda row: (row["time_seconds"], row["created_at"], row["note_id"]))
+ return notes
+
+
+def create_note(
+ manager: NotebookManager, material_id: str, body: str, time_seconds: float
+) -> dict[str, Any]:
+ clean_body = body.strip()
+ if not clean_body:
+ raise TimedMediaError("A timed-media note needs text.")
+ material = get_timed_media_store().get(material_id)
+ duration = float(material.get("metadata", {}).get("duration_seconds") or 0)
+ if duration and time_seconds > duration:
+ raise TimedMediaError("Timed-media note timestamp is beyond the material duration.")
+
+ segment = _segment_at(material, time_seconds)
+ quote = _clip_text(segment.get("text")) if segment else ""
+ title = _clip_text(
+ str(material.get("metadata", {}).get("title") or "Timed media").strip() or "Timed media",
+ 140,
+ )
+ notebook = manager.get_or_create_notebook(
+ NOTEBOOK_NAME,
+ description="Notes captured while learning with timed media.",
+ color="#EF4444",
+ icon="video",
+ )
+ now = time.time()
+ result = manager.add_record(
+ notebook_ids=[str(notebook["id"])],
+ record_type=RecordType.VIDEO_LEARNING,
+ title=f"{title} - {_format_time(time_seconds)}",
+ summary=_clip_text(clean_body, 160),
+ user_query=quote,
+ output=clean_body,
+ metadata={
+ "material_id": material_id,
+ "time_seconds": time_seconds,
+ "locator": int(segment.get("locator") or 0) if segment else 0,
+ "quote": quote,
+ "updated_at": now,
+ },
+ )
+ if not result.get("added_to_notebooks"):
+ raise TimedMediaError("The Video Learning notebook could not be saved.")
+ return _note(str(notebook["id"]), result["record"])
+
+
+def update_note(
+ manager: NotebookManager, material_id: str, note_id: str, body: str
+) -> dict[str, Any]:
+ clean_body = body.strip()
+ if not clean_body:
+ raise TimedMediaError("A timed-media note needs text.")
+ get_timed_media_store().get(material_id)
+ matches = _matching_records(manager, material_id, note_id)
+ if not matches:
+ raise TimedMediaNotFound("Timed-media note was not found.")
+ now = time.time()
+ updated: dict[str, Any] | None = None
+ for notebook_id, record in matches:
+ updated = manager.update_record(
+ notebook_id,
+ str(record.get("id") or ""),
+ summary=_clip_text(clean_body, 160),
+ output=clean_body,
+ metadata={"updated_at": now},
+ )
+ if updated is None:
+ raise TimedMediaNotFound("Timed-media note was not found.")
+ return _note(matches[0][0], updated)
+
+
+def delete_note(manager: NotebookManager, material_id: str, note_id: str) -> bool:
+ get_timed_media_store().get(material_id)
+ matches = _matching_records(manager, material_id, note_id)
+ if not matches:
+ raise TimedMediaNotFound("Timed-media note was not found.")
+ removed = [
+ manager.remove_record(notebook_id, str(record.get("id") or ""))
+ for notebook_id, record in matches
+ ]
+ return any(removed)
+
+
+__all__ = [
+ "NOTEBOOK_NAME",
+ "create_note",
+ "delete_note",
+ "get_notebook_manager",
+ "list_notes",
+ "update_note",
+]
diff --git a/tests/video_learning/test_router.py b/tests/video_learning/test_router.py
index e7d69b3f1..e23308e4e 100644
--- a/tests/video_learning/test_router.py
+++ b/tests/video_learning/test_router.py
@@ -9,6 +9,8 @@ import pytest
from deeptutor.api.routers import video_learning
from deeptutor.api.routers.auth import require_admin, require_auth
+from deeptutor.services.notebook.service import NotebookManager
+from deeptutor.video_learning import notes as video_notes
from deeptutor.video_learning import service
@@ -22,11 +24,21 @@ class _Paths:
@pytest.fixture
-def client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> TestClient:
+def notebook_manager(tmp_path: Path) -> NotebookManager:
+ return NotebookManager(base_dir=str(tmp_path / "notebooks"))
+
+
+def client(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ notebook_manager: NotebookManager,
+) -> TestClient:
monkeypatch.setattr(service, "get_current_path_service", lambda: _Paths(tmp_path))
monkeypatch.setattr(
service, "video_learning_settings_path", lambda: tmp_path / "video_learning.json"
)
+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: notebook_manager)
app = FastAPI()
app.include_router(video_learning.router, prefix="/api/v1/video-learning")
return TestClient(app)
@@ -100,6 +112,83 @@ def test_progress_clamps_to_duration_and_unknown_material_is_404(client: TestCli
assert missing.status_code == 404
+def test_video_notes_use_notebook_storage_and_stay_material_scoped(
+ client: TestClient,
+ notebook_manager: NotebookManager,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ material = _material()
+ service.get_timed_media_store().save(material)
+ material_id = str(material["material_id"])
+ notes_url = f"/api/v1/video-learning/materials/{material_id}/notes"
+
+ created_response = client.post(
+ notes_url, json={"body": " Revisit the opening idea. ", "time_seconds": 2}
+ )
+
+ assert created_response.status_code == 200
+ created = created_response.json()
+ assert created["material_id"] == material_id
+ assert created["body"] == "Revisit the opening idea."
+ assert created["time_seconds"] == 2.0
+ assert created["locator"] == 1
+ assert "one" in created["quote"]
+ assert created["notebook_id"]
+
+ notebook = notebook_manager.get_notebook(created["notebook_id"])
+ assert notebook is not None
+ assert notebook["name"] == video_notes.NOTEBOOK_NAME
+ assert notebook["records"][0]["type"] == "video_learning"
+ assert notebook["records"][0]["metadata"]["material_id"] == material_id
+ persisted = str(notebook)
+ assert "https://youtu.be" not in persisted
+ assert "provider_cache" not in persisted
+ assert "dQw4w9WgXcQ" not in persisted
+
+ material["metadata"]["title"] = "T" * 300
+ material["transcript"]["cues"][0]["text"] = "q" * 400
+ service.get_timed_media_store().save(material)
+ bounded_response = client.post(notes_url, json={"body": "Note", "time_seconds": 2})
+ assert bounded_response.status_code == 200
+ assert len(bounded_response.json()["quote"]) <= 280
+ records = notebook_manager.get_notebook(created["notebook_id"])["records"]
+ assert len(records[-1]["title"]) <= 160
+
+ updated_response = client.put(
+ f"{notes_url}/{created['note_id']}", json={"body": "Updated note."}
+ )
+ assert updated_response.status_code == 200
+ assert updated_response.json()["body"] == "Updated note."
+ assert (
+ notebook_manager.get_notebook(created["notebook_id"])["records"][0]["summary"]
+ == "Updated note."
+ )
+
+ other_manager = NotebookManager(
+ base_dir=str(notebook_manager.base_dir.parent / "other-account-notebooks")
+ )
+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: other_manager)
+ assert client.get(notes_url).json() == []
+
+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: notebook_manager)
+ for note in client.get(notes_url).json():
+ delete_response = client.delete(f"{notes_url}/{note['note_id']}")
+ assert delete_response.status_code == 200
+ assert client.get(notes_url).json() == []
+
+
+def test_video_note_errors_are_bounded_and_useful(client: TestClient) -> None:
+ material = _material(duration=100)
+ service.get_timed_media_store().save(material)
+ notes_url = f"/api/v1/video-learning/materials/{material['material_id']}/notes"
+
+ assert client.post(notes_url, json={"body": " ", "time_seconds": 2}).status_code == 400
+ assert client.post(notes_url, json={"body": "Note", "time_seconds": 101}).status_code == 400
+ assert client.post(notes_url, json={"body": "", "time_seconds": 2}).status_code == 422
+ assert client.get("/api/v1/video-learning/materials/0123456789abcdef/notes").status_code == 404
+ assert client.put(f"{notes_url}/missing-note", json={"body": "Note"}).status_code == 404
+
+
def test_progress_does_not_replace_known_duration_with_client_value(client: TestClient) -> None:
material = _material(duration=100)
service.get_timed_media_store().save(material)
diff --git a/web/components/notebook/NotebookRecordRow.tsx b/web/components/notebook/NotebookRecordRow.tsx
index a7d58b04a..ce85594cb 100644
--- a/web/components/notebook/NotebookRecordRow.tsx
+++ b/web/components/notebook/NotebookRecordRow.tsx
@@ -10,6 +10,7 @@ import {
NotebookPen,
Pencil,
Search,
+ Video,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
@@ -68,6 +69,11 @@ const BADGES: Record<
"bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",
icon: Pencil,
},
+ video_learning: {
+ labelKey: "Video Learning",
+ className: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",
+ icon: Video,
+ },
};
const FALLBACK_BADGE = {
diff --git a/web/components/watching/WatchingPane.tsx b/web/components/watching/WatchingPane.tsx
index 96fc4261a..9c7c35b43 100644
--- a/web/components/watching/WatchingPane.tsx
+++ b/web/components/watching/WatchingPane.tsx
@@ -3,22 +3,37 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
AlertTriangle,
+ Check,
+ Captions,
ExternalLink,
Loader2,
+ Pencil,
Play,
RotateCcw,
+ StickyNote,
+ Trash2,
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { useWatching } from "@/context/WatchingContext";
+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import type { PlayerController } from "@/lib/video-player-controller";
-import { saveVideoProgress } from "@/lib/video-learning-api";
+import {
+ createVideoNote,
+ deleteVideoNote,
+ listVideoNotes,
+ saveVideoProgress,
+ updateVideoNote,
+ type VideoNote,
+} from "@/lib/video-learning-api";
import { videoTimeFromHref } from "@/lib/watching-citations";
import { WatchingPlayer } from "./WatchingPlayer";
export const WATCHING_ASK_EVENT = "dt:watching-ask";
+type WatchTab = "transcript" | "notes";
+
export function WatchingPane({ onClose }: { onClose(): void }) {
const { t } = useTranslation();
const {
@@ -35,8 +50,17 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
} = useWatching();
const [input, setInput] = useState("");
const [playerError, setPlayerError] = useState<string | null>(null);
+ const [tab, setTab] = useState<WatchTab>("transcript");
const [time, setTime] = useState(0);
const [duration, setDuration] = useState(0);
+ const [notes, setNotes] = useState<VideoNote[]>([]);
+ const [notesLoading, setNotesLoading] = useState(false);
+ const [notesError, setNotesError] = useState<string | null>(null);
+ const [noteDraft, setNoteDraft] = useState("");
+ const [editingNoteId, setEditingNoteId] = useState<string | null>(null);
+ const [editingDraft, setEditingDraft] = useState("");
+ const [noteBusy, setNoteBusy] = useState(false);
+ const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
const controllerRef = useRef<PlayerController | null>(null);
const lastSavedRef = useRef(0);
const stateRef = useRef({ time: 0, duration: 0 });
@@ -130,6 +154,114 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
);
};
+ const materialId = material?.material_id ?? null;
+ const reloadNotes = useCallback(async () => {
+ if (!materialId) return;
+ setNotesLoading(true);
+ setNotesError(null);
+ try {
+ setNotes(await listVideoNotes(materialId));
+ } catch (caught) {
+ setNotesError(
+ caught instanceof Error
+ ? caught.message
+ : t("Notes could not be loaded."),
+ );
+ } finally {
+ setNotesLoading(false);
+ }
+ }, [materialId, t]);
+
+ useEffect(() => {
+ if (!materialId) {
+ setNotes([]);
+ setNotesError(null);
+ setNotesLoading(false);
+ setNoteDraft("");
+ setEditingNoteId(null);
+ return;
+ }
+ void reloadNotes();
+ }, [materialId, reloadNotes]);
+
+ const sortNotes = (rows: VideoNote[]) =>
+ [...rows].sort(
+ (left, right) =>
+ left.time_seconds - right.time_seconds ||
+ left.created_at - right.created_at ||
+ left.note_id.localeCompare(right.note_id),
+ );
+
+ const addNote = async () => {
+ if (!material || !noteDraft.trim() || noteBusy) return;
+ setNoteBusy(true);
+ setNotesError(null);
+ try {
+ const saved = await createVideoNote(
+ material.material_id,
+ noteDraft.trim(),
+ time,
+ );
+ setNotes((current) => sortNotes([...current, saved]));
+ setNoteDraft("");
+ } catch (caught) {
+ setNotesError(
+ caught instanceof Error ? caught.message : t("Note was not saved."),
+ );
+ } finally {
+ setNoteBusy(false);
+ }
+ };
+
+ const saveEditedNote = async () => {
+ if (!material || !editingNoteId || !editingDraft.trim() || noteBusy) return;
+ setNoteBusy(true);
+ setNotesError(null);
+ try {
+ const saved = await updateVideoNote(
+ material.material_id,
+ editingNoteId,
+ editingDraft.trim(),
+ );
+ setNotes((current) =>
+ sortNotes(
+ current.map((note) => (note.note_id === saved.note_id ? saved : note)),
+ ),
+ );
+ setEditingNoteId(null);
+ setEditingDraft("");
+ } catch (caught) {
+ setNotesError(
+ caught instanceof Error ? caught.message : t("Note was not saved."),
+ );
+ } finally {
+ setNoteBusy(false);
+ }
+ };
+
+ const confirmDelete = async () => {
+ if (!material || !pendingDeleteId || noteBusy) return;
+ setNoteBusy(true);
+ setNotesError(null);
+ try {
+ await deleteVideoNote(material.material_id, pendingDeleteId);
+ setNotes((current) =>
+ current.filter((note) => note.note_id !== pendingDeleteId),
+ );
+ if (editingNoteId === pendingDeleteId) {
+ setEditingNoteId(null);
+ setEditingDraft("");
+ }
+ setPendingDeleteId(null);
+ } catch (caught) {
+ setNotesError(
+ caught instanceof Error ? caught.message : t("Note was not deleted."),
+ );
+ } finally {
+ setNoteBusy(false);
+ }
+ };
+
const closePane = () => {
persist();
close();
@@ -297,48 +429,235 @@ export function WatchingPane({ onClose }: { onClose(): void }) {
</a>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-4">
- {material.transcript.status !== "ready" ? (
- <div className="rounded-lg border border-[var(--border)] p-4 text-sm text-[var(--muted-foreground)]">
- {t(
- "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.",
- {
- reason: material.transcript.reason || t("no captions"),
- },
- )}
- </div>
- ) : (
- <>
+ <div
+ className="mb-3 grid w-full max-w-56 grid-cols-2 rounded-lg bg-[var(--muted)] p-1"
+ role="tablist"
+ aria-label={t("Video learning panels")}
+ >
+ {(["transcript", "notes"] as const).map((item) => (
<button
+ key={item}
type="button"
- onClick={askHere}
- disabled={!cue}
- className="mb-3 rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-50"
+ role="tab"
+ aria-selected={tab === item}
+ onClick={() => {
+ setTab(item);
+ setEditingNoteId(null);
+ }}
+ className={`flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium ${tab === item ? "bg-[var(--background)] shadow-sm" : "text-[var(--muted-foreground)]"}`}
>
- {t("Explain here")}
+ {item === "transcript" ? (
+ <>
+ <Captions className="h-3.5 w-3.5" />
+ {t("Transcript")}
+ </>
+ ) : (
+ <>
+ <StickyNote className="h-3.5 w-3.5" />
+ {t("Video notes")}
+ </>
+ )}
</button>
- <div className="space-y-1">
- {material.transcript.cues.map((row, index) => {
- const active = row === cue;
- return (
- <button
- key={`${row.start}-${index}`}
- type="button"
- onClick={() => controllerRef.current?.seek(row.start)}
- className={`flex w-full gap-3 rounded-md px-2 py-1.5 text-left text-sm ${active ? "bg-blue-500/15 ring-1 ring-blue-500/30" : "hover:bg-[var(--muted)]"}`}
- >
- <span className="shrink-0 tabular-nums text-blue-600">
- {formatTime(row.start)}
- </span>
- <span>{row.text}</span>
- </button>
- );
- })}
+ ))}
+ </div>
+
+ {tab === "transcript" ? (
+ material.transcript.status !== "ready" ? (
+ <div className="rounded-lg border border-[var(--border)] p-4 text-sm text-[var(--muted-foreground)]">
+ {t(
+ "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.",
+ {
+ reason: material.transcript.reason || t("no captions"),
+ },
+ )}
</div>
- </>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={askHere}
+ disabled={!cue}
+ className="mb-3 rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-50"
+ >
+ {t("Explain here")}
+ </button>
+ <div className="space-y-1">
+ {material.transcript.cues.map((row, index) => {
+ const active = row === cue;
+ return (
+ <button
+ key={`${row.start}-${index}`}
+ type="button"
+ onClick={() => controllerRef.current?.seek(row.start)}
+ className={`flex w-full gap-3 rounded-md px-2 py-1.5 text-left text-sm ${active ? "bg-blue-500/15 ring-1 ring-blue-500/30" : "hover:bg-[var(--muted)]"}`}
+ >
+ <span className="shrink-0 tabular-nums text-blue-600">
+ {formatTime(row.start)}
+ </span>
+ <span>{row.text}</span>
+ </button>
+ );
+ })}
+ </div>
+ </>
+ )
+ ) : (
+ <div className="space-y-3">
+ <form
+ className="space-y-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void addNote();
+ }}
+ >
+ <textarea
+ value={noteDraft}
+ onChange={(event) => setNoteDraft(event.target.value)}
+ placeholder={t("Note at {{time}}", {
+ time: formatTime(time),
+ })}
+ className="min-h-20 w-full resize-y rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-sm"
+ />
+ <button
+ type="submit"
+ disabled={noteBusy || !noteDraft.trim()}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-50"
+ >
+ {noteBusy ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Check className="h-4 w-4" />
+ )}
+ {t("Add video note")}
+ </button>
+ </form>
+
+ {notesError && (
+ <p
+ role="alert"
+ className="rounded-lg border border-[var(--border)] bg-[var(--muted)] px-3 py-2 text-sm text-[var(--destructive)]"
+ >
+ {notesError}
+ </p>
+ )}
+
+ {notesLoading ? (
+ <p className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("Loading notes.")}
+ </p>
+ ) : notes.length ? (
+ notes.map((note) => (
+ <article
+ key={`${note.notebook_id}:${note.note_id}`}
+ className="rounded-lg border border-[var(--border)] p-3"
+ >
+ <div className="flex items-start gap-2">
+ <button
+ type="button"
+ onClick={() =>
+ controllerRef.current?.seek(note.time_seconds)
+ }
+ className="shrink-0 rounded px-1.5 py-0.5 font-mono text-xs tabular-nums text-blue-600 hover:bg-blue-500/10"
+ >
+ {formatTime(note.time_seconds)}
+ </button>
+ <div className="min-w-0 flex-1">
+ {editingNoteId === note.note_id ? (
+ <textarea
+ value={editingDraft}
+ onChange={(event) =>
+ setEditingDraft(event.target.value)
+ }
+ aria-label={t("Edit note at {{time}}", {
+ time: formatTime(note.time_seconds),
+ })}
+ className="min-h-20 w-full resize-y rounded-lg border border-[var(--border)] bg-transparent px-2 py-1.5 text-sm"
+ />
+ ) : (
+ <p className="whitespace-pre-wrap text-sm">
+ {note.body}
+ </p>
+ )}
+ {note.quote && (
+ <blockquote className="mt-2 border-l-2 border-[var(--border)] pl-2 text-xs text-[var(--muted-foreground)]">
+ {note.quote}
+ </blockquote>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {editingNoteId === note.note_id ? (
+ <>
+ <button
+ type="button"
+ onClick={() => void saveEditedNote()}
+ disabled={noteBusy || !editingDraft.trim()}
+ className="rounded-md p-1.5 hover:bg-[var(--muted)] disabled:opacity-50"
+ aria-label={t("Save video note")}
+ >
+ <Check className="h-4 w-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setEditingNoteId(null)}
+ disabled={noteBusy}
+ className="rounded-md p-1.5 hover:bg-[var(--muted)] disabled:opacity-50"
+ aria-label={t("Cancel")}
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </>
+ ) : (
+ <button
+ type="button"
+ onClick={() => {
+ setEditingNoteId(note.note_id);
+ setEditingDraft(note.body);
+ }}
+ disabled={noteBusy}
+ className="rounded-md p-1.5 hover:bg-[var(--muted)] disabled:opacity-50"
+ aria-label={t("Edit note at {{time}}", {
+ time: formatTime(note.time_seconds),
+ })}
+ >
+ <Pencil className="h-4 w-4" />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => setPendingDeleteId(note.note_id)}
+ disabled={noteBusy}
+ className="rounded-md p-1.5 text-[var(--destructive)] hover:bg-[var(--destructive)]/10 disabled:opacity-50"
+ aria-label={t("Delete note at {{time}}", {
+ time: formatTime(note.time_seconds),
+ })}
+ >
+ <Trash2 className="h-4 w-4" />
+ </button>
+ </div>
+ </div>
+ </article>
+ ))
+ ) : (
+ !notesError && <p className="text-sm">{t("No notes yet.")}</p>
+ )}
+ </div>
)}
</div>
</div>
)}
+
+ <ConfirmDialog
+ open={Boolean(pendingDeleteId)}
+ title={t("Delete this note?")}
+ confirmLabel={t("Delete")}
+ tone="danger"
+ busy={noteBusy}
+ onConfirm={() => void confirmDelete()}
+ onCancel={() => setPendingDeleteId(null)}
+ >
+ {t("This note will be removed from Video Learning.")}
+ </ConfirmDialog>
</section>
);
}
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index f8e05fc18..f1213903c 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -16,7 +16,8 @@ export type NotebookRecordType =
| "chat"
| "co_writer"
| "reading"
- | "tutorbot";
+ | "tutorbot"
+ | "video_learning";
export interface NotebookSummary {
id: string;
diff --git a/web/lib/video-learning-api.ts b/web/lib/video-learning-api.ts
index c148be8e8..84de0d5fd 100644
--- a/web/lib/video-learning-api.ts
+++ b/web/lib/video-learning-api.ts
@@ -57,6 +57,18 @@ export interface TimedMediaMaterial {
playback: VideoPlayback;
}
+export interface VideoNote {
+ notebook_id: string;
+ note_id: string;
+ material_id: string;
+ body: string;
+ time_seconds: number;
+ locator: number;
+ quote: string;
+ created_at: number;
+ updated_at: number;
+}
+
export interface VideoLearningSettings {
version: 1;
default_provider: VideoProvider;
@@ -67,13 +79,86 @@ export interface VideoLearningSettings {
async function unwrap<T>(response: Response): Promise<T> {
if (!response.ok) {
const payload = await response.json().catch(() => ({}));
+ const detail = (payload as { detail?: unknown })?.detail;
+ const message =
+ typeof detail === "string"
+ ? detail
+ : typeof (detail as { message?: unknown } | undefined)?.message ===
+ "string"
+ ? (detail as { message: string }).message
+ : null;
throw new Error(
- String(payload?.detail || `Request failed (${response.status})`),
+ message || `Request failed (${response.status})`,
);
}
return (await response.json()) as T;
}
+export async function listVideoNotes(
+ materialId: string,
+): Promise<VideoNote[]> {
+ return unwrap(
+ await apiFetch(
+ apiUrl(
+ `/api/v1/video-learning/materials/${encodeURIComponent(materialId)}/notes`,
+ ),
+ { cache: "no-store" },
+ ),
+ );
+}
+
+export async function createVideoNote(
+ materialId: string,
+ body: string,
+ timeSeconds: number,
+): Promise<VideoNote> {
+ return unwrap(
+ await apiFetch(
+ apiUrl(
+ `/api/v1/video-learning/materials/${encodeURIComponent(materialId)}/notes`,
+ ),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ body, time_seconds: timeSeconds }),
+ },
+ ),
+ );
+}
+
+export async function updateVideoNote(
+ materialId: string,
+ noteId: string,
+ body: string,
+): Promise<VideoNote> {
+ return unwrap(
+ await apiFetch(
+ apiUrl(
+ `/api/v1/video-learning/materials/${encodeURIComponent(materialId)}/notes/${encodeURIComponent(noteId)}`,
+ ),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ body }),
+ },
+ ),
+ );
+}
+
+export async function deleteVideoNote(
+ materialId: string,
+ noteId: string,
+): Promise<void> {
+ await unwrap(
+ await apiFetch(
+ apiUrl(
+ `/api/v1/video-learning/materials/${encodeURIComponent(materialId)}/notes/${encodeURIComponent(noteId)}`,
+ ),
+ { method: "DELETE" },
+ ),
+ );
+}
+
export async function resolveVideo(
url: string,
language = "",
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 125449c60..b21ee1037 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -4260,5 +4260,19 @@
"Explain this part of the video": "Explain this part of the video",
"YouTube Player API did not initialize.": "YouTube Player API did not initialize.",
"YouTube Player API timed out.": "YouTube Player API timed out.",
- "YouTube Player API could not be loaded.": "YouTube Player API could not be loaded."
+ "YouTube Player API could not be loaded.": "YouTube Player API could not be loaded.",
+ "Video notes": "Video notes",
+ "Add video note": "Add video note",
+ "Save video note": "Save video note",
+ "Note at {{time}}": "Note at {{time}}",
+ "Edit note at {{time}}": "Edit note at {{time}}",
+ "Delete note at {{time}}": "Delete note at {{time}}",
+ "Delete this note?": "Delete this note?",
+ "This note will be removed from Video Learning.": "This note will be removed from Video Learning.",
+ "No notes yet.": "No notes yet.",
+ "Loading notes.": "Loading notes.",
+ "Notes could not be loaded.": "Notes could not be loaded.",
+ "Note was not saved.": "Note was not saved.",
+ "Note was not deleted.": "Note was not deleted.",
+ "Video learning panels": "Video learning panels"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index d3171771f..e5e4dc3e4 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -4260,5 +4260,19 @@
"Explain this part of the video": "解释视频的这一部分",
"YouTube Player API did not initialize.": "YouTube Player API 未能初始化。",
"YouTube Player API timed out.": "YouTube Player API 加载超时。",
- "YouTube Player API could not be loaded.": "无法加载 YouTube Player API。"
+ "YouTube Player API could not be loaded.": "无法加载 YouTube Player API。",
+ "Video notes": "视频笔记",
+ "Add video note": "添加视频笔记",
+ "Save video note": "保存视频笔记",
+ "Note at {{time}}": "{{time}} 的笔记",
+ "Edit note at {{time}}": "编辑 {{time}} 的笔记",
+ "Delete note at {{time}}": "删除 {{time}} 的笔记",
+ "Delete this note?": "删除这条笔记?",
+ "This note will be removed from Video Learning.": "这条笔记将从视频学习中移除。",
+ "No notes yet.": "暂无笔记。",
+ "Loading notes.": "正在加载笔记。",
+ "Notes could not be loaded.": "无法加载笔记。",
+ "Note was not saved.": "笔记未保存。",
+ "Note was not deleted.": "笔记未删除。",
+ "Video learning panels": "视频学习面板"
}
diff --git a/web/tests/e2e/video-learning.audit.ts b/web/tests/e2e/video-learning.audit.ts
index 0f05ea1bf..b1051821e 100644
--- a/web/tests/e2e/video-learning.audit.ts
+++ b/web/tests/e2e/video-learning.audit.ts
@@ -9,6 +9,18 @@ test("YouTube learning survives reload and switches to Invidious without silent
let invidiousOffline = false;
let savedPosition = 0;
let nativeResolveCount = 0;
+ let nextNoteId = 1;
+ const notes: Array<{
+ notebook_id: string;
+ note_id: string;
+ material_id: string;
+ body: string;
+ time_seconds: number;
+ locator: number;
+ quote: string;
+ created_at: number;
+ updated_at: number;
+ }> = [];
const material = (selected: "youtube" | "invidious") => ({
version: 1,
@@ -141,6 +153,40 @@ test("YouTube learning survives reload and switches to Invidious without silent
savedPosition = body.time_seconds;
return json({ time_seconds: savedPosition, duration_seconds: 120 });
}
+ if (path.endsWith("/notes") && request.method() === "GET") {
+ return json(notes);
+ }
+ if (path.endsWith("/notes") && request.method() === "POST") {
+ const body = request.postDataJSON() as { body: string; time_seconds: number };
+ const note = {
+ notebook_id: "video-notes",
+ note_id: `note-${nextNoteId++}`,
+ material_id: MATERIAL_ID,
+ body: body.body,
+ time_seconds: body.time_seconds,
+ locator: 1,
+ quote: "The first grounded concept.",
+ created_at: Date.now() / 1000,
+ updated_at: Date.now() / 1000,
+ };
+ notes.push(note);
+ return json(note);
+ }
+ const noteMatch = /\/materials\/[^/]+\/notes\/([^/]+)$/.exec(path);
+ if (noteMatch) {
+ const noteId = noteMatch[1];
+ const index = notes.findIndex((note) => note.note_id === noteId);
+ if (index === -1) return json({ detail: "Note not found" }, 404);
+ if (request.method() === "PUT") {
+ const body = request.postDataJSON() as { body: string };
+ notes[index] = { ...notes[index], body: body.body, updated_at: Date.now() / 1000 };
+ return json(notes[index]);
+ }
+ if (request.method() === "DELETE") {
+ notes.splice(index, 1);
+ return json({ status: "deleted" });
+ }
+ }
if (path.endsWith("/subtitles.vtt")) {
return route.fulfill({
status: 200,
@@ -183,6 +229,58 @@ test("YouTube learning survives reload and switches to Invidious without silent
await expect(
page.getByText("The first grounded concept.").locator(".."),
).toHaveClass(/ring-1/);
+
+ await page.getByRole("tab", { name: "Video notes" }).click();
+ await expect(page.getByText("No notes yet.")).toBeVisible();
+ await page
+ .getByPlaceholder("Note at 0:08")
+ .fill("First timestamped note");
+ await page.getByRole("button", { name: "Add video note" }).click();
+ await expect(page.getByText("First timestamped note")).toBeVisible();
+ await expect(page.getByText("The first grounded concept.")).toBeVisible();
+
+ await page.reload();
+ await page.getByRole("button", { name: "Chat", exact: true }).click();
+ await page
+ .getByRole("button", { name: /Immersive Watching/ })
+ .last()
+ .click();
+ await expect(page.getByText("Timestamped lesson")).toBeVisible();
+ await page.getByRole("tab", { name: "Video notes" }).click();
+ await expect(page.getByText("First timestamped note")).toBeVisible();
+
+ await page.evaluate(() => {
+ const player = (
+ window as typeof window & { __fakePlayers: Array<{ current: number }> }
+ ).__fakePlayers.at(-1);
+ if (player) player.current = 70;
+ });
+ await page.getByRole("button", { name: "0:08", exact: true }).click();
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const player = (
+ window as typeof window & { __fakePlayers: Array<{ current: number }> }
+ ).__fakePlayers.at(-1);
+ return player?.current || 0;
+ }),
+ )
+ .toBe(8);
+
+ await page.getByRole("button", { name: "Edit note at 0:08" }).click();
+ await page
+ .getByLabel("Edit note at 0:08")
+ .locator("..")
+ .locator("textarea")
+ .fill("Updated timestamped note");
+ await page.getByRole("button", { name: "Save video note" }).click();
+ await expect(page.getByText("Updated timestamped note")).toBeVisible();
+
+ await page.getByRole("button", { name: "Delete note at 0:08" }).click();
+ await page.getByRole("button", { name: "Delete", exact: true }).click();
+ await expect(page.getByText("No notes yet.")).toBeVisible();
+ await page.getByRole("tab", { name: "Transcript" }).click();
+
await page.getByRole("button", { name: "Explain here" }).click();
await expect(page.locator("textarea")).toHaveValue(
/\[0:08\] The first grounded concept\./,