DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(watching): browse connected Invidious accounts (#1241)
evan188199-tech0f8759f730da
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex f8dc3f7c8..9b1760769 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -5,7 +5,7 @@ import sysfrom fastapi import Depends, FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddleware-from fastapi.responses import JSONResponse+from fastapi.responses import JSONResponse, RedirectResponsefrom deeptutor.logging import configure_loggingfrom deeptutor.services.config import (@@ -435,6 +435,17 @@ if not any(getattr(h, "_deeptutor_access_handler", False) for h in _access_logge@app.middleware("http")async def selective_access_log(request, call_next):response = await call_next(request)+ # An expired app login must not strand provider credentials in a callback URL.+ # Authentication still runs normally; only its failure presentation changes.+ if (+ request.url.path == "/api/video-learning/invidious/account/callback"+ and response.status_code in {401, 403}+ ):+ response = RedirectResponse(+ "/watching?account=authorization_login_required",+ status_code=303,+ headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"},+ )if response.status_code != 200:_access_logger.info('%s - "%s %s HTTP/%s" %d',diff --git a/deeptutor/api/routers/video_learning.py b/deeptutor/api/routers/video_learning.pyindex 93daf9dd9..37afa131a 100644--- a/deeptutor/api/routers/video_learning.py+++ b/deeptutor/api/routers/video_learning.py@@ -6,8 +6,8 @@ import refrom typing import Anyfrom urllib.parse import urljoin, urlparse-from fastapi import APIRouter, HTTPException, Request-from fastapi.responses import JSONResponse, Response, StreamingResponse+from fastapi import APIRouter, HTTPException, Query, Request+from fastapi.responses import JSONResponse, RedirectResponse, Response, StreamingResponseimport httpxfrom pydantic import BaseModel, Fieldfrom starlette.background import BackgroundTask@@ -126,16 +126,41 @@ async def authorize_invidious_account() -> dict[str, str]:@router.get("/invidious/account/callback")-async def invidious_account_callback(token: str = "", state: str = "") -> JSONResponse:+async def invidious_account_callback(token: str = "", state: str = "") -> RedirectResponse:+ result = "connected"try:- status = await invidious_account.complete_invidious_account_authorization(+ await invidious_account.complete_invidious_account_authorization(owner_id=current_owner_id(),state=state,token=token,)+ except Exception as exc:+ result = invidious_account.authorization_failure_code(exc, has_token=bool(token))+ return RedirectResponse(+ f"/watching?account={result}",+ status_code=303,+ headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"},+ )++[email protected]("/invidious/browse/{kind}")+async def browse_invidious(+ kind: str,+ q: str = Query(default="", max_length=500),+ page: int = Query(default=1, ge=1, le=1000),+ playlist_id: str = Query(default="", max_length=100),+) -> JSONResponse:+ try:+ payload = await invidious_account.browse_invidious(+ owner_id=current_owner_id(),+ kind=kind,+ query=q,+ page=page,+ playlist_id=playlist_id,+ )except Exception as exc:raise _http_error(exc) from exc- return JSONResponse(status, headers={"Cache-Control": "no-store"})+ return JSONResponse(payload, headers={"Cache-Control": "no-store"})@router.get("/invidious/account/status")diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.pyindex 2cfc3a26c..8d99bb16c 100644--- a/deeptutor/services/session/turns/request_preparer.py+++ b/deeptutor/services/session/turns/request_preparer.py@@ -14,6 +14,7 @@ from deeptutor.runtime.capability_routing import route_explicit_quiz_requestfrom deeptutor.services.session.workspace_preferences import (WORKSPACE_MODE_MASTERY,WORKSPACE_MODE_READING,+ WORKSPACE_MODE_WATCHING,)from .._turn_runtime_shared import (@@ -169,6 +170,16 @@ class TurnRequestPreparer:except PermissionError as exc:raise RuntimeError(str(exc)) from exc+ if workspace_mode == WORKSPACE_MODE_WATCHING:+ from deeptutor.video_learning import get_timed_media_store++ media_id = _timed_media_id(payload.get("timed_media_id"))+ if media_id:+ # Resolve only in the authenticated owner's store before saving the binding.+ get_timed_media_store().get(media_id)+ else:+ payload.pop("timed_media_id", None)+ payload.pop("timed_media_viewport", None)try:from deeptutor.runtime.request_contracts import validate_capability_config@@ -426,6 +437,8 @@ class TurnRequestPreparer:# non-empty legacy capability is persisted as part of migration.if workspace_mode_explicit or workspace_mode:preference_update["workspace_mode"] = workspace_mode+ if workspace_mode == "immersive_watching":+ preference_update["timed_media_id"] = _timed_media_id(payload.get("timed_media_id"))if course_id_explicit:preference_update["course_id"] = requested_course_iddiff --git a/deeptutor/services/session/workspace_preferences.py b/deeptutor/services/session/workspace_preferences.pyindex a847b72d8..a99b2bcd2 100644--- a/deeptutor/services/session/workspace_preferences.py+++ b/deeptutor/services/session/workspace_preferences.py@@ -11,7 +11,10 @@ from typing import AnyWORKSPACE_MODE_READING = "immersive_reading"WORKSPACE_MODE_MASTERY = "mastery_path"-WORKSPACE_MODES = frozenset({WORKSPACE_MODE_READING, WORKSPACE_MODE_MASTERY})+WORKSPACE_MODE_WATCHING = "immersive_watching"+WORKSPACE_MODES = frozenset(+ {WORKSPACE_MODE_READING, WORKSPACE_MODE_MASTERY, WORKSPACE_MODE_WATCHING}+)def upgrade_workspace_preferences(value: Any) -> dict[str, Any]:@@ -33,7 +36,9 @@ def upgrade_workspace_preferences(value: Any) -> dict[str, Any]:reading_workspace_id = str(preferences.get("reading_workspace_id") or "").strip()session_kind = str(preferences.get("session_kind") or "").strip()- if capability == WORKSPACE_MODE_MASTERY and mastery_path_id:+ if capability == WORKSPACE_MODE_WATCHING:+ preferences["workspace_mode"] = WORKSPACE_MODE_WATCHING+ elif capability == WORKSPACE_MODE_MASTERY and mastery_path_id:preferences["workspace_mode"] = WORKSPACE_MODE_MASTERYelif reading_workspace_id and (capability == WORKSPACE_MODE_READING or session_kind == WORKSPACE_MODE_READINGdiff --git a/deeptutor/video_learning/invidious_account.py b/deeptutor/video_learning/invidious_account.pyindex 9b99b218d..18a08642f 100644--- a/deeptutor/video_learning/invidious_account.py+++ b/deeptutor/video_learning/invidious_account.py@@ -14,7 +14,7 @@ import osimport secretsimport timefrom typing import Any-from urllib.parse import urlencode, urlparse+from urllib.parse import unquote_plus, urlencode, urlparseimport deeptutor.video_learning.invidious_account_client as _clientimport deeptutor.video_learning.invidious_account_storage as _storage@@ -28,7 +28,13 @@ CALLBACK_PATH = "/api/video-learning/invidious/account/callback"FLOW_TIMEOUT_S = 600.0PUBLIC_URL_ENV = "DEEPTUTOR_PUBLIC_URL"DEFAULT_PUBLIC_URL = "http://localhost:3782"-ACCOUNT_SCOPES = ("GET:preferences", "POST:tokens/unregister")+ACCOUNT_SCOPES = (+ "GET:preferences",+ "POST:tokens/unregister",+ "GET:feed",+ "GET:playlists",+ "GET:playlists/*",+)_MAX_TOKEN_BYTES = 8192# Explicit call seams let the workflow tests substitute transport behavior@@ -85,7 +91,8 @@ def begin_invidious_account_authorization(*, owner_id: str, redirect_uri: str) -state = secrets.token_urlsafe(32)separator = "&" if parsed_redirect.query else "?"callback_url = f"{redirect_uri}{separator}{urlencode({'state': state})}"- authorize_url = f"{base}/authorize_token?{urlencode({'scopes': ','.join(ACCOUNT_SCOPES), 'callback_url': callback_url})}"+ public_base = settings["invidious"].get("public_base_url") or base+ authorize_url = f"{public_base}/authorize_token?{urlencode({'scopes': ','.join(ACCOUNT_SCOPES), 'callback_url': callback_url})}"_storage.replace_pending_flow(state=state,@@ -103,7 +110,16 @@ def _parse_token(raw_token: str) -> dict[str, Any]:if not raw_token or len(raw_token.encode("utf-8")) > _MAX_TOKEN_BYTES:raise TimedMediaError("Invidious returned an invalid account token.")try:- token = json.loads(raw_token)+ # Invidious form-encodes the JSON, then encodes it again when adding+ # it to the callback query. FastAPI has already removed the outer layer.+ # Preserve literal JSON unchanged (including + and % in signed values),+ # and decode at most one additional layer for the native callback format.+ decoded = (+ raw_token+ if raw_token.lstrip().startswith("{")+ else unquote_plus(raw_token, errors="strict")+ )+ token = json.loads(decoded)except (json.JSONDecodeError, UnicodeError) as exc:raise TimedMediaError("Invidious returned an invalid account token.") from excif not isinstance(token, dict):@@ -183,7 +199,9 @@ def invidious_account_status(owner_id: str) -> dict[str, Any]:if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:return {"connected": False}if not _scopes_include_required(scopes):- return {"connected": False}+ return {"connected": False, "needs_reauthorization": True}+ if base != load_video_learning_settings()["invidious"]["api_base_url"]:+ return {"connected": False, "needs_reauthorization": True}if not isinstance(connected_at, str) or not connected_at:return {"connected": False}return {@@ -227,3 +245,116 @@ __all__ = ["invidious_account_status","invidious_redirect_uri",]+++async def browse_invidious(+ *, owner_id: str, kind: str, query: str = "", page: int = 1, playlist_id: str = ""+) -> Any:+ """Read only the configured provider; credentials never leave this boundary."""+ from urllib.parse import quote++ settings = load_video_learning_settings()+ base = settings["invidious"]["api_base_url"]+ if not base:+ raise TimedMediaError("Invidious is not configured.")+ token = None+ if kind == "search":+ path = "/api/v1/search"+ params = {"q": query, "page": page, "type": "video"}+ else:+ if not invidious_account_status(owner_id).get("connected"):+ raise TimedMediaError("Reconnect your Invidious account to browse your videos.")+ token = _storage.read_account(owner_id).get("token")+ if kind == "feed":+ path, params = "/api/v1/auth/feed", {"page": page, "max_results": 24}+ elif kind == "playlists":+ path, params = "/api/v1/auth/playlists", {}+ elif kind == "playlist":+ if (+ not playlist_id+ or len(playlist_id) > 100+ or not all(c.isalnum() or c in "_-" for c in playlist_id)+ ):+ raise TimedMediaError("Invalid playlist identifier.")+ path, params = "/api/v1/auth/playlists/" + quote(playlist_id, safe=""), {"page": page}+ else:+ raise TimedMediaError("Unknown video browser view.")+ data = await _client.request_catalog(api_base_url=base, path=path, params=params, token=token)+ return _catalog_payload(+ data, kind=kind, public_base=settings["invidious"].get("public_base_url") or base+ )+++def _catalog_payload(data: Any, *, kind: str, public_base: str) -> Any:+ """Expose only card metadata, with thumbnails on a trusted provider origin."""+ import re+ from urllib.parse import urljoin, urlsplit++ def video(raw: Any) -> dict[str, Any] | None:+ if not isinstance(raw, dict) or not re.fullmatch(+ r"[A-Za-z0-9_-]{11}", str(raw.get("videoId", ""))+ ):+ return None+ vid = raw["videoId"]+ thumbnail = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"+ for entry in raw.get("videoThumbnails", []) or []:+ if not isinstance(entry, dict):+ continue+ candidate = urljoin(public_base + "/", str(entry.get("url", "")))+ parsed = urlsplit(candidate)+ if (+ parsed.scheme in {"http", "https"}+ and not parsed.username+ and not parsed.password+ and parsed.netloc == urlsplit(public_base).netloc+ ):+ thumbnail = candidate+ break+ duration = raw.get("lengthSeconds", 0)+ return {+ "videoId": vid,+ "title": str(raw.get("title", "")),+ "author": str(raw.get("author", "")),+ "lengthSeconds": max(0, duration) if isinstance(duration, int) else 0,+ "videoThumbnails": [{"url": thumbnail}],+ }++ if kind == "playlists":+ return (+ [+ {+ "playlistId": item["playlistId"],+ "title": str(item.get("title", "")),+ "videoCount": item.get("videoCount", 0),+ "videos": [v for raw in item.get("videos", []) if (v := video(raw))],+ }+ for item in data+ if isinstance(item, dict)+ and re.fullmatch(r"[A-Za-z0-9_-]{1,100}", str(item.get("playlistId", "")))+ ]+ if isinstance(data, list)+ else []+ )+ rows = data if isinstance(data, list) else data.get("videos", [])+ return {"videos": [v for raw in rows if (v := video(raw))]}+++def authorization_failure_code(error: Exception, *, has_token: bool) -> str:+ """Stable non-sensitive callback outcomes; never put provider errors in URLs."""+ if not has_token:+ return "authorization_cancelled"+ message = str(error) if isinstance(error, TimedMediaError) else ""+ if message == "Invidious account callback is unknown, expired, or already used.":+ return "authorization_expired"+ if message == "Invidious account token is missing a required scope.":+ return "authorization_scopes"+ if message.startswith("Invidious returned an"):+ return "authorization_token_invalid"+ if message in {+ "Invidious account verification failed with HTTP 401.",+ "Invidious account verification failed with HTTP 403.",+ }:+ return "authorization_token_rejected"+ if message.startswith("Invidious account verification"):+ return "authorization_unavailable"+ return "authorization_failed"diff --git a/deeptutor/video_learning/invidious_account_client.py b/deeptutor/video_learning/invidious_account_client.pyindex 6fc25de07..e99ed9522 100644--- a/deeptutor/video_learning/invidious_account_client.py+++ b/deeptutor/video_learning/invidious_account_client.py@@ -62,3 +62,24 @@ __all__ = ["request_preferences","revoke_token",]+++async def request_catalog(*, api_base_url: str, path: str, params: dict, token: dict | None) -> Any:+ headers = {"Authorization": f"Bearer {bearer_token(token)}"} if token else {}+ try:+ async with httpx.AsyncClient(timeout=20.0, follow_redirects=False) as client:+ response = await client.get(f"{api_base_url}{path}", params=params, headers=headers)+ if response.status_code in (401, 403):+ raise TimedMediaError("Reconnect your Invidious account to browse your videos.")+ if response.status_code != 200:+ raise TimedMediaError(+ "Invidious could not load videos. Please retry or check the instance."+ )+ data = response.json()+ if not isinstance(data, (dict, list)):+ raise ValueError("Invalid catalog")+ return data+ except (httpx.HTTPError, ValueError) as exc:+ raise TimedMediaError(+ "Invidious could not load videos. Please retry or check the instance."+ ) from excdiff --git a/deeptutor/video_learning/service.py b/deeptutor/video_learning/service.pyindex e3b73fdb1..ed7b3ea21 100644--- a/deeptutor/video_learning/service.py+++ b/deeptutor/video_learning/service.py@@ -134,7 +134,14 @@ def _is_local_host(host: str) -> bool:address = ipaddress.ip_address(host)except ValueError:return False- return address.is_loopback or address.is_private or address.is_link_local+ # RFC 6598 shared address space is used by private overlays such as Tailscale.+ # ipaddress intentionally classifies it as neither private nor global.+ return (+ address.is_loopback+ or address.is_private+ or address.is_link_local+ or address in ipaddress.ip_network("100.64.0.0/10")+ )def normalize_video_learning_settings(payload: Any) -> dict[str, Any]:diff --git a/docs/guides/watching-workspace.md b/docs/guides/watching-workspace.mdnew file mode 100644index 000000000..09eaa2bb5--- /dev/null+++ b/docs/guides/watching-workspace.md@@ -0,0 +1,66 @@+# Immersive Watching workspace++Open **Immersive Watching** in the sidebar, or visit `/watching`. Paste a YouTube URL and open the video. The first question creates a conversation at `/watching/{sessionId}`. Desktop shows video beside the conversation; smaller screens have Video and Conversation buttons that preserve the mounted player.++The workspace reuses the chat runtime and the existing timed-media APIs. Session preferences store `workspace_mode: "immersive_watching"` and `timed_media_id`; material access is checked against the current user's store. Existing Watching conversations recover their material from their latest recorded turn when the preference is absent. Browser-global recent-video storage is no longer a source of session identity. A new draft starts empty; send a question to save it as a conversation.++## Configure Invidious++In administrator settings, open the video-learning section, enter the existing instance's backend API origin and public origin, test the connection, and select Invidious as the default provider. Settings are persisted by the application's administrator path service as `video_learning.json`; do not put them in the project `.env` or hard-code them in frontend code.++- `invidious.api_base_url`: an origin reachable by the DeepTutor backend. Loopback is suitable only when the backend and instance share a host network. Containers must use an appropriate service or host address.+- `invidious.public_base_url`: the same instance's origin reachable by the user's browser/device.+Private HTTP origins include loopback, LAN and RFC 6598 shared addresses used by overlays such as Tailscale. Public instances must use HTTPS.++- `default_provider`: `invidious` or `youtube`.++DeepTutor continues to proxy media through its authenticated video-learning endpoints. Do not replace the player with an Invidious iframe or relax the stream proxy's allowed-origin checks. Invidious failure remains visible; switching to native YouTube requires the user's explicit action.++## Verify and troubleshoot++1. Open a captioned video and check actual playback and seeking, not just the instance status endpoint. Media requests should support byte ranges (`206` where applicable).+2. Click a caption, use Explain here, follow an answer's timestamp, and save/reopen a timestamped note.+3. Refresh the conversation URL, visit another conversation, and return. Confirm both the material and saved progress; ordinary Chat and Reading must retain their own context.+4. Repeat with a narrow viewport, missing captions, an unavailable instance, and a user who cannot access the material.++If metadata works but playback fails, inspect the authenticated stream response and the configured instance's media/companion service. If captions are unavailable, use Retry captions; do not silently substitute a different provider. A missing or unauthorized saved video leaves an error and an empty video surface rather than another conversation's video.++## Deployment and rollback++Before deployment, record the running commit, save the tracked working-tree diff, and back up the video settings and service launch configuration. Build a separate release directory containing the existing deployment changes plus the reviewed Watching patch. Keep the existing data directory and owner identity; do not copy user data into Git.++Run frontend type, contract, lint, translation and build checks, the Watching browser tests, and `pytest tests/video_learning`. Switch service paths only after the release is ready. Check `/watching`, `/reading`, `/chat` and real Invidious playback. On failure, restore the previous service paths and video settings, restart the old release, and verify readiness. Leave the previous working tree and its uncommitted changes intact.++## Connected Invidious browsing++Watching can search videos without an Invidious account. Connect an account from+Watching to read its subscription feed and playlists, including private playlists.+Video selection uses the existing timed-media resolver and opens a fresh Watching+conversation; older conversations retain their original material.++The account workflow reuses the owner-private account store and transport adapter.+The additional scopes are `GET:feed`, `GET:playlists`, and `GET:playlists/*`.+Older tokens require reconnection; subscription and playlist mutations are not requested.+DeepTutor never asks for the Invidious password. Sign in and consent on the configured+Invidious site. Revocation failures retain the saved token so disconnect can be retried.++Set the administrator's `api_base_url` to an address reachable by the backend and+`public_base_url` to the same instance's browser-reachable origin. Set+`DEEPTUTOR_PUBLIC_URL` in the backend service environment to DeepTutor's canonical+external origin. Restart the backend after changing that environment variable.+Authorization uses the public instance origin; API requests use the internal origin.+The callback returns to Watching with a non-sensitive outcome and no token in the+redirect target. An expired application login must be renewed before reconnecting.++For diagnosis, verify search first, then authorize, inspect subscription feed and+playlist contents, select a video, and verify actual playback and seeking. An empty+feed can mean that the account has no subscriptions. Expired/revoked tokens require+reconnection; an unavailable instance offers retry. Provider failure never selects+YouTube playback automatically.++Before deploying, back up service definitions, video settings, and owner-private+account files with their original restrictive permissions. Build in an isolated+release directory and verify Reading and ordinary chat as well as Watching. Roll+back service paths, environment, and settings to the previous release if acceptance+fails; do not overwrite user data created after deployment. Preserve newly issued+tokens until they can be explicitly revoked on the instance.diff --git a/tests/video_learning/test_invidious_account.py b/tests/video_learning/test_invidious_account.pyindex 36f56f3ca..7e43aa7fd 100644--- a/tests/video_learning/test_invidious_account.py+++ b/tests/video_learning/test_invidious_account.py@@ -531,8 +531,10 @@ def test_router_authorize_callback_status_and_disconnect(callback = client.get("/api/video-learning/invidious/account/callback",params={"state": state, "token": _token()},+ follow_redirects=False,)- assert callback.status_code == 200+ assert callback.status_code == 303+ assert callback.headers["location"] == "/watching?account=connected"assert callback.headers["cache-control"] == "no-store"assert "v1:test-session" not in callback.text@@ -566,14 +568,16 @@ def test_router_authorize_callback_status_and_disconnect(assert disconnected == {"owner_id": "u_ada"}-def test_unknown_callback_returns_400_without_calling_invidious(+def test_unknown_callback_redirects_without_calling_invidious(client: TestClient,) -> None:response = client.get("/api/video-learning/invidious/account/callback",params={"state": "forged", "token": _token()},+ follow_redirects=False,)- assert response.status_code == 400+ assert response.status_code == 303+ assert response.headers["location"] == "/watching?account=authorization_expired"assert "forged" not in response.textassert "v1:test-session" not in response.text@@ -597,3 +601,211 @@ def test_router_start_returns_400_when_invidious_is_not_configured(assert response.json()["detail"] == ("Configure the Invidious API base URL before connecting an account.")+++def test_authorization_uses_public_origin_and_preserves_private_transport(system_root, monkeypatch):+ monkeypatch.setattr(+ account,+ "load_video_learning_settings",+ lambda: {+ "invidious": {+ "api_base_url": "http://127.0.0.1:3000",+ "public_base_url": "http://100.101.207.44:3000",+ }+ },+ )+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="http://100.101.207.44:3782/callback"+ )+ assert url.startswith("http://100.101.207.44:3000/authorize_token?")+ flow = account_storage.consume_pending_flow("u_ada", _state_from_authorize_url(url))+ assert flow.api_base_url == "http://127.0.0.1:3000"+++async def test_catalog_is_owner_scoped_and_search_is_anonymous(+ system_root, configured_instance, monkeypatch+):+ calls = []++ async def catalog(**kwargs):+ calls.append(kwargs)+ return [+ {+ "videoId": "aircAruvnKk",+ "title": "Neural networks",+ "videoThumbnails": [{"url": "https://untrusted.test/tracking"}],+ }+ ]++ monkeypatch.setattr(account_client, "request_catalog", catalog)+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "now",+ "token": json.loads(_token()),+ },+ )+ await account.browse_invidious(owner_id="u_ada", kind="feed")+ assert calls[-1]["token"]["session"] == "v1:test-session"+ with pytest.raises(TimedMediaError, match="Reconnect"):+ await account.browse_invidious(owner_id="u_other", kind="feed")+ result = await account.browse_invidious(owner_id="u_ada", kind="search", query="neural")+ assert calls[-1]["token"] is None+ assert result["videos"][0]["videoThumbnails"][0]["url"].startswith("https://i.ytimg.com/")+ assert "token" not in result+ with pytest.raises(TimedMediaError, match="Invalid playlist"):+ await account.browse_invidious(+ owner_id="u_ada", kind="playlist", playlist_id="../preferences"+ )+++def test_old_account_requires_read_permission_upgrade(system_root, configured_instance):+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": ["GET:preferences", "POST:tokens/unregister"],+ "connected_at": "now",+ "token": json.loads(_token()),+ },+ )+ assert account.invidious_account_status("u_ada") == {+ "connected": False,+ "needs_reauthorization": True,+ }+++def test_catalog_rejects_invalid_pagination(client):+ assert client.get("/api/video-learning/invidious/browse/search?page=0").status_code == 422+++async def test_catalog_transport_maps_offline_and_revoked_tokens(monkeypatch):+ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ pass++ async def get(self, *args, **kwargs):+ return httpx.Response(401)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", lambda **kwargs: FakeClient())+ with pytest.raises(TimedMediaError, match="Reconnect"):+ await account_client.request_catalog(+ api_base_url="https://invidious.test",+ path="/api/v1/auth/feed",+ params={},+ token=json.loads(_token()),+ )+++async def test_unauthenticated_callback_clears_credentials_from_destination():+ from starlette.requests import Request+ from starlette.responses import Response++ from deeptutor.api.main import selective_access_log++ request = Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/api/video-learning/invidious/account/callback",+ "query_string": b"token=secret&state=secret",+ "headers": [],+ "scheme": "http",+ "server": ("localhost", 8001),+ }+ )++ async def denied(_request):+ return Response(status_code=401)++ response = await selective_access_log(request, denied)+ assert response.status_code == 303+ assert response.headers["location"] == "/watching?account=authorization_login_required"+ assert "secret" not in str(dict(response.headers))++[email protected]("encoded", [False, True])+def test_real_invidious_callback_encoding(+ client, system_root, configured_instance, monkeypatch, encoded+):+ from urllib.parse import quote_plus++ # Native Invidious encodes JSON before HTTP::Params encodes the query again.+ raw = json.loads(_token())+ raw["session"] = "v1:literal+percent%2B"+ serialized = json.dumps(raw)++ async def preferences(*, api_base_url, token):+ assert token == raw+ return {}++ monkeypatch.setattr(account, "_request_preferences", preferences)+ started = client.post("/api/video-learning/invidious/account/authorize").json()+ state = _state_from_authorize_url(started["authorize_url"])+ callback = client.get(+ "/api/video-learning/invidious/account/callback",+ params={+ "state": state,+ "token": quote_plus(serialized) if encoded else serialized,+ },+ follow_redirects=False,+ )+ assert callback.status_code == 303+ assert callback.headers["location"] == "/watching?account=connected"+ assert account_storage.read_account("u_ada")["token"] == raw+ assert client.get("/api/video-learning/invidious/account/status").json()["connected"]+ repeated = client.get(+ "/api/video-learning/invidious/account/callback",+ params={"state": state, "token": serialized},+ follow_redirects=False,+ )+ assert repeated.headers["location"] == "/watching?account=authorization_expired"+++def test_token_decoding_is_bounded_and_does_not_decode_literal_json():+ from urllib.parse import quote_plus++ raw = _token()+ with pytest.raises(TimedMediaError, match="invalid account token"):+ account._parse_token(quote_plus(quote_plus(raw)))+++ ("error", "has_token", "code"),+ [+ (+ TimedMediaError("Invidious account callback is unknown, expired, or already used."),+ True,+ "authorization_expired",+ ),+ (+ TimedMediaError("Invidious account token is missing a required scope."),+ True,+ "authorization_scopes",+ ),+ (+ TimedMediaError("Invidious account verification failed with HTTP 403."),+ True,+ "authorization_token_rejected",+ ),+ (+ TimedMediaError("Invidious account verification request failed."),+ True,+ "authorization_unavailable",+ ),+ (RuntimeError("secret token should not be shown"), True, "authorization_failed"),+ (RuntimeError("anything"), False, "authorization_cancelled"),+ ],+)+def test_callback_failures_have_safe_actionable_codes(error, has_token, code):+ assert account.authorization_failure_code(error, has_token=has_token) == codediff --git a/tests/video_learning/test_turn_wiring.py b/tests/video_learning/test_turn_wiring.pyindex 2835d36eb..37d20df08 100644--- a/tests/video_learning/test_turn_wiring.py+++ b/tests/video_learning/test_turn_wiring.py@@ -31,3 +31,97 @@ def test_timed_media_id_is_saved_for_regenerate() -> None:snapshot = metadata["request_snapshot"]assert snapshot["timedMediaId"] == "0123456789abcdef"assert "timedMediaViewport" not in snapshot+++def test_watching_workspace_migrates_legacy_preferences() -> None:+ from deeptutor.services.session._turn_runtime_shared import _workspace_mode+ from deeptutor.services.session.workspace_preferences import upgrade_workspace_preferences++ assert upgrade_workspace_preferences({"capability": "immersive_watching"}) == {+ "capability": "immersive_watching",+ "workspace_mode": "immersive_watching",+ }+ assert _workspace_mode("immersive_watching") == "immersive_watching"+ assert upgrade_workspace_preferences({"capability": "chat", "timed_media_id": "stale"}) == {+ "capability": "chat",+ "timed_media_id": "stale",+ }+++import pytest+++async def test_watching_turn_persists_owner_validated_binding(tmp_path, monkeypatch) -> None:+ from types import SimpleNamespace++ from deeptutor.services.session.sqlite_store import SQLiteSessionStore+ from deeptutor.services.session.turn_runtime import TurnRuntimeManager++ store = SQLiteSessionStore(tmp_path / "sessions.db")+ runtime = TurnRuntimeManager(store)+ seen = []+ monkeypatch.setattr(+ "deeptutor.video_learning.get_timed_media_store",+ lambda: SimpleNamespace(get=lambda value: seen.append(value)),+ )++ async def no_execution(execution):+ pass++ monkeypatch.setattr(runtime, "_run_turn", no_execution)+ session, turn = await runtime.start_turn(+ {+ "content": "Explain here",+ "capability": "immersive_watching",+ "workspace_mode": "immersive_watching",+ "timed_media_id": "0123456789abcdef",+ "language": "en",+ }+ )+ await runtime._executions[turn["id"]].task+ loaded = await store.get_session(session["id"])+ assert loaded["preferences"]["workspace_mode"] == "immersive_watching"+ assert loaded["preferences"]["timed_media_id"] == "0123456789abcdef"+ assert seen == ["0123456789abcdef"]+++async def test_watching_turn_rejects_another_owners_material(tmp_path, monkeypatch) -> None:+ from deeptutor.services.session.sqlite_store import SQLiteSessionStore+ from deeptutor.services.session.turn_runtime import TurnRuntimeManager+ from deeptutor.video_learning import TimedMediaNotFound++ class PrivateStore:+ def get(self, material_id):+ raise TimedMediaNotFound("Video not found")++ monkeypatch.setattr("deeptutor.video_learning.get_timed_media_store", PrivateStore)+ runtime = TurnRuntimeManager(SQLiteSessionStore(tmp_path / "sessions.db"))+ with pytest.raises(TimedMediaNotFound):+ await runtime.start_turn(+ {+ "content": "Explain here",+ "capability": "immersive_watching",+ "timed_media_id": "0123456789abcdef",+ "language": "en",+ }+ )++[email protected]("origin", ["http://100.64.0.1:3000", "http://100.127.255.254:3000"])+def test_private_overlay_invidious_origins(origin):+ from deeptutor.video_learning.service import _validate_origin++ assert _validate_origin(origin) == origin+++ "origin", ["http://100.63.255.255:3000", "http://100.128.0.1:3000", "http://8.8.8.8:3000"]+)+def test_public_invidious_origins_still_require_https(origin):+ from deeptutor.video_learning import TimedMediaError+ from deeptutor.video_learning.service import _validate_origin++ with pytest.raises(TimedMediaError, match="HTTPS"):+ _validate_origin(origin)diff --git a/web/app/(workspace)/watching/[sessionId]/page.tsx b/web/app/(workspace)/watching/[sessionId]/page.tsxnew file mode 100644index 000000000..c383887d8--- /dev/null+++ b/web/app/(workspace)/watching/[sessionId]/page.tsx@@ -0,0 +1,5 @@+import ChatWorkspace from "@/features/chat/components/ChatWorkspace";++export default function WatchingPage() {+ return <ChatWorkspace watching />;+}diff --git a/web/app/(workspace)/watching/page.tsx b/web/app/(workspace)/watching/page.tsxnew file mode 100644index 000000000..c383887d8--- /dev/null+++ b/web/app/(workspace)/watching/page.tsx@@ -0,0 +1,5 @@+import ChatWorkspace from "@/features/chat/components/ChatWorkspace";++export default function WatchingPage() {+ return <ChatWorkspace watching />;+}diff --git a/web/app/globals.css b/web/app/globals.cssindex 4716c9d1a..7ad6b3c00 100644--- a/web/app/globals.css+++ b/web/app/globals.css@@ -843,9 +843,7 @@ body[data-picker-open] .dt-breathing-text {}/* ----- Immersive watching ------------------------------------------------ The video-learning panel remains part of Home while reading owns its- dedicated workspace. Keeping a watching-specific shell prevents the two- navigation models from becoming coupled again. */+ Watching shares the conversation renderer and owns its responsive video surface. */.dt-watching-shell {position: absolute;inset: 0 auto 0 0;@@ -1108,3 +1106,137 @@ a[href^="#dt-locator-"]:hover {animation: none !important;}}++/* Watching switches panes on small screens without unmounting playback or chat. */+.watching-mobile-tabs {+ display: none;+}+@media (max-width: 1023px) {+ .watching-mobile-tabs {+ display: flex;+ height: 44px;+ gap: 8px;+ padding: 4px 12px;+ position: absolute;+ inset: 0 0 auto;+ z-index: 40;+ background: var(--background);+ border-bottom: 1px solid var(--border);+ }+ .watching-mobile-tabs button {+ flex: 1;+ border-radius: 8px;+ }+ .watching-mobile-tabs button[aria-pressed="true"] {+ background: var(--muted);+ font-weight: 600;+ }+ .watching-surface .dt-watching-shell {+ top: 44px;+ }+ .watching-surface[data-mobile-view="chat"] .dt-watching-shell {+ visibility: hidden;+ pointer-events: none;+ }+ [data-watching-workspace="true"] > .chat-preview-shell {+ padding-top: 44px;+ }+ .watching-surface[data-mobile-view="video"] ~ .chat-preview-shell {+ visibility: hidden;+ pointer-events: none;+ }+}++/* Native provider browsing stays above the mounted learning workspace. */+.watching-browser {+ position: absolute;+ inset: 0;+ z-index: 45;+ display: flex;+ flex-direction: column;+ background: var(--background);+}+.watching-browser-button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 9px 12px;+ border: 1px solid var(--border);+ border-radius: 10px;+ font-size: 13px;+}+.watching-browser-button:hover,+.watching-browser-button[aria-pressed='true'] {+ background: var(--muted);+}+.watching-browser-button:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}+.watching-video-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));+ gap: 24px 20px;+}+.watching-video-card {+ text-align: left;+ min-width: 0;+ border-radius: 12px;+}+.watching-video-card:hover h2 {+ text-decoration: underline;+}+.watching-browser-empty {+ min-height: 220px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 16px;+ color: var(--muted-foreground);+ text-align: center;+}+.watching-browse-toggle {+ position: absolute;+ right: 12px;+ top: 8px;+ z-index: 44;+ background: var(--background);+}+.watching-account-error {+ position: absolute;+ bottom: 12px;+ left: 12px;+ right: 12px;+ z-index: 46;+ padding: 16px;+ border: 1px solid var(--border);+ border-radius: 12px;+ background: var(--background);+}+.watching-surface[data-browsing] ~ .chat-preview-shell {+ visibility: hidden;+ pointer-events: none;+}+@media (max-width: 1023px) {+ .watching-browse-toggle {+ top: 48px;+ }+}+@media (max-width: 520px) {+ .watching-video-grid {+ grid-template-columns: 1fr;+ }+}+.watching-surface .dt-watching-shell { top: 48px; }+[data-watching-workspace="true"] > .chat-preview-shell { padding-top: 48px; }+@media (max-width: 1023px) {+ .watching-surface .dt-watching-shell { top: 92px; }+ [data-watching-workspace="true"] > .chat-preview-shell { padding-top: 92px; }+}+.watching-surface[data-browsing] .dt-watching-shell,+.watching-surface[data-browsing] .watching-mobile-tabs {+ visibility: hidden;+ pointer-events: none;+}diff --git a/web/components/sidebar/nav-entries.ts b/web/components/sidebar/nav-entries.tsindex b4668174b..7159dcbd5 100644--- a/web/components/sidebar/nav-entries.ts+++ b/web/components/sidebar/nav-entries.ts@@ -1,4 +1,5 @@import {+ Clapperboard,BookOpen,BookText,Bot,@@ -88,6 +89,13 @@ export const PRIMARY_NAV: NavEntry[] = [tooltipKey: "Immersive Reading tooltip",requires: "llm",},+ {+ href: "/watching",+ label: "Immersive Watching",+ icon: Clapperboard,+ tooltipKey: "Watch videos with a grounded AI companion.",+ requires: "llm",+ },{href: "/space",label: "Learning Space",diff --git a/web/components/watching/WatchingBrowser.tsx b/web/components/watching/WatchingBrowser.tsxnew file mode 100644index 000000000..dc22efa47--- /dev/null+++ b/web/components/watching/WatchingBrowser.tsx@@ -0,0 +1,431 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";+import {+ Search,+ Link2,+ Play,+ ListVideo,+ Rss,+ Loader2,+ ArrowLeft,+} from "lucide-react";+import { browserStorage } from "@/shared/storage";+import { useAuthStatus } from "@/hooks/useAuthStatus";+import {+ browseInvidious,+ invidiousAccount,+ type InvidiousAccountStatus,+ type InvidiousVideo,+ type InvidiousPlaylist,+} from "@/lib/video-learning-api";++/* eslint-disable @next/next/no-img-element -- Invidious thumbnails come from arbitrary user instances. */++type BrowserView = "feed" | "playlists" | "search" | "playlist";+export function WatchingBrowser({+ onDismiss,+ canDismiss,+}: {+ onDismiss(): void;+ canDismiss: boolean;+}) {+ const { t } = useTranslation();+ const router = useRouter();+ const auth = useAuthStatus();+ const [account, setAccount] = useState<InvidiousAccountStatus | null>(null);+ const [view, setView] = useState<BrowserView>("search");+ const [input, setInput] = useState("");+ const [query, setQuery] = useState("");+ const [playlist, setPlaylist] = useState("");+ const [page, setPage] = useState(1);+ const [items, setItems] = useState<(InvidiousVideo | InvidiousPlaylist)[]>(+ [],+ );+ const [busy, setBusy] = useState(false);+ const [accountBusy, setAccountBusy] = useState(false);+ const [error, setError] = useState("");+ const [reload, setReload] = useState(0);+ const scroll = useRef<HTMLDivElement>(null);+ const restored = useRef(false);+ const key = `watching-browser:${auth.userId ?? "local"}`;++ useEffect(() => {+ if (auth.loading || !auth.statusAvailable) return;+ let alive = true;+ setItems([]);+ setAccount(null);+ void invidiousAccount("status")+ .then((status) => {+ if (!alive) return;+ setAccount(status);+ let saved: {+ view?: BrowserView;+ query?: string;+ page?: number;+ playlist?: string;+ scroll?: number;+ } = {};+ try {+ saved = JSON.parse(browserStorage.readRaw("session", key) || "{}");+ } catch {+ /* Storage is optional. */+ }+ if (!restored.current) {+ restored.current = true;+ setView(saved.view || (status.connected ? "feed" : "search"));+ setQuery(saved.query || "");+ setInput(saved.query || "");+ setPage(saved.page || 1);+ setPlaylist(saved.playlist || "");+ }+ })+ .catch(() => {+ if (alive)+ setError(t("Could not load the Invidious account. Please retry."));+ });+ return () => {+ alive = false;+ };+ }, [auth.loading, auth.statusAvailable, key, t]);++ useEffect(() => {+ if (!account) return;+ const controller = new AbortController();+ setItems([]);+ setError("");+ setBusy(false);+ if (+ (view !== "search" && !account.connected) ||+ (view === "search" && !query.trim())+ )+ return;+ setBusy(true);+ void browseInvidious(view, query, page, playlist, controller.signal)+ .then((data) => {+ if (controller.signal.aborted) return;+ setItems(Array.isArray(data) ? data : data.videos || []);+ requestAnimationFrame(() => {+ try {+ if (scroll.current)+ scroll.current.scrollTop =+ JSON.parse(browserStorage.readRaw("session", key) || "{}")+ .scroll || 0;+ } catch {+ /* Optional. */+ }+ });+ })+ .catch((e: Error) => {+ if (!controller.signal.aborted) setError(e.message);+ })+ .finally(() => {+ if (!controller.signal.aborted) setBusy(false);+ });+ return () => controller.abort();+ }, [account, view, query, page, playlist, reload, key]);++ function remember(position = 0) {+ try {+ browserStorage.writeRaw(+ "session",+ key,+ JSON.stringify({ view, query, page, playlist, scroll: position }),+ );+ } catch {+ /* Optional. */+ }+ }+ async function connect() {+ setAccountBusy(true);+ setError("");+ try {+ const result = await invidiousAccount("authorize");+ if (result.authorize_url) {+ remember();+ window.location.assign(result.authorize_url);+ }+ } catch {+ setError(t("Could not connect to Invidious. Please retry."));+ } finally {+ setAccountBusy(false);+ }+ }+ async function disconnect() {+ setAccountBusy(true);+ setError("");+ try {+ const status = await invidiousAccount("disconnect");+ setAccount(status);+ setItems([]);+ setView("search");+ setPage(1);+ setQuery("");+ setInput("");+ try {+ browserStorage.removeRaw("session", key);+ } catch {+ /* Optional. */+ }+ } catch {+ setError(+ t("Could not disconnect. Please retry when the instance is available."),+ );+ } finally {+ setAccountBusy(false);+ }+ }+ function select(url: string) {+ remember(scroll.current?.scrollTop || 0);+ router.push(`/watching?video=${encodeURIComponent(url)}`);+ onDismiss();+ }+ return (+ <section className="watching-browser" aria-label={t("Browse videos")}>+ <header className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] p-5">+ <div>+ <h1 className="text-xl font-semibold">{t("Immersive Watching")}</h1>+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ {t("Your videos, with room to learn.")}+ </p>+ </div>+ <div className="flex items-center gap-2 text-sm">+ {canDismiss && (+ <button className="watching-browser-button" onClick={onDismiss}>+ <ArrowLeft size={16} />+ {t("Back to video")}+ </button>+ )}+ <button+ className="watching-browser-button"+ disabled={accountBusy || auth.loading}+ onClick={() => void (account?.connected ? disconnect() : connect())}+ >+ {accountBusy ? (+ <Loader2 className="animate-spin" size={16} />+ ) : (+ <Link2 size={16} />+ )}+ {account?.connected+ ? t("Disconnect Invidious")+ : account?.needs_reauthorization+ ? t("Reconnect Invidious")+ : t("Connect Invidious")}+ </button>+ </div>+ </header>+ <div className="px-5 pt-5">+ {account && !account.connected && (+ <p className="mb-4 text-sm text-[var(--muted-foreground)]">+ {t(+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.",+ )}+ </p>+ )}+ <form+ className="flex gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ if (/^https?:\/\//i.test(input.trim())) {+ select(input.trim());+ return;+ }+ setView("search");+ setQuery(input.trim());+ setPage(1);+ }}+ >+ <input+ className="min-w-0 flex-1 rounded-xl border border-[var(--border)] bg-[var(--background)] px-4 py-3"+ aria-label={t("Search videos or paste a video link")}+ placeholder={t("Search videos or paste a video link")}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ />+ <button+ className="watching-browser-button"+ type="submit"+ disabled={!input.trim()}+ >+ <Search size={18} />+ <span className="hidden sm:inline">{t("Search")}</span>+ </button>+ </form>+ <nav className="mt-4 flex gap-2" aria-label={t("Video browsing views")}>+ {(+ [+ ["feed", Rss, t("Subscription feed")],+ ["playlists", ListVideo, t("Playlists")],+ ["search", Search, t("Search")],+ ] as const+ ).map(([tab, Icon, label]) => (+ <button+ key={tab}+ className="watching-browser-button"+ aria-pressed={+ view === tab || (tab === "playlists" && view === "playlist")+ }+ onClick={() => {+ setView(tab);+ setPage(1);+ }}+ >+ <Icon size={16} />+ {label}+ </button>+ ))}+ </nav>+ </div>+ <div+ ref={scroll}+ className="min-h-0 flex-1 overflow-y-auto p-5"+ onScroll={() => remember(scroll.current?.scrollTop || 0)}+ >+ {error && (+ <div+ role="alert"+ className="mb-4 rounded-xl border border-[var(--border)] p-4"+ >+ {t(error)}{" "}+ <button+ className="underline"+ onClick={() => {+ setReload((n) => n + 1);+ if (!account)+ void invidiousAccount("status")+ .then(setAccount)+ .catch(() => undefined);+ }}+ >+ {t("Retry")}+ </button>+ </div>+ )}+ {view !== "search" && account && !account.connected ? (+ <div className="watching-browser-empty">+ <Link2 size={32} />+ <p>+ {t(+ "Connect your Invidious account to see subscriptions and playlists.",+ )}+ </p>+ <button+ className="watching-browser-button"+ onClick={() => void connect()}+ disabled={accountBusy}+ >+ {t("Connect Invidious")}+ </button>+ </div>+ ) : busy ? (+ <div role="status" className="watching-browser-empty">+ <Loader2 className="animate-spin" />+ {t("Loading videos…")}+ </div>+ ) : (+ <>+ {view === "playlist" && (+ <button+ className="watching-browser-button mb-4"+ onClick={() => {+ setView("playlists");+ setPage(1);+ }}+ >+ <ArrowLeft size={16} />+ {t("Playlists")}+ </button>+ )}+ <div className="watching-video-grid">+ {items.map((item) => {+ const isPlaylist = "playlistId" in item;+ const video = isPlaylist ? item.videos?.[0] : item;+ const thumbnail = video?.videoThumbnails?.find((thumb) =>+ /^https?:\/\//.test(thumb.url),+ )?.url;+ return (+ <button+ key={isPlaylist ? item.playlistId : item.videoId}+ className="watching-video-card"+ onClick={() => {+ if (isPlaylist) {+ setPlaylist(item.playlistId);+ setView("playlist");+ setPage(1);+ } else+ select(+ `https://www.youtube.com/watch?v=${encodeURIComponent(item.videoId)}`,+ );+ }}+ >+ <div className="relative flex aspect-video items-center justify-center overflow-hidden rounded-xl bg-[var(--muted)]">+ {thumbnail ? (+ <img+ src={thumbnail}+ alt=""+ loading="lazy"+ referrerPolicy="no-referrer"+ className="h-full w-full object-cover"+ />+ ) : (+ <Play size={28} />+ )}+ {!isPlaylist && (+ <span className="absolute bottom-2 right-2 rounded bg-black/75 px-1.5 py-0.5 text-xs text-white">+ {Math.floor((item.lengthSeconds || 0) / 60)}:+ {String((item.lengthSeconds || 0) % 60).padStart(+ 2,+ "0",+ )}+ </span>+ )}+ </div>+ <h2 className="mt-3 line-clamp-2 text-sm font-medium">+ {item.title}+ </h2>+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">+ {isPlaylist+ ? `${item.videoCount} ${t("videos")}`+ : item.author}+ </p>+ </button>+ );+ })}+ </div>+ {!items.length && !error && (+ <div className="watching-browser-empty">+ <Play size={32} />+ <p>+ {view === "search" && !query+ ? t("Find a video to start learning.")+ : t("No videos here yet.")}+ </p>+ </div>+ )}+ {view !== "playlists" && (items.length > 0 || page > 1) && (+ <div className="mt-6 flex justify-center gap-4">+ <button+ className="watching-browser-button"+ disabled={page <= 1}+ onClick={() => setPage(page - 1)}+ >+ {t("Previous")}+ </button>+ <span className="self-center">{page}</span>+ <button+ className="watching-browser-button"+ disabled={!items.length}+ onClick={() => setPage(page + 1)}+ >+ {t("Next")}+ </button>+ </div>+ )}+ </>+ )}+ </div>+ </section>+ );+}diff --git a/web/components/watching/WatchingWorkspace.tsx b/web/components/watching/WatchingWorkspace.tsxnew file mode 100644index 000000000..c21e7905e--- /dev/null+++ b/web/components/watching/WatchingWorkspace.tsx@@ -0,0 +1,148 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useSearchParams, useParams } from "next/navigation";+import { invidiousAccountResultMessage } from "@/lib/invidious-account-result";+import { WatchingBrowser } from "./WatchingBrowser";+import { useTranslation } from "react-i18next";+import { useWatching } from "@/context/WatchingContext";+import type { SessionConfiguration } from "@/features/chat/ChatStateAdapter";+import { WatchingPane, WATCHING_ASK_EVENT } from "./WatchingPane";++/** Bind the existing player to the selected conversation, never browser-global history. */+export function WatchingSessionBridge({+ sessionKey,+ materialId,+ onMaterial,+ sourceUrl,+}: {+ sourceUrl?: string | null;+ sessionKey: string;+ materialId: string | null;+ onMaterial(configuration: SessionConfiguration): void;+}) {+ const { material, loading, error, restore, close, openUrl } = useWatching();+ const [restoredKey, setRestoredKey] = useState<string | null>(null);+ const binding = useRef(materialId);+ useEffect(() => {+ binding.current = materialId;+ }, [materialId]);+ useEffect(() => {+ let cancelled = false;+ void restore(sourceUrl ? null : binding.current).then(async () => {+ if (cancelled) return;+ if (sourceUrl) await openUrl(sourceUrl);+ if (!cancelled) setRestoredKey(sessionKey);+ });+ return () => {+ cancelled = true;+ close();+ };+ }, [sessionKey, sourceUrl, restore, close, openUrl]);+ useEffect(() => {+ if (+ restoredKey !== sessionKey ||+ loading ||+ error ||+ (material?.material_id ?? null) === materialId+ )+ return;+ onMaterial({ timedMediaId: material?.material_id ?? null });+ }, [+ restoredKey,+ sessionKey,+ material,+ materialId,+ loading,+ error,+ onMaterial,+ ]);+ return null;+}++/** Responsive presentation only; ChatWorkspace continues to own the single chat runtime. */+export function WatchingSurface() {+ const { t } = useTranslation();+ const { material } = useWatching();+ const params = useSearchParams();+ const route = useParams();+ const [browsing, setBrowsing] = useState(+ !params.get("video") && !route.sessionId,+ );+ const [accountResult, setAccountResult] = useState(params.get("account"));+ const accountMessage = invidiousAccountResultMessage(accountResult);+ useEffect(() => {+ if (params.has("account"))+ window.history.replaceState(null, "", "/watching");+ }, [params]);+ const showBrowser = browsing && !params.get("video");+ const [view, setView] = useState<"video" | "chat">("video");+ useEffect(() => {+ const showChat = () => setView("chat");+ window.addEventListener(WATCHING_ASK_EVENT, showChat);+ return () => window.removeEventListener(WATCHING_ASK_EVENT, showChat);+ }, []);+ return (+ <div+ className="watching-surface"+ data-mobile-view={view}+ data-browsing={showBrowser || undefined}+ >+ {accountMessage && showBrowser && (+ <div+ role={accountResult === "connected" ? "status" : "alert"}+ className="watching-account-error flex items-center justify-between gap-3"+ >+ <span>{t(accountMessage)}</span>+ <button+ type="button"+ className="watching-browser-button shrink-0"+ onClick={() => setAccountResult(null)}+ >+ {t("Dismiss")}+ </button>+ </div>+ )}+ {showBrowser && (+ <WatchingBrowser+ canDismiss={!!material}+ onDismiss={() => setBrowsing(false)}+ />+ )}+ {!showBrowser && (+ <button+ className="watching-browse-toggle watching-browser-button"+ onClick={() => {+ window.history.replaceState(null, "", window.location.pathname);+ setBrowsing(true);+ }}+ >+ {t("Browse videos")}+ </button>+ )}+ <div+ className="watching-mobile-tabs"+ role="group"+ aria-label={t("Immersive Watching")}+ >+ <button+ type="button"+ aria-pressed={view === "video"}+ onClick={() => setView("video")}+ >+ {t("Video")}+ </button>+ <button+ type="button"+ aria-pressed={view === "chat"}+ onClick={() => setView("chat")}+ >+ {t("Conversation")}+ </button>+ </div>+ <div className="dt-watching-shell" data-watching-open="true">+ <WatchingPane onClose={() => setView("chat")} />+ </div>+ </div>+ );+}diff --git a/web/context/WatchingContext.tsx b/web/context/WatchingContext.tsxindex a51ec310d..119f959a6 100644--- a/web/context/WatchingContext.tsx+++ b/web/context/WatchingContext.tsx@@ -1,12 +1,10 @@"use client";-import { browserStorage } from "@/shared/storage";-import {createContext,useCallback,useContext,- useEffect,+ useRef,useMemo,useState,type ReactNode,@@ -25,9 +23,6 @@ import {setWatchingViewport,} from "@/lib/watching-turn-state";-const LAST_MATERIAL_KEY = "dt:video-learning:last-material";-const LAST_URL_KEY = "dt:video-learning:last-url";-interface WatchingContextValue {material: TimedMediaMaterial | null;active: boolean;@@ -39,6 +34,7 @@ interface WatchingContextValue {language?: string,providerOverride?: VideoProvider,): Promise<void>;+ restore(materialId: string | null): Promise<void>;refresh(): Promise<void>;refreshTranscript(): Promise<void>;close(): void;@@ -56,46 +52,52 @@ export function WatchingProvider({ children }: { children: ReactNode }) {const [error, setError] = useState<string | null>(null);const [lastUrl, setLastUrl] = useState("");const [active, setActive] = useState(false);+ const generation = useRef(0);const accept = useCallback((next: TimedMediaMaterial) => {setMaterial(next);setWatchingMaterial(next.material_id);setWatchingViewport(next.playback.start_seconds || 0);- if (typeof window !== "undefined") {- browserStorage.writeRaw("local", LAST_MATERIAL_KEY, next.material_id);- browserStorage.writeRaw("local", LAST_URL_KEY, next.source.url);- }+ setLastUrl(next.source.url);}, []);- useEffect(() => {- if (typeof window === "undefined") return;- if (!active || material) return;- const materialId = browserStorage.readRaw("local", LAST_MATERIAL_KEY);- if (!materialId) return;- const sourceUrl = browserStorage.readRaw("local", LAST_URL_KEY) || "";- setLastUrl(sourceUrl);- setLoading(true);- void getVideoMaterial(materialId)- .then(accept)- .catch((caught) => {- setError(- caught instanceof Error- ? caught.message- : t("The player provider is unavailable."),- );- browserStorage.removeRaw("local", LAST_MATERIAL_KEY);- })- .finally(() => setLoading(false));- }, [accept, active, material, t]);+ const restore = useCallback(+ async (materialId: string | null) => {+ const request = ++generation.current;+ setMaterial(null);+ setWatchingMaterial(null);+ setLastUrl("");+ setError(null);+ setLoading(Boolean(materialId));+ if (!materialId) return;+ try {+ const next = await getVideoMaterial(materialId);+ if (request === generation.current) accept(next);+ } catch (caught) {+ if (request === generation.current)+ setError(+ caught instanceof Error+ ? caught.message+ : t("The player provider is unavailable."),+ );+ } finally {+ if (request === generation.current) setLoading(false);+ }+ },+ [accept, t],+ );const openUrl = useCallback(async (url: string, language = "", providerOverride?: VideoProvider) => {+ const request = ++generation.current;setLoading(true);setError(null);setLastUrl(url);try {- accept(await resolveVideo(url, language, providerOverride));+ const next = await resolveVideo(url, language, providerOverride);+ if (request === generation.current) accept(next);} catch (caught) {+ if (request !== generation.current) return;setError(caught instanceof Error? caught.message@@ -103,7 +105,7 @@ export function WatchingProvider({ children }: { children: ReactNode }) {);throw caught;} finally {- setLoading(false);+ if (request === generation.current) setLoading(false);}},[accept, t],@@ -111,46 +113,51 @@ export function WatchingProvider({ children }: { children: ReactNode }) {const refresh = useCallback(async () => {if (!material) return;+ const request = ++generation.current;setLoading(true);setError(null);try {- accept(await getVideoMaterial(material.material_id));+ const next = await getVideoMaterial(material.material_id);+ if (request === generation.current) accept(next);} catch (caught) {+ if (request !== generation.current) return;setError(caught instanceof Error? caught.message: t("The player provider is unavailable."),);} finally {- setLoading(false);+ if (request === generation.current) setLoading(false);}}, [accept, material, t]);const refreshTranscript = useCallback(async () => {if (!material) return;+ const request = ++generation.current;setLoading(true);setError(null);try {- accept(await refreshInvidiousTranscript(material.material_id));+ const next = await refreshInvidiousTranscript(material.material_id);+ if (request === generation.current) accept(next);} catch (caught) {+ if (request !== generation.current) return;setError(caught instanceof Error? caught.message: t("The player provider is unavailable."),);} finally {- setLoading(false);+ if (request === generation.current) setLoading(false);}}, [accept, material, t]);const close = useCallback(() => {+ generation.current += 1;setMaterial(null);setWatchingMaterial(null);+ setLastUrl("");+ setLoading(false);setError(null);- if (typeof window !== "undefined") {- browserStorage.removeRaw("local", LAST_MATERIAL_KEY);- browserStorage.removeRaw("local", LAST_URL_KEY);- }}, []);const reportTime = useCallback((seconds: number) => setWatchingViewport(seconds),@@ -166,6 +173,7 @@ export function WatchingProvider({ children }: { children: ReactNode }) {error,lastUrl,openUrl,+ restore,refresh,refreshTranscript,close,@@ -180,6 +188,7 @@ export function WatchingProvider({ children }: { children: ReactNode }) {error,lastUrl,openUrl,+ restore,refresh,refreshTranscript,close,diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex d72678dfe..c950b5168 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -8513,6 +8513,23 @@ export interface paths {readonly patch?: never;readonly trace?: never;};+ readonly "/api/video-learning/invidious/browse/{kind}": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ /** Browse Invidious */+ readonly get: operations["browse_invidious_api_video_learning_invidious_browse__kind__get"];+ readonly put?: never;+ readonly post?: never;+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/video-learning/materials/{material_id}": {readonly parameters: {readonly query?: never;@@ -32997,6 +33014,45 @@ export interface operations {};};};+ readonly browse_invidious_api_video_learning_invidious_browse__kind__get: {+ readonly parameters: {+ readonly query?: {+ readonly page?: number;+ readonly playlist_id?: string;+ readonly q?: string;+ };+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path: {+ readonly kind: string;+ };+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody?: never;+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": unknown;+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };readonly get_video_material_api_video_learning_materials__material_id__get: {readonly parameters: {readonly query?: never;diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex c103168fc..8685a2efe 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -49541,6 +49541,110 @@]}},+ "/api/video-learning/invidious/browse/{kind}": {+ "get": {+ "operationId": "browse_invidious_api_video_learning_invidious_browse__kind__get",+ "parameters": [+ {+ "in": "path",+ "name": "kind",+ "required": true,+ "schema": {+ "title": "Kind",+ "type": "string"+ }+ },+ {+ "in": "query",+ "name": "q",+ "required": false,+ "schema": {+ "default": "",+ "maxLength": 500,+ "title": "Q",+ "type": "string"+ }+ },+ {+ "in": "query",+ "name": "page",+ "required": false,+ "schema": {+ "default": 1,+ "maximum": 1000,+ "minimum": 1,+ "title": "Page",+ "type": "integer"+ }+ },+ {+ "in": "query",+ "name": "playlist_id",+ "required": false,+ "schema": {+ "default": "",+ "maxLength": 100,+ "title": "Playlist Id",+ "type": "string"+ }+ },+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {}+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Browse Invidious",+ "tags": ["video-learning"]+ }+ },"/api/video-learning/materials/resolve": {"post": {"operationId": "resolve_video_api_video_learning_materials_resolve_post",diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 8770a28ac..9ac681978 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -88,12 +88,7 @@ import {} from "@/lib/reading-references";type SessionRuntimeStatus =- | "idle"- | "running"- | "completed"- | "failed"- | "cancelled"- | "rejected";+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";interface OutgoingAttachment {type: string;@@ -143,6 +138,7 @@ export interface ChatState {activeCapability: string | null;/** Stable product surface; per-turn capability selection is orthogonal. */workspaceMode: WorkspaceMode | null;+ timedMediaId: string | null;knowledgeBases: string[];llmSelection: LLMSelection | null;/** Persistent mastery state associated with this conversation. */@@ -171,6 +167,7 @@ export interface ChatState {export interface SessionConfiguration {capability?: string | null;workspaceMode?: WorkspaceMode | null;+ timedMediaId?: string | null;knowledgeBases?: string[];masteryPathId?: string | null;masterySessionMode?: string | null;@@ -285,6 +282,7 @@ interface SessionSnapshot {tools?: string[];capability?: string | null;workspaceMode?: WorkspaceMode | null;+ timedMediaId?: string | null;knowledgeBases?: string[];llmSelection?: LLMSelection | null;masteryPathId?: string | null;@@ -394,6 +392,7 @@ function createSessionEntry(enabledTools: [],activeCapability: null,workspaceMode: null,+ timedMediaId: null,knowledgeBases: [],llmSelection: null,masteryPathId: null,@@ -448,6 +447,10 @@ function applySessionConfiguration(configuration.capability !== undefined? configuration.capability: session.activeCapability,+ timedMediaId:+ configuration.timedMediaId !== undefined+ ? configuration.timedMediaId+ : session.timedMediaId,workspaceMode:configuration.workspaceMode !== undefined? configuration.workspaceMode@@ -893,6 +896,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {action.capability !== undefined? action.capability: existing.activeCapability,+ timedMediaId:+ action.timedMediaId !== undefined+ ? action.timedMediaId+ : existing.timedMediaId,workspaceMode:action.workspaceMode !== undefined? action.workspaceMode@@ -1987,10 +1994,18 @@ export function ChatStateAdapterProvider({// promoted to a workspace mode, that value means the default Chat// action rather than a hidden legacy entry in the action picker.capability:- session.preferences?.capability === loadedWorkspaceMode+ session.preferences?.capability === loadedWorkspaceMode &&+ loadedWorkspaceMode !== "immersive_watching"? null: session.preferences?.capability || null,workspaceMode: loadedWorkspaceMode,+ timedMediaId:+ session.preferences?.timed_media_id ||+ [...messages]+ .reverse()+ .find((message) => message.requestSnapshot?.timedMediaId)+ ?.requestSnapshot?.timedMediaId ||+ null,knowledgeBases: Array.isArray(session.preferences?.knowledge_bases)? session.preferences.knowledge_bases: [],@@ -2497,6 +2512,7 @@ export function ChatStateAdapterProvider({enabledTools: current.enabledTools,activeCapability: current.activeCapability,workspaceMode: current.workspaceMode,+ timedMediaId: current.timedMediaId,knowledgeBases: current.knowledgeBases,llmSelection: current.llmSelection,masteryPathId: current.masteryPathId,diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 01e102db2..53fefade5 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -1,5 +1,11 @@"use client";+import {+ WatchingSessionBridge,+ WatchingSurface,+} from "@/components/watching/WatchingWorkspace";++import { useSearchParams } from "next/navigation";import dynamic from "next/dynamic";import {type KeyboardEvent,@@ -55,10 +61,7 @@ import {} from "@/features/chat/ChatStateAdapter";import { useAppShell } from "@/context/AppShellContext";-import {- WATCHING_ASK_EVENT,- WatchingPane,-} from "@/components/watching/WatchingPane";+import { WATCHING_ASK_EVENT } from "@/components/watching/WatchingPane";import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";import type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";import {@@ -239,8 +242,13 @@ interface KnowledgeBase {/* Chat page *//* ------------------------------------------------------------------ */-export default function ChatWorkspace() {+export default function ChatWorkspace({+ watching = false,+}: {+ watching?: boolean;+}) {const { router, sessionId: sessionIdParam } = useChatRouteSession();+ const searchParams = useSearchParams();const { t } = useTranslation();const {capabilities,@@ -253,6 +261,7 @@ export default function ChatWorkspace() {state,setTools,setCapability,+ configureSession,setKBs,setLLMSelection,setPersonaSelection,@@ -272,6 +281,8 @@ export default function ChatWorkspace() {setCourseId,} = useChatStateAdapter();+ const entrySessionId = useRef(state.sessionId);+const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);const [knowledgeBasesLoaded, setKnowledgeBasesLoaded] = useState(false);const availableKbNames = useMemo(@@ -608,7 +619,19 @@ export default function ChatWorkspace() {const isQuizMode = activeCap.value === "deep_question";const isVisualizeMode = activeCap.value === "visualize";const isResearchMode = activeCap.value === "deep_research";- const isWatchingMode = activeCap.value === "immersive_watching";+ const isWatchingMode = watching;+ useEffect(() => {+ if (!sessionIdParam || state.sessionId !== sessionIdParam) return;+ if (!watching && state.workspaceMode === "immersive_watching") {+ router.replace(`/watching/${encodeURIComponent(sessionIdParam)}`, {+ scroll: false,+ });+ } else if (watching && state.workspaceMode !== "immersive_watching") {+ router.replace(`/chat/${encodeURIComponent(sessionIdParam)}`, {+ scroll: false,+ });+ }+ }, [watching, state.workspaceMode, state.sessionId, sessionIdParam, router]);const capabilityNeedsConfig = isQuizMode || isVisualizeMode || isResearchMode;const returnedResearchTurnRef = useRef<string | null>(null);@@ -1009,8 +1032,8 @@ export default function ChatWorkspace() {/* ---- URL-driven session loading ---- */const navigateToHome = useCallback(() => {- router.replace("/chat", { scroll: false });- }, [router]);+ router.replace(watching ? "/watching" : "/chat", { scroll: false });+ }, [router, watching]);/** Abort in-flight load + navigate home. */const cancelSessionLoad = useCallback(() => {@@ -1115,7 +1138,14 @@ export default function ChatWorkspace() {if (sessionIdParam) {startSessionLoad(sessionIdParam);} else {- newSession();+ newSession(+ watching+ ? {+ capability: "immersive_watching",+ workspaceMode: "immersive_watching",+ }+ : undefined,+ );}return () => {initialLoadRef.current = false;@@ -1138,18 +1168,31 @@ export default function ChatWorkspace() {}startSessionLoad(sessionIdParam);} else {- newSession();+ newSession(+ watching+ ? {+ capability: "immersive_watching",+ workspaceMode: "immersive_watching",+ }+ : undefined,+ );setSessionLoading(false);setSessionLoadFailed(false);}- }, [sessionIdParam, startSessionLoad, newSession, state.sessionId]);+ }, [sessionIdParam, startSessionLoad, newSession, state.sessionId, watching]);// When a new session_id is assigned by the server, update the URLuseEffect(() => {- if (state.sessionId && !sessionIdParam) {- router.replace(`/chat/${state.sessionId}`, { scroll: false });+ if (+ state.sessionId &&+ !sessionIdParam &&+ state.sessionId !== entrySessionId.current+ ) {+ router.replace(`${watching ? "/watching" : "/chat"}/${state.sessionId}`, {+ scroll: false,+ });}- }, [state.sessionId, sessionIdParam, router]);+ }, [state.sessionId, sessionIdParam, router, watching]);useEffect(() => {setActiveSessionId(state.sessionId || sessionIdParam || null);@@ -1366,6 +1409,11 @@ export default function ChatWorkspace() {const handleSelectCapability = useCallback((value: string) => {+ if (value === "immersive_watching" && !watching) {+ router.push("/watching");+ return;+ }+ if (watching && value !== "immersive_watching") return;const cap =capabilities.find((capability) => capability.value === value) ??capabilities[0] ??@@ -1385,7 +1433,7 @@ export default function ChatWorkspace() {setCapabilityConfigConfirmed(false);setCapMenuOpen(false);},- [capabilities, setCapability, setTools, userEnabledTools],+ [capabilities, setCapability, setTools, userEnabledTools, watching, router],);const fileToAttachment = fileToPendingAttachment;@@ -2247,20 +2295,21 @@ export default function ChatWorkspace() {messages={state.messages}viewerPanelRef={viewerPanelRef}/>- <div className="relative h-full overflow-hidden">- {/* The video panel slides in from the left and the chat column shrinks to- make room. Rendered as a sibling with its own transform rather than- wrapping the chat, so switching modes never remounts the chat tree —- a remount would refetch every piece of session metadata and stall the- UI for seconds (the regression behind the slow session-open bug). */}- <div- data-watching-open={isWatchingMode ? "true" : "false"}- className="dt-watching-shell"- >- {isWatchingMode && (- <WatchingPane onClose={() => setCapability("")} />+ <div+ className="relative h-full overflow-hidden"+ data-watching-workspace={watching ? "true" : undefined}+ >+ {watching &&+ state.workspaceMode === "immersive_watching" &&+ (!sessionIdParam || state.sessionId === sessionIdParam) && (+ <WatchingSessionBridge+ sessionKey={state.sessionId || "draft"}+ sourceUrl={!sessionIdParam ? searchParams.get("video") : null}+ materialId={state.timedMediaId}+ onMaterial={configureSession}+ />)}- </div>+ {watching && <WatchingSurface />}<div// When the preview drawer is open AND the viewport is wide enough,// push the chat content to the left by the drawer's width so the two@@ -2533,7 +2582,13 @@ export default function ChatWorkspace() {capabilityNeedsConfig={capabilityNeedsConfig}capabilityConfigConfirmed={capabilityConfigConfirmed}onRequestConfigConfirm={ensureActivityPanelOpen}- capabilities={visibleCapabilities}+ capabilities={+ watching+ ? visibleCapabilities.filter(+ (cap) => cap.value === "immersive_watching",+ )+ : visibleCapabilities+ }onSetCapMenuOpen={setCapMenuOpen}onSetSpaceMenuOpen={setSpaceMenuOpen}onToggleKB={handleToggleKB}diff --git a/web/lib/capability-routes.ts b/web/lib/capability-routes.tsindex 3ff7e3452..81924e9aa 100644--- a/web/lib/capability-routes.ts+++ b/web/lib/capability-routes.ts@@ -24,6 +24,7 @@ export const ROUTE_CAPABILITIES: ReadonlyArray<{{ prefix: "/co-writer", capability: "llm" },{ prefix: "/books", capability: "llm" },{ prefix: "/reading", capability: "llm" },+ { prefix: "/watching", capability: "llm" },{ prefix: "/mastery", capability: "llm" }, // Mastery Path];diff --git a/web/lib/invidious-account-result.ts b/web/lib/invidious-account-result.tsnew file mode 100644index 000000000..ae7e6e354--- /dev/null+++ b/web/lib/invidious-account-result.ts@@ -0,0 +1,27 @@+/** Static translation keys for safe callback outcomes; never render provider input. */+export function invidiousAccountResultMessage(+ result: string | null,+): string | null {+ switch (result) {+ case "connected":+ return "Invidious account connected. Your subscriptions and playlists are ready.";+ case "authorization_expired":+ return "This authorization link expired or was already used. Click Connect Invidious to start again.";+ case "authorization_cancelled":+ return "Authorization was cancelled. You can connect again whenever you are ready.";+ case "authorization_scopes":+ return "Some read permissions were missing. Reconnect and approve all listed permissions.";+ case "authorization_token_invalid":+ return "The instance returned an unsupported token. Start a new connection and try again.";+ case "authorization_token_rejected":+ return "Invidious rejected the token. Reconnect to issue a new one.";+ case "authorization_unavailable":+ return "The Invidious instance could not verify your account. Check the instance and reconnect.";+ case "authorization_login_required":+ return "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.";+ case "authorization_failed":+ return "The account could not be connected. Please start a new connection.";+ default:+ return null;+ }+}diff --git a/web/lib/mastery-session.ts b/web/lib/mastery-session.tsindex 30b3ef3a6..8e7ae5020 100644--- a/web/lib/mastery-session.ts+++ b/web/lib/mastery-session.ts@@ -74,5 +74,11 @@ export function sessionRoute(session: SessionSummary): string {if (workspaceId) {return `/reading/${encodeURIComponent(workspaceId)}/sessions/${sessionId}`;}+ if (+ session.preferences?.workspace_mode === "immersive_watching" ||+ session.preferences?.capability === "immersive_watching"+ ) {+ return `/watching/${sessionId}`;+ }return `/chat/${sessionId}`;}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 070af14b6..987022013 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -63,8 +63,10 @@ export interface MessageTracePage {export interface SessionPreferences {capability?: string;+ timed_media_id?: string;/** Stable learning surface, independent of the action used for a turn. */- workspace_mode?: "immersive_reading" | "mastery_path" | "";+ workspace_mode?:+ "immersive_reading" | "mastery_path" | "immersive_watching" | "";tools?: string[];knowledge_bases?: string[];language?: string;@@ -101,12 +103,7 @@ export interface SessionSummary {message_count: number;last_message: string;status?:- | "idle"- | "running"- | "completed"- | "failed"- | "cancelled"- | "rejected";+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";active_turn_id?: string;preferences?: SessionPreferences;}@@ -131,12 +128,7 @@ export interface SessionDetail {created_at: number;updated_at: number;status?:- | "idle"- | "running"- | "completed"- | "failed"- | "cancelled"- | "rejected";+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";active_turn_id?: string;compressed_summary?: string;summary_up_to_msg_id?: number;@@ -232,7 +224,10 @@ export async function fetchSessionAskHint(try {const response = await apiFetch(apiUrl(`/api/sessions/${sessionId}/ask-hint`),- { cache: "no-store", ...init },+ {+ cache: "no-store",+ ...init,+ },);const result = await expectJson<{ hint?: string }>(response);return typeof result.hint === "string" ? result.hint : "";@@ -326,7 +321,9 @@ export async function deleteMessage(): Promise<void> {const response = await apiFetch(apiUrl(`/api/sessions/${sessionId}/messages/${messageId}`),- { method: "DELETE" },+ {+ method: "DELETE",+ },);await expectJson<{ deleted: boolean }>(response);}diff --git a/web/lib/video-learning-api.ts b/web/lib/video-learning-api.tsindex fe81e48a7..6704c3385 100644--- a/web/lib/video-learning-api.ts+++ b/web/lib/video-learning-api.ts@@ -274,3 +274,53 @@ export async function testInvidious(}),);}++export interface InvidiousAccountStatus {+ connected: boolean;+ needs_reauthorization?: boolean;+}+export interface InvidiousVideo {+ videoId: string;+ title: string;+ author: string;+ lengthSeconds: number;+ videoThumbnails?: { url: string }[];+}+export interface InvidiousPlaylist {+ playlistId: string;+ title: string;+ videoCount: number;+ videos?: InvidiousVideo[];+}+export interface InvidiousCatalog {+ videos?: InvidiousVideo[];+}+export async function invidiousAccount(+ action: "status" | "authorize" | "disconnect",+) {+ return unwrap<InvidiousAccountStatus & { authorize_url?: string }>(+ await apiFetch(`/api/video-learning/invidious/account/${action}`, {+ method: action === "status" ? "GET" : "POST",+ cache: "no-store",+ }),+ );+}+export async function browseInvidious(+ kind: string,+ query: string,+ page: number,+ playlistId: string,+ signal: AbortSignal,+) {+ const params = new URLSearchParams({+ q: query,+ page: String(page),+ playlist_id: playlistId,+ });+ return unwrap<InvidiousVideo[] | InvidiousPlaylist[] | InvidiousCatalog>(+ await apiFetch(`/api/video-learning/invidious/browse/${kind}?${params}`, {+ signal,+ cache: "no-store",+ }),+ );+}diff --git a/web/lib/watching-citations.ts b/web/lib/watching-citations.tsindex bb1975e90..e76a0b332 100644--- a/web/lib/watching-citations.ts+++ b/web/lib/watching-citations.ts@@ -1,7 +1,8 @@import { codeRanges } from "@/lib/reading-citations";export const VIDEO_TIME_HREF_PREFIX = "#dt-video-time-";-const TIMESTAMP = /\[(?:(\d{1,2}):)?([0-5]?\d):([0-5]\d)\]/g;+const TIMESTAMP =+ /\[(?:(\d{1,2}):)?([0-5]?\d):([0-5]\d)\](?:\((?:[^()]|\([^()]*\))*\))?/g;export function linkifyVideoTimestamps(text: string): string {const skip = codeRanges(text);@@ -15,10 +16,12 @@ export function linkifyVideoTimestamps(text: string): string {offset: number,) => {if (skip.some(([from, to]) => offset >= from && offset < to)) return raw;- if (text[offset + raw.length] === "(") return raw;+ // A video citation always seeks the current material, including when+ // the model supplied a fabricated or external Markdown link target.+ const label = raw.slice(0, raw.indexOf("]") + 1);const total =Number(hours || 0) * 3600 + Number(minutes) * 60 + Number(seconds);- return `${raw}(${VIDEO_TIME_HREF_PREFIX}${total})`;+ return `${label}(${VIDEO_TIME_HREF_PREFIX}${total})`;},);}diff --git a/web/lib/workspace-mode.ts b/web/lib/workspace-mode.tsindex 61838e304..340e43fbc 100644--- a/web/lib/workspace-mode.ts+++ b/web/lib/workspace-mode.ts@@ -1,4 +1,5 @@-export type WorkspaceMode = "immersive_reading" | "mastery_path";+export type WorkspaceMode =+ "immersive_reading" | "mastery_path" | "immersive_watching";export const READING_WORKSPACE_MODE = "immersive_reading" as const;export const MASTERY_WORKSPACE_MODE = "mastery_path" as const;@@ -20,12 +21,17 @@ export function normalizeWorkspaceMode(value: unknown,legacyCapability?: unknown,): WorkspaceMode | null {- if (value === READING_WORKSPACE_MODE || value === MASTERY_WORKSPACE_MODE) {+ if (+ value === READING_WORKSPACE_MODE ||+ value === MASTERY_WORKSPACE_MODE ||+ value === "immersive_watching"+ ) {return value;}if (legacyCapability === READING_WORKSPACE_MODE ||- legacyCapability === MASTERY_WORKSPACE_MODE+ legacyCapability === MASTERY_WORKSPACE_MODE ||+ legacyCapability === "immersive_watching") {return legacyCapability;}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex a7135d41d..ea72027d8 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1001,6 +1001,8 @@"Initial documents": "Initial documents","e.g. project-papers": "e.g. project-papers","Processing…": "Processing…",+ "Ready · {{count}} doc": "Ready · {{count}} doc",+ "Ready · {{count}} docs": "Ready · {{count}} docs","Dismiss": "Dismiss","Files": "Files","Add documents": "Add documents",@@ -4009,5 +4011,39 @@"references": "references","That question is no longer waiting for an answer, so this was sent as a new message.": "That question is no longer waiting for an answer, so this was sent as a new message.","A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.",- "Select text in the document first.": "Select text in the document first."+ "Select text in the document first.": "Select text in the document first.",+ "Watch videos with a grounded AI companion.": "Watch videos with a grounded AI companion.",+ "Conversation": "Conversation",+ "Browse videos": "Browse videos",+ "Back to video": "Back to video",+ "Your videos, with room to learn.": "Your videos, with room to learn.",+ "Connect Invidious": "Connect Invidious",+ "Disconnect Invidious": "Disconnect Invidious",+ "Reconnect Invidious": "Reconnect Invidious",+ "Search videos or paste a video link": "Search videos or paste a video link",+ "Video browsing views": "Video browsing views",+ "Subscription feed": "Subscription feed",+ "Playlists": "Playlists",+ "Connect your Invidious account to see subscriptions and playlists.": "Connect your Invidious account to see subscriptions and playlists.",+ "Loading videos…": "Loading videos…",+ "Find a video to start learning.": "Find a video to start learning.",+ "No videos here yet.": "No videos here yet.",+ "videos": "videos",+ "Could not load the Invidious account. Please retry.": "Could not load the Invidious account. Please retry.",+ "Could not connect to Invidious. Please retry.": "Could not connect to Invidious. Please retry.",+ "Could not disconnect. Please retry when the instance is available.": "Could not disconnect. Please retry when the instance is available.",+ "Invidious authorization was cancelled or expired. Please connect again.": "Invidious authorization was cancelled or expired. Please connect again.",+ "Reconnect your Invidious account to browse your videos.": "Reconnect your Invidious account to browse your videos.",+ "Invidious could not load videos. Please retry or check the instance.": "Invidious could not load videos. Please retry or check the instance.",+ "Invidious is not configured.": "Invidious is not configured.",+ "Invidious account connected. Your subscriptions and playlists are ready.": "Invidious account connected. Your subscriptions and playlists are ready.",+ "This authorization link expired or was already used. Click Connect Invidious to start again.": "This authorization link expired or was already used. Click Connect Invidious to start again.",+ "Authorization was cancelled. You can connect again whenever you are ready.": "Authorization was cancelled. You can connect again whenever you are ready.",+ "Some read permissions were missing. Reconnect and approve all listed permissions.": "Some read permissions were missing. Reconnect and approve all listed permissions.",+ "The instance returned an unsupported token. Start a new connection and try again.": "The instance returned an unsupported token. Start a new connection and try again.",+ "Invidious rejected the token. Reconnect to issue a new one.": "Invidious rejected the token. Reconnect to issue a new one.",+ "The Invidious instance could not verify your account. Check the instance and reconnect.": "The Invidious instance could not verify your account. Check the instance and reconnect.",+ "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.",+ "The account could not be connected. Please start a new connection.": "The account could not be connected. Please start a new connection.",+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1b903f057..702df3f39 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1115,6 +1115,8 @@"Initial documents": "初始文档","e.g. project-papers": "例如:project-papers","Processing…": "处理中…",+ "Ready · {{count}} doc": "就绪 · {{count}} 个文档",+ "Ready · {{count}} docs": "就绪 · {{count}} 个文档","Dismiss": "关闭","Files": "文件","Add documents": "添加文档",@@ -4009,5 +4011,39 @@"references": "引用","That question is no longer waiting for an answer, so this was sent as a new message.": "这道题已经不再等待作答,所以这条内容作为新消息发送了。","A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "知识库名称不能包含 {{chars}} —— 这些字符会切断路径和 URL。",- "Select text in the document first.": "请先在文档中选中文字。"+ "Select text in the document first.": "请先在文档中选中文字。",+ "Watch videos with a grounded AI companion.": "与有出处依据的 AI 伙伴一起观看视频。",+ "Conversation": "对话",+ "Browse videos": "浏览视频",+ "Back to video": "返回视频",+ "Your videos, with room to learn.": "从感兴趣的视频开始,边看边学。",+ "Connect Invidious": "关联 Invidious 账号",+ "Disconnect Invidious": "解除 Invidious 关联",+ "Reconnect Invidious": "重新关联 Invidious",+ "Search videos or paste a video link": "搜索视频或粘贴视频链接",+ "Video browsing views": "视频浏览视图",+ "Subscription feed": "订阅动态",+ "Playlists": "播放列表",+ "Connect your Invidious account to see subscriptions and playlists.": "关联 Invidious 账号,查看订阅动态和播放列表。",+ "Loading videos…": "正在加载视频…",+ "Find a video to start learning.": "搜索或打开一部视频,开始学习。",+ "No videos here yet.": "这里暂时没有视频。",+ "videos": "个视频",+ "Could not load the Invidious account. Please retry.": "无法加载 Invidious 账号,请重试。",+ "Could not connect to Invidious. Please retry.": "无法关联 Invidious,请重试。",+ "Could not disconnect. Please retry when the instance is available.": "暂时无法解除关联,请在实例恢复后重试。",+ "Invidious authorization was cancelled or expired. Please connect again.": "Invidious 授权已取消或过期,请重新关联。",+ "Reconnect your Invidious account to browse your videos.": "请重新关联 Invidious 账号,以浏览视频。",+ "Invidious could not load videos. Please retry or check the instance.": "Invidious 无法加载视频,请重试或检查实例。",+ "Invidious is not configured.": "尚未配置 Invidious。",+ "Invidious account connected. Your subscriptions and playlists are ready.": "Invidious 账号已关联,可以查看订阅动态和播放列表。",+ "This authorization link expired or was already used. Click Connect Invidious to start again.": "此授权链接已过期或已使用,请点击“关联 Invidious 账号”重新开始。",+ "Authorization was cancelled. You can connect again whenever you are ready.": "已取消授权,你可以随时重新关联。",+ "Some read permissions were missing. Reconnect and approve all listed permissions.": "缺少部分读取权限,请重新关联并确认页面列出的所有权限。",+ "The instance returned an unsupported token. Start a new connection and try again.": "实例返回的令牌格式不受支持,请重新发起关联后重试。",+ "Invidious rejected the token. Reconnect to issue a new one.": "Invidious 拒绝了此令牌,请重新关联以获取新令牌。",+ "The Invidious instance could not verify your account. Check the instance and reconnect.": "Invidious 实例暂时无法验证账号,请检查实例后重新关联。",+ "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "授权期间 DeepTutor 登录已失效,请先登录 DeepTutor,再重新关联 Invidious。",+ "The account could not be connected. Please start a new connection.": "账号关联失败,请重新发起关联。",+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。"}diff --git a/web/tests/e2e/video-learning.audit.ts b/web/tests/e2e/video-learning.audit.tsindex 988a2fba1..6aa35bb74 100644--- a/web/tests/e2e/video-learning.audit.ts+++ b/web/tests/e2e/video-learning.audit.ts@@ -3,571 +3,657 @@ import { expect, test } from '@playwright/test'const MATERIAL_ID = '0123456789abcdef0123456789abcdef'const SECOND_MATERIAL_ID = 'fedcba9876543210fedcba9876543210'-test('YouTube learning survives reload and switches to Invidious without silent fallback', async ({- page,-}) => {- let provider: 'youtube' | 'invidious' = 'youtube'- let secondMaterial = false- let invidiousOffline = false- let transcriptReady = true- let transcriptRefreshCount = 0- let materialRequestCount = 0- let savedPosition = 0- let nativeResolveCount = 0- let exportRequestCount = 0- let exportShouldFail = false- 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 transcriptCues = [- { start: 7, end: 12, text: 'The first grounded concept.' },- ...Array.from({ length: 60 }, (_, index) => ({- start: 13 + index,- end: 14 + index,- text: `Intermediate lesson detail ${index + 1}.`,- })),- { start: 70, end: 75, text: 'The second grounded concept.' },- { start: 110, end: 115, text: 'The third grounded concept.' },- ]+for (const mobile of [false, true]) {+ test(`Watching workspace restores its session and handles provider failures (${mobile ? 'mobile' : 'desktop'})`, async ({+ page,+ }) => {+ await page.setViewportSize(mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 })+ let provider: 'youtube' | 'invidious' = 'youtube'+ let secondMaterial = false+ let invidiousOffline = false+ let transcriptReady = true+ let transcriptRefreshCount = 0+ let savedPosition = 0+ let nativeResolveCount = 0+ let exportRequestCount = 0+ let exportShouldFail = false+ 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 transcriptCues = [+ { start: 7, end: 12, text: 'The first grounded concept.' },+ ...Array.from({ length: 60 }, (_, index) => ({+ start: 13 + index,+ end: 14 + index,+ text: `Intermediate lesson detail ${index + 1}.`,+ })),+ { start: 70, end: 75, text: 'The second grounded concept.' },+ { start: 110, end: 115, text: 'The third grounded concept.' },+ ]- const material = (selected: 'youtube' | 'invidious') => {- const materialId = secondMaterial ? SECOND_MATERIAL_ID : MATERIAL_ID- const videoId = secondMaterial ? '9bZkp7q19f0' : 'dQw4w9WgXcQ'- return {- version: 1,- type: 'timed_media',- material_id: materialId,- source: {- provider: 'youtube',- video_id: videoId,- url: `https://youtu.be/${videoId}`,- entry_time_seconds: 0,- },- metadata: {- title: secondMaterial ? 'Replacement lesson' : 'Timestamped lesson',- author: 'Teacher',- duration_seconds: 120,- },- transcript: transcriptReady- ? {- status: 'ready',- reason: '',- language: 'en',- source: selected,- cues: transcriptCues,- }- : {- status: 'unavailable',- reason: 'temporary Invidious error',- language: '',- source: 'unavailable',- cues: [],- },- segments: [],- learning: { last_position: savedPosition },- playback:- selected === 'youtube'+ const material = (selected: 'youtube' | 'invidious') => {+ const materialId = secondMaterial ? SECOND_MATERIAL_ID : MATERIAL_ID+ const videoId = secondMaterial ? '9bZkp7q19f0' : 'dQw4w9WgXcQ'+ return {+ version: 1,+ type: 'timed_media',+ material_id: materialId,+ source: {+ provider: 'youtube',+ video_id: videoId,+ url: `https://youtu.be/${videoId}`,+ entry_time_seconds: 0,+ },+ metadata: {+ title: secondMaterial ? 'Replacement lesson' : 'Timestamped lesson',+ author: 'Teacher',+ duration_seconds: 120,+ },+ transcript: transcriptReady? {- provider: 'youtube',- kind: 'youtube_iframe',- video_id: videoId,- start_seconds: savedPosition,+ status: 'ready',+ reason: '',+ language: 'en',+ source: selected,+ cues: transcriptCues,}: {- provider: 'invidious',- kind: 'html5',- format_id: '18',- mime_type: 'video/mp4',- stream_url: `/api/video-learning/materials/${materialId}/stream/18`,- subtitles_url: `/api/video-learning/materials/${materialId}/subtitles.vtt`,- start_seconds: savedPosition,+ status: 'unavailable',+ reason: 'temporary Invidious error',+ language: '',+ source: 'unavailable',+ cues: [],},+ segments: [],+ learning: { last_position: savedPosition },+ playback:+ selected === 'youtube'+ ? {+ provider: 'youtube',+ kind: 'youtube_iframe',+ video_id: videoId,+ start_seconds: savedPosition,+ }+ : {+ provider: 'invidious',+ kind: 'html5',+ format_id: '18',+ mime_type: 'video/mp4',+ stream_url: `/api/video-learning/materials/${materialId}/stream/18`,+ subtitles_url: `/api/video-learning/materials/${materialId}/subtitles.vtt`,+ start_seconds: savedPosition,+ },+ }}- }- await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])- await page.addInitScript(() => {- class FakePlayer {- current = 0- duration = 120- rate = 1- element: HTMLElement- options: Record<string, unknown>+ await page.addInitScript(() => {+ class FakePlayer {+ current = 0+ duration = 120+ rate = 1+ element: HTMLElement+ options: Record<string, unknown>- constructor(element: HTMLElement, options: Record<string, unknown>) {- this.element = element- this.options = options- const iframe = document.createElement('iframe')- const host = String(options.host || '')- const videoId = String(options.videoId || '')- iframe.src = `${host}/embed/${videoId}`- iframe.title = 'Fake YouTube player'- element.replaceWith(iframe)- this.element = iframe- const players = ((- window as typeof window & { __fakePlayers?: FakePlayer[] }- ).__fakePlayers ||= [])- players.push(this)- queueMicrotask(() => {- const events = options.events as {- onReady?: (event: { target: FakePlayer }) => void- }- events.onReady?.({ target: this })- })- }+ constructor(element: HTMLElement, options: Record<string, unknown>) {+ this.element = element+ this.options = options+ const iframe = document.createElement('iframe')+ const host = String(options.host || '')+ const videoId = String(options.videoId || '')+ iframe.src = `${host}/embed/${videoId}`+ iframe.title = 'Fake YouTube player'+ element.replaceWith(iframe)+ this.element = iframe+ const players = ((+ window as typeof window & { __fakePlayers?: FakePlayer[] }+ ).__fakePlayers ||= [])+ players.push(this)+ queueMicrotask(() => {+ const events = options.events as {+ onReady?: (event: { target: FakePlayer }) => void+ }+ events.onReady?.({ target: this })+ })+ }- getCurrentTime() {- return this.current+ getCurrentTime() {+ return this.current+ }+ getDuration() {+ return this.duration+ }+ getPlaybackRate() {+ return this.rate+ }+ seekTo(seconds: number) {+ this.current = seconds+ }+ setPlaybackRate(rate: number) {+ this.rate = rate+ }+ playVideo() {}+ pauseVideo() {}+ destroy() {+ const players = (window as typeof window & { __fakePlayers?: FakePlayer[] }).__fakePlayers+ const index = players?.indexOf(this) ?? -1+ if (index >= 0) players?.splice(index, 1)+ this.element.remove()+ }}- getDuration() {- return this.duration++ ;(window as typeof window & { YT?: unknown }).YT = { Player: FakePlayer }+ })++ const turns: Record<string, unknown>[] = []+ await page.routeWebSocket('**/ws', socket => {+ socket.onMessage(raw => {+ const command = JSON.parse(String(raw))+ if (command.type !== 'start_turn') return+ turns.push(command)+ for (const [index, type] of ['session', 'content', 'done'].entries()) {+ socket.send(+ JSON.stringify({+ protocol_version: '2.0',+ type,+ session_id: 'watching-test',+ turn_id: 'turn-test',+ seq: index + 1,+ source: 'watching',+ stage: 'responding',+ timestamp: Date.now() / 1000,+ content:+ type === 'content'+ ? 'See [00:07](https://example.com/video?start=7) for the first concept.'+ : '',+ metadata: type === 'done' ? { status: 'completed' } : {},+ })+ )+ }+ })+ })+ await page.route('**/api/**', async route => {+ const request = route.request()+ const path = new URL(request.url()).pathname+ const json = (payload: unknown, status = 200) => route.fulfill({ status, json: payload })++ if (path === '/api/video-learning/invidious/account/status') return json({ connected: true })+ if (path === '/api/video-learning/invidious/browse/playlists')+ return json([+ {+ playlistId: 'IVPLlesson',+ title: 'My learning list',+ videoCount: 1,+ },+ ])+ if (path.startsWith('/api/video-learning/invidious/browse/'))+ return json({+ videos: [+ {+ videoId: 'dQw4w9WgXcQ',+ title: 'Browse lesson',+ author: 'Teacher',+ lengthSeconds: 120,+ },+ ],+ })+ if (path === '/api/auth/status') {+ return json({+ enabled: false,+ authenticated: true,+ role: 'admin',+ is_admin: true,+ })}- getPlaybackRate() {- return this.rate+ if (path === '/api/sessions/watching-test')+ return json({+ id: 'watching-test',+ session_id: 'watching-test',+ title: 'Video discussion',+ preferences: {+ capability: 'immersive_watching',+ workspace_mode: 'immersive_watching',+ timed_media_id: MATERIAL_ID,+ },+ messages: [+ {+ id: 1,+ role: 'user',+ content: 'Explain the video',+ events: [],+ attachments: [],+ },+ ],+ active_turns: [],+ })+ if (path === '/api/settings/ui') return json({ language: 'en' })+ if (path === '/api/capabilities/registered') {+ return json({+ capabilities: [+ { id: 'chat', kind: 'turn', available: true },+ { id: 'immersive_watching', kind: 'turn', available: true },+ ],+ })}- seekTo(seconds: number) {- this.current = seconds+ if (path === '/api/settings') return json({ catalog: {} })+ if (path === '/api/settings/llm-options') {+ return json({+ active: { profile_id: 'p', model_id: 'm' },+ options: [],+ })}- setPlaybackRate(rate: number) {- this.rate = rate+ if (path === '/api/dashboard/suggestions') return json({ suggestions: [], stale: false })+ if (path === '/api/video-learning/materials/resolve') {+ const body = request.postDataJSON() as {+ provider_override?: 'youtube'+ url?: string+ }+ secondMaterial = String(body.url || '').includes('9bZkp7q19f0')+ if (body.provider_override === 'youtube') nativeResolveCount += 1+ return json(material(body.provider_override || provider))}- playVideo() {}- pauseVideo() {}- destroy() {- const players = (window as typeof window & { __fakePlayers?: FakePlayer[] }).__fakePlayers- const index = players?.indexOf(this) ?? -1- if (index >= 0) players?.splice(index, 1)- this.element.remove()+ const materialId = secondMaterial ? SECOND_MATERIAL_ID : MATERIAL_ID+ if (path === `/api/video-learning/materials/${materialId}`) {+ if (provider === 'invidious' && invidiousOffline) {+ return json({ detail: 'Invidious is offline' }, 400)+ }+ return json(material(provider))}- }-- ;(window as typeof window & { YT?: unknown }).YT = { Player: FakePlayer }- })-- await page.route('**/api/**', async route => {- const request = route.request()- const path = new URL(request.url()).pathname- const json = (payload: unknown, status = 200) => route.fulfill({ status, json: payload })-- if (path === '/api/auth/status') {- return json({- enabled: false,- authenticated: true,- role: 'admin',- is_admin: true,- })- }- if (path === '/api/settings/ui') return json({ language: 'en' })- if (path === '/api/capabilities/registered') {- return json({- capabilities: [- { id: 'chat', kind: 'turn', available: true },- { id: 'immersive_watching', kind: 'turn', available: true },- ],- })- }- if (path === '/api/settings') return json({ catalog: {} })- if (path === '/api/settings/llm-options') {- return json({ active: { profile_id: 'p', model_id: 'm' }, options: [] })- }- if (path === '/api/dashboard/suggestions') return json({ suggestions: [], stale: false })- if (path === '/api/video-learning/materials/resolve') {- const body = request.postDataJSON() as {- provider_override?: 'youtube'- url?: string+ if (path === `/api/video-learning/materials/${materialId}/transcript/refresh`) {+ transcriptRefreshCount += 1+ transcriptReady = true+ return json(material('invidious'))}- secondMaterial = String(body.url || '').includes('9bZkp7q19f0')- if (body.provider_override === 'youtube') nativeResolveCount += 1- return json(material(body.provider_override || provider))- }- if (path === `/api/video-learning/materials/${MATERIAL_ID}`) {- materialRequestCount += 1- if (provider === 'invidious' && invidiousOffline) {- return json({ detail: 'Invidious is offline' }, 400)+ if (path.endsWith('/progress')) {+ const body = request.postDataJSON() as { time_seconds: number }+ savedPosition = body.time_seconds+ return json({ time_seconds: savedPosition, duration_seconds: 120 })}- return json(material(provider))- }- if (path === `/api/video-learning/materials/${MATERIAL_ID}/transcript/refresh`) {- transcriptRefreshCount += 1- transcriptReady = true- return json(material('invidious'))- }- if (path.endsWith('/progress')) {- const body = request.postDataJSON() as { time_seconds: number }- 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.md')) {- exportRequestCount += 1- if (exportShouldFail) return json({ detail: 'Notes export failed' }, 500)- return route.fulfill({- status: 200,- contentType: 'text/markdown',- body: '# Video notes: Timestamped lesson\n\n## 0:08\n\nFirst timestamped note\n',- })- }- if (path.endsWith('/notes') && request.method() === 'POST') {- const body = request.postDataJSON() as {- body: string- time_seconds: number+ if (path.endsWith('/notes') && request.method() === 'GET') {+ return json(notes)}- 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,+ if (path.endsWith('/notes.md')) {+ exportRequestCount += 1+ if (exportShouldFail) return json({ detail: 'Notes export failed' }, 500)+ return route.fulfill({+ status: 200,+ contentType: 'text/markdown',+ body: '# Video notes: Timestamped lesson\n\n## 0:08\n\nFirst timestamped note\n',+ })}- 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],+ 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: secondMaterial ? SECOND_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,}- return json(notes[index])+ notes.push(note)+ return json(note)}- if (request.method() === 'DELETE') {- notes.splice(index, 1)- return json({ status: 'deleted' })+ 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,- contentType: 'text/vtt',- body: 'WEBVTT\n',- })- }- if (path.includes('/stream/')) {- return route.fulfill({- status: 206,- contentType: 'video/mp4',- body: 'not-real-media',- })- }- return json({})- })+ if (path.endsWith('/subtitles.vtt')) {+ return route.fulfill({+ status: 200,+ contentType: 'text/vtt',+ body: 'WEBVTT\n',+ })+ }+ if (path.includes('/stream/')) {+ return route.fulfill({+ status: 206,+ contentType: 'video/mp4',+ body: 'not-real-media',+ })+ }+ return json({})+ })- await page.goto('/chat?capability=immersive_watching')- await page.getByPlaceholder('https://youtu.be/…').fill('https://youtu.be/dQw4w9WgXcQ?t=7')- await page.getByRole('button', { name: 'Open', exact: true }).click()+ await page.goto('/chat?capability=immersive_watching')+ await expect(page).toHaveURL(/\/watching$/)+ await expect(page.getByRole('button', { name: 'Disconnect Invidious' })).toBeVisible()+ await expect(page.getByRole('button', { name: /Browse lesson/ })).toBeVisible()+ await page.getByRole('button', { name: 'Playlists', exact: true }).click()+ await page.getByRole('button', { name: /My learning list/ }).click()+ await expect(page.getByRole('button', { name: /Browse lesson/ })).toBeVisible()+ const search = page.getByPlaceholder('Search videos or paste a video link')+ await search.fill('lesson')+ await search.press('Enter')+ await expect(page.getByRole('button', { name: /Browse lesson/ })).toBeVisible()+ await page.screenshot({+ path: test.info().outputPath(`watching-${mobile ? 'mobile' : 'desktop'}.png`),+ })+ await page.getByRole('button', { name: /Browse lesson/ }).click()- await expect(page.getByText('Timestamped lesson')).toBeVisible()- await expect(page.locator('iframe[title="Fake YouTube player"]')).toHaveAttribute(- 'src',- /youtube-nocookie\.com\/embed\/dQw4w9WgXcQ/- )- await expect(page.getByRole('button', { name: 'Set playback speed to 1x' })).toHaveAttribute(- 'aria-pressed',- 'true'- )- await page.getByRole('button', { name: 'Set playback speed to 1.5x' }).click()- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ rate: number }> }- ).__fakePlayers.at(-1)- return player?.rate || 0- })+ await expect(page.getByText('Timestamped lesson')).toBeVisible()+ await expect(page.locator('iframe[title="Fake YouTube player"]')).toHaveAttribute(+ 'src',+ /youtube-nocookie\.com\/embed\/dQw4w9WgXcQ/)- .toBe(1.5)-- await page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ current: number }> }- ).__fakePlayers.at(-1)- if (player) player.current = 8- })- await expect(page.getByText('The first grounded concept.').locator('..')).toHaveClass(/ring-1/)- const transcriptList = page.getByTestId('video-transcript-list')- const followButton = page.getByRole('button', { name: 'Follow playback' })- await expect(followButton).toHaveAttribute('aria-pressed', 'true')- const transcriptSearch = page.getByRole('searchbox', {- name: 'Search transcript',- })- await transcriptSearch.fill('grounded concept')- await expect(page.getByText('3 transcript matches')).toBeVisible()- await expect(page.getByText('Intermediate lesson detail 1.')).toBeHidden()- await expect(followButton).toBeDisabled()- await expect(followButton).toHaveAttribute('aria-pressed', 'false')- await transcriptSearch.press('Enter')- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & {- __fakePlayers: Array<{ current: number }>- }- ).__fakePlayers.at(-1)- return player?.current || 0- })+ await expect(page.getByRole('button', { name: 'Set playback speed to 1x' })).toHaveAttribute(+ 'aria-pressed',+ 'true')- .toBe(7)- await transcriptSearch.press('Enter')- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & {- __fakePlayers: Array<{ current: number }>- }- ).__fakePlayers.at(-1)- return player?.current || 0- })- )- .toBe(70)- await transcriptSearch.press('Shift+Enter')- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & {- __fakePlayers: Array<{ current: number }>- }- ).__fakePlayers.at(-1)- return player?.current || 0- })- )- .toBe(7)- await transcriptSearch.press('Escape')- await expect(transcriptSearch).toHaveValue('')- await expect(page.getByText('Intermediate lesson detail 1.')).toBeVisible()- await expect(followButton).toBeEnabled()- await expect(followButton).toHaveAttribute('aria-pressed', 'false')- await followButton.click()- await expect(followButton).toHaveAttribute('aria-pressed', 'true')- await page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ current: number }> }- ).__fakePlayers.at(-1)- if (player) player.current = 74- })- await expect(page.getByText('The second grounded concept.').locator('..')).toHaveClass(/ring-1/)- await expect- .poll(() => transcriptList.evaluate(element => element.scrollTop))- .toBeGreaterThan(100)-- await transcriptList.hover()- await page.mouse.wheel(0, 20)- await expect(followButton).toHaveAttribute('aria-pressed', 'false')- const pausedScrollTop = await transcriptList.evaluate(element => element.scrollTop)- await page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ current: number }> }- ).__fakePlayers.at(-1)- if (player) player.current = 112- })- await expect(page.getByText('The third grounded concept.').locator('..')).toHaveClass(/ring-1/)- await expect- .poll(() => transcriptList.evaluate(element => element.scrollTop))- .toBe(pausedScrollTop)- await followButton.click()- await expect(followButton).toHaveAttribute('aria-pressed', 'true')- await expect- .poll(() => transcriptList.evaluate(element => element.scrollTop))- .toBeGreaterThan(pausedScrollTop)+ await page.getByRole('button', { name: 'Set playback speed to 1.5x' }).click()+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ rate: number }> }+ ).__fakePlayers.at(-1)+ return player?.rate || 0+ })+ )+ .toBe(1.5)- await transcriptList.dispatchEvent('pointerdown', { pointerType: 'mouse' })- await expect(followButton).toHaveAttribute('aria-pressed', 'false')- await followButton.click()- await expect(followButton).toHaveAttribute('aria-pressed', 'true')+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ if (player) player.current = 8+ })+ await expect(page.getByText('The first grounded concept.').locator('..')).toHaveClass(/ring-1/)- await page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ current: number }> }- ).__fakePlayers.at(-1)- if (player) player.current = 8- })- await page.getByRole('tab', { name: 'Video notes' }).click()- await expect(page.getByText('No notes yet.')).toBeVisible()- await expect(page.getByRole('button', { name: 'Copy notes' })).toBeDisabled()- 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.getByRole('button', { name: 'Copy notes' }).click()- await expect(page.getByRole('button', { name: 'Notes copied' })).toBeVisible()- await expect.poll(() => exportRequestCount).toBe(1)- await expect(page.evaluate(() => navigator.clipboard.readText())).resolves.toContain(- 'First timestamped note'- )+ const transcriptList = page.getByTestId('video-transcript-list')+ const followButton = page.getByRole('button', { name: 'Follow playback' })+ await expect(followButton).toHaveAttribute('aria-pressed', 'true')+ const transcriptSearch = page.getByRole('searchbox', {+ name: 'Search transcript',+ })+ await transcriptSearch.fill('grounded concept')+ await expect(page.getByText('3 transcript matches')).toBeVisible()+ await expect(page.getByText('Intermediate lesson detail 1.')).toBeHidden()+ await expect(followButton).toBeDisabled()+ await expect(followButton).toHaveAttribute('aria-pressed', 'false')+ await transcriptSearch.press('Enter')+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ return player?.current || 0+ })+ )+ .toBe(7)+ await transcriptSearch.press('Enter')+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ return player?.current || 0+ })+ )+ .toBe(70)+ await transcriptSearch.press('Shift+Enter')+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ return player?.current || 0+ })+ )+ .toBe(7)+ await transcriptSearch.press('Escape')+ await expect(transcriptSearch).toHaveValue('')+ await expect(page.getByText('Intermediate lesson detail 1.')).toBeVisible()+ await expect(followButton).toBeEnabled()+ await expect(followButton).toHaveAttribute('aria-pressed', 'false')+ await followButton.click()+ await expect(followButton).toHaveAttribute('aria-pressed', 'true')+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ if (player) player.current = 74+ })+ await expect(page.getByText('The second grounded concept.').locator('..')).toHaveClass(/ring-1/)+ await expect+ .poll(() => transcriptList.evaluate(element => element.scrollTop))+ .toBeGreaterThan(100)- exportShouldFail = true- await page.getByRole('button', { name: 'Notes copied' }).click()- await expect(page.getByRole('alert').filter({ hasText: 'Notes export failed' })).toBeVisible()- exportShouldFail = false+ await transcriptList.hover()+ await page.mouse.wheel(0, 20)+ await expect(followButton).toHaveAttribute('aria-pressed', 'false')+ const pausedScrollTop = await transcriptList.evaluate(element => element.scrollTop)+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ if (player) player.current = 112+ })+ await expect(page.getByText('The third grounded concept.').locator('..')).toHaveClass(/ring-1/)+ await expect+ .poll(() => transcriptList.evaluate(element => element.scrollTop))+ .toBe(pausedScrollTop)+ await followButton.click()+ await expect(followButton).toHaveAttribute('aria-pressed', 'true')+ await expect+ .poll(() => transcriptList.evaluate(element => element.scrollTop))+ .toBeGreaterThan(pausedScrollTop)- await page.goto('/')- await page.waitForTimeout(100)- expect(materialRequestCount).toBe(0)- await page.goto('/chat?capability=immersive_watching')- await expect.poll(() => materialRequestCount).toBe(1)- await expect(page.getByText('Timestamped lesson')).toBeVisible()- await page.getByRole('tab', { name: 'Video notes' }).click()- await expect(page.getByText('First timestamped note')).toBeVisible()+ if (mobile) await page.getByRole('button', { name: 'Conversation', exact: true }).click()+ await page.locator('textarea').fill('Explain the video')+ await page.locator('textarea').press('Enter')+ await expect(page).toHaveURL(/\/watching\/watching-test$/)+ expect(turns[0]).toMatchObject({+ capability: 'immersive_watching',+ workspace_mode: 'immersive_watching',+ timed_media_id: MATERIAL_ID,+ })+ if (mobile) await page.getByRole('button', { name: 'Video', exact: true }).click()+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1)+ if (player) player.current = 8+ })+ await expect(page.getByText('The first grounded concept.').locator('..')).toHaveClass(/ring-1/)- 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- })+ 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.getByRole('button', { name: 'Copy notes' }).click()+ await expect(page.getByRole('button', { name: 'Notes copied' })).toBeVisible()+ await expect.poll(() => exportRequestCount).toBe(1)+ await expect(page.evaluate(() => navigator.clipboard.readText())).resolves.toContain(+ 'First timestamped note')- .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()+ exportShouldFail = true+ await page.getByRole('button', { name: 'Notes copied' }).click()+ await expect(page.getByRole('alert').filter({ hasText: 'Notes export failed' })).toBeVisible()+ exportShouldFail = false- 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.goto('/watching/watching-test')+ await page.reload()+ 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.getByRole('button', { name: 'Explain here' }).click()- await expect(page.locator('textarea')).toHaveValue(/\[0:08\] The first grounded concept\./)+ 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.evaluate(() => {- const link = document.createElement('a')- link.id = 'fake-assistant-timestamp'- link.href = '#dt-video-time-70'- link.textContent = '[01:10]'- document.body.appendChild(link)- })- await page.locator('#fake-assistant-timestamp').click()- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & {- __fakePlayers: Array<{ current: number }>- }- ).__fakePlayers.at(-1)- return player?.current || 0- })- )- .toBe(70)+ 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: 'Close video learning' }).evaluate(button => {- document.dispatchEvent(new Event('visibilitychange'))- button.setAttribute('data-persisted', 'true')- })- await expect.poll(() => savedPosition).toBeGreaterThanOrEqual(70)- await page.reload()- await expect(page.getByText('Timestamped lesson')).toBeVisible()- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & {- __fakePlayers: Array<{ current: number }>- }- ).__fakePlayers.at(-1)- return player?.current || 0- })- )- .toBeGreaterThanOrEqual(70)- await page.getByRole('button', { name: 'Set playback speed to 1.5x' }).click()+ await page.getByRole('button', { name: 'Delete note at 0:08' }).click()+ await page.getByRole('alertdialog').getByRole('button', { name: 'Delete', exact: true }).click()+ await expect(page.getByText('No notes yet.')).toBeVisible()+ await page.getByRole('tab', { name: 'Transcript' }).click()- provider = 'invidious'- transcriptReady = false- await page.getByRole('button', { name: 'Refresh provider' }).click()- await expect(page.locator('video')).toBeVisible()- await expect(page.getByText('Invidious', { exact: true })).toBeVisible()- await expect(page.getByRole('button', { name: 'Retry captions' })).toBeVisible()- const player = page.locator('video')- await player.evaluate(video => video.setAttribute('data-transcript-retry-probe', 'before'))- await page.getByRole('button', { name: 'Retry captions' }).click()- await expect.poll(() => transcriptRefreshCount).toBe(1)- await expect(page.getByRole('button', { name: 'Explain here' })).toBeVisible()- await expect(player).toHaveAttribute('data-transcript-retry-probe', 'before')- await expect- .poll(() => player.evaluate(video => (video as HTMLVideoElement).playbackRate))- .toBe(1.5)+ await page.getByRole('button', { name: 'Explain here' }).click()+ await expect(page.locator('textarea')).toHaveValue(/\[0:08\] The first grounded concept\./)- const beforeFailure = nativeResolveCount- invidiousOffline = true- await page.getByRole('button', { name: 'Refresh provider' }).click()- await expect(page.getByRole('alert').filter({ hasText: 'Invidious is offline' })).toBeVisible()- expect(nativeResolveCount).toBe(beforeFailure)+ if (mobile) await page.getByRole('button', { name: 'Video', exact: true }).click()+ await page.evaluate(() => {+ const link = document.createElement('a')+ link.id = 'fake-assistant-timestamp'+ link.href = '#dt-video-time-70'+ link.textContent = '[01:10]'+ document.body.appendChild(link)+ })+ await page.locator('#fake-assistant-timestamp').click()+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & {+ __fakePlayers: Array<{ current: number }>+ }+ ).__fakePlayers.at(-1)+ return player?.current || 0+ })+ )+ .toBe(70)- await page.getByRole('button', { name: 'Use native YouTube' }).click()- await expect(page.locator('iframe[title="Fake YouTube player"]')).toBeVisible()- expect(nativeResolveCount).toBe(beforeFailure + 1)- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ rate: number }> }- ).__fakePlayers.at(-1)- return player?.rate || 0- })- )- .toBe(1.5)+ await page.getByRole('button', { name: 'Close video learning' }).evaluate(button => {+ document.dispatchEvent(new Event('visibilitychange'))+ button.setAttribute('data-persisted', 'true')+ })+ await expect.poll(() => savedPosition).toBeGreaterThanOrEqual(70)+ await page.reload()+ await expect(page.getByText('Timestamped lesson')).toBeVisible()+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & {+ __fakePlayers: Array<{ current: number }>+ }+ ).__fakePlayers.at(-1)+ return player?.current || 0+ })+ )+ .toBeGreaterThanOrEqual(70)- provider = 'youtube'- invidiousOffline = false- await page.getByRole('button', { name: 'Close video learning' }).click()- await page.goto('/chat?capability=immersive_watching')- await page.getByPlaceholder('https://youtu.be/…').fill('https://youtu.be/9bZkp7q19f0')- await page.getByRole('button', { name: 'Open', exact: true }).click()- await expect(page.getByText('Replacement lesson')).toBeVisible()- await expect(page.getByRole('button', { name: 'Set playback speed to 1x' })).toHaveAttribute(- 'aria-pressed',- 'true'- )- await expect- .poll(() =>- page.evaluate(() => {- const player = (- window as typeof window & { __fakePlayers: Array<{ rate: number }> }- ).__fakePlayers.at(-1)- return player?.rate || 0- })+ await page+ .getByRole('button', { name: 'Set playback speed to 1.5x' })+ .click()++ provider = 'invidious'+ transcriptReady = false+ await page.getByRole('button', { name: 'Refresh provider' }).click()+ await expect(page.locator('video')).toBeVisible()+ await expect(page.getByText('Invidious', { exact: true })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Retry captions' })).toBeVisible()+ const player = page.locator('video')+ await player.evaluate(video => video.setAttribute('data-transcript-retry-probe', 'before'))+ await page.getByRole('button', { name: 'Retry captions' }).click()+ await expect.poll(() => transcriptRefreshCount).toBe(1)+ await expect(page.getByRole('button', { name: 'Explain here' })).toBeVisible()+ await expect(player).toHaveAttribute('data-transcript-retry-probe', 'before')+ await expect+ .poll(() => player.evaluate(video => (video as HTMLVideoElement).playbackRate))+ .toBe(1.5)++ const beforeFailure = nativeResolveCount+ invidiousOffline = true+ await page.getByRole('button', { name: 'Refresh provider' }).click()+ await expect(page.getByRole('alert').filter({ hasText: 'Invidious is offline' })).toBeVisible()+ expect(nativeResolveCount).toBe(beforeFailure)++ await page.getByRole('button', { name: 'Use native YouTube' }).click()+ await expect(page.locator('iframe[title="Fake YouTube player"]')).toBeVisible()+ expect(nativeResolveCount).toBe(beforeFailure + 1)+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ rate: number }> }+ ).__fakePlayers.at(-1)+ return player?.rate || 0+ })+ )+ .toBe(1.5)++ provider = 'youtube'+ invidiousOffline = false+ secondMaterial = true+ await page.getByRole('button', { name: 'Close video learning' }).click()+ await page.goto('/watching?video=https%3A%2F%2Fyoutu.be%2F9bZkp7q19f0')+ await expect(page.getByText('Replacement lesson')).toBeVisible()+ await expect(page.getByRole('button', { name: 'Set playback speed to 1x' })).toHaveAttribute(+ 'aria-pressed',+ 'true')- .toBe(1)-})+ await expect+ .poll(() =>+ page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ rate: number }> }+ ).__fakePlayers.at(-1)+ return player?.rate || 0+ })+ )+ .toBe(1)+ })+}diff --git a/web/tests/invidious-account-feedback.spec.tsx b/web/tests/invidious-account-feedback.spec.tsxnew file mode 100644index 000000000..d18132c5d--- /dev/null+++ b/web/tests/invidious-account-feedback.spec.tsx@@ -0,0 +1,44 @@+import React from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { WatchingSurface } from "@/components/watching/WatchingWorkspace";++const route = vi.hoisted(() => ({ result: "authorization_expired" }));+vi.mock("next/navigation", () => ({+ useSearchParams: () => new URLSearchParams({ account: route.result }),+ useParams: () => ({}),+}));+const t = (key: string) => key;+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t }) }));+vi.mock("@/context/WatchingContext", () => ({+ useWatching: () => ({ material: null }),+}));+vi.mock("@/components/watching/WatchingBrowser", () => ({+ WatchingBrowser: () => <div>Browser</div>,+}));+vi.mock("@/components/watching/WatchingPane", () => ({+ WatchingPane: () => null,+ WATCHING_ASK_EVENT: "dt:watching-ask",+}));++describe("Invidious callback feedback", () => {+ it("shows actionable failure and lets the learner dismiss it", () => {+ route.result = "authorization_expired";+ render(<WatchingSurface />);+ expect(screen.getByRole("alert")).toHaveTextContent(+ "Click Connect Invidious to start again",+ );+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(screen.queryByRole("alert")).toBeNull();+ });+ it("announces success and removes callback parameters", () => {+ route.result = "connected";+ const history = vi.spyOn(window.history, "replaceState");+ render(<WatchingSurface />);+ expect(screen.getByRole("status")).toHaveTextContent(+ "Invidious account connected",+ );+ expect(history).toHaveBeenCalledWith(null, "", "/watching");+ history.mockRestore();+ });+});diff --git a/web/tests/invidious-account-result.test.ts b/web/tests/invidious-account-result.test.tsnew file mode 100644index 000000000..d15041f1c--- /dev/null+++ b/web/tests/invidious-account-result.test.ts@@ -0,0 +1,20 @@+import assert from "node:assert/strict";+import test from "node:test";+import { invidiousAccountResultMessage } from "../lib/invidious-account-result";++test("authorization failures give specific recovery steps without reflecting input", () => {+ assert.match(+ invidiousAccountResultMessage("authorization_expired")!,+ /start again/,+ );+ assert.match(+ invidiousAccountResultMessage("authorization_login_required")!,+ /DeepTutor login/,+ );+ assert.match(+ invidiousAccountResultMessage("authorization_unavailable")!,+ /instance/,+ );+ assert.match(invidiousAccountResultMessage("connected")!, /connected/);+ assert.equal(invidiousAccountResultMessage("token=secret"), null);+});diff --git a/web/tests/watching-browser.spec.tsx b/web/tests/watching-browser.spec.tsxnew file mode 100644index 000000000..383e2c877--- /dev/null+++ b/web/tests/watching-browser.spec.tsx@@ -0,0 +1,91 @@+import React from "react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { WatchingBrowser } from "@/components/watching/WatchingBrowser";++const mock = vi.hoisted(() => ({+ account: vi.fn(),+ browse: vi.fn(),+ push: vi.fn(),+}));+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mock.push }) }));+const translate = (key: string) => key;+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: translate }) }));+vi.mock("@/hooks/useAuthStatus", () => ({+ useAuthStatus: () => ({+ loading: false,+ statusAvailable: true,+ userId: "owner-a",+ }),+}));+vi.mock("@/lib/video-learning-api", () => ({+ invidiousAccount: mock.account,+ browseInvidious: mock.browse,+}));+const video = {+ videoId: "aircAruvnKk",+ title: "Neural networks",+ author: "Teacher",+ lengthSeconds: 120,+};++beforeEach(() => {+ vi.clearAllMocks();+ sessionStorage.clear();+ mock.account.mockResolvedValue({ connected: true });+ mock.browse.mockResolvedValue({ videos: [video] });+});+describe("Watching account browser", () => {+ it("opens a selected subscription video as a new Watching route", async () => {+ render(<WatchingBrowser canDismiss onDismiss={vi.fn()} />);+ fireEvent.click(+ await screen.findByRole("button", { name: /Neural networks/ }),+ );+ expect(mock.push).toHaveBeenCalledWith(+ `/watching?video=${encodeURIComponent("https://www.youtube.com/watch?v=aircAruvnKk")}`,+ );+ expect(mock.browse.mock.calls[0][0]).toBe("feed");+ });+ it("allows anonymous search and guides account-only browsing", async () => {+ mock.account.mockResolvedValue({ connected: false });+ render(<WatchingBrowser canDismiss={false} onDismiss={vi.fn()} />);+ await waitFor(() => expect(mock.account).toHaveBeenCalled());+ fireEvent.click(screen.getByRole("button", { name: "Subscription feed" }));+ await screen.findByText(+ "Connect your Invidious account to see subscriptions and playlists.",+ );+ expect(mock.browse).not.toHaveBeenCalled();+ const input = screen.getByRole("textbox");+ fireEvent.change(input, { target: { value: "neural" } });+ fireEvent.submit(input.closest("form")!);+ await screen.findByText("Neural networks");+ expect(mock.browse.mock.calls[0].slice(0, 3)).toEqual([+ "search",+ "neural",+ 1,+ ]);+ });+ it("clears private rows when disconnected", async () => {+ render(<WatchingBrowser canDismiss={false} onDismiss={vi.fn()} />);+ await screen.findByText("Neural networks");+ mock.account.mockResolvedValue({ connected: false });+ fireEvent.click(+ screen.getByRole("button", { name: "Disconnect Invidious" }),+ );+ await waitFor(() =>+ expect(screen.queryByText("Neural networks")).toBeNull(),+ );+ });+ it("shows an actionable instance failure", async () => {+ mock.browse.mockRejectedValue(+ new Error(+ "Invidious could not load videos. Please retry or check the instance.",+ ),+ );+ render(<WatchingBrowser canDismiss={false} onDismiss={vi.fn()} />);+ await screen.findByRole("alert");+ mock.browse.mockResolvedValue({ videos: [video] });+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await screen.findByText("Neural networks");+ });+});diff --git a/web/tests/watching-citations.test.ts b/web/tests/watching-citations.test.tsindex 782ffc991..e88d2b196 100644--- a/web/tests/watching-citations.test.ts+++ b/web/tests/watching-citations.test.ts@@ -13,10 +13,10 @@ test("linkifies minute and hour timestamp citations", () => {);});-test("does not rewrite code or existing links", () => {+test("preserves code and normalizes existing timestamp links to the current video", () => {assert.equal(linkifyVideoTimestamps("`[01:23]` [01:23](https://example.test)"),- "`[01:23]` [01:23](https://example.test)",+ "`[01:23]` [01:23](#dt-video-time-83)",);});@@ -25,3 +25,11 @@ test("parses only valid video seek anchors", () => {assert.equal(videoTimeFromHref("https://example.test"), null);assert.equal(videoTimeFromHref("#dt-video-time-nope"), null);});++test("normalization is idempotent and preserves non-timestamp links", () => {+ const text =+ "[00:28](https://example.com/video?start=28) [source](https://example.com)";+ const normalized = "[00:28](#dt-video-time-28) [source](https://example.com)";+ assert.equal(linkifyVideoTimestamps(text), normalized);+ assert.equal(linkifyVideoTimestamps(normalized), normalized);+});diff --git a/web/tests/watching-session.test.ts b/web/tests/watching-session.test.tsnew file mode 100644index 000000000..dc957d071--- /dev/null+++ b/web/tests/watching-session.test.ts@@ -0,0 +1,31 @@+import assert from "node:assert/strict";+import test from "node:test";+import { sessionRoute } from "../lib/mastery-session";+import { normalizeWorkspaceMode } from "../lib/workspace-mode";+import { capabilityForPath } from "../lib/capability-routes";+import type { SessionSummary } from "../lib/session-api";++test("Watching links retain their owning workspace, including legacy sessions", () => {+ for (const preferences of [+ { workspace_mode: "immersive_watching" as const },+ { capability: "immersive_watching" },+ ]) {+ assert.equal(+ sessionRoute({ session_id: "lesson 1", preferences } as SessionSummary),+ "/watching/lesson%201",+ );+ }+ assert.equal(+ sessionRoute({+ session_id: "chat",+ preferences: { timed_media_id: "stale" },+ } as SessionSummary),+ "/chat/chat",+ );+ assert.equal(+ normalizeWorkspaceMode("", "immersive_watching"),+ "immersive_watching",+ );+ assert.equal(capabilityForPath("/watching/lesson"), "llm");+ assert.equal(capabilityForPath("/watching-other"), null);+});diff --git a/web/tests/watching-workspace.spec.tsx b/web/tests/watching-workspace.spec.tsxnew file mode 100644index 000000000..7f89a9b69--- /dev/null+++ b/web/tests/watching-workspace.spec.tsx@@ -0,0 +1,122 @@+import React, { useEffect } from "react";+import { act, render, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { WatchingProvider, useWatching } from "@/context/WatchingContext";+import { WatchingSessionBridge } from "@/components/watching/WatchingWorkspace";+import { watchingTurnFields } from "@/lib/watching-turn-state";+import type { TimedMediaMaterial } from "@/lib/video-learning-api";++const api = vi.hoisted(() => ({ get: vi.fn(), resolve: vi.fn() }));+vi.mock("@/lib/video-learning-api", () => ({+ getVideoMaterial: api.get,+ resolveVideo: api.resolve,+ refreshInvidiousTranscript: vi.fn(),+}));+const translate = (key: string) => key;+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: translate }) }));+vi.mock("@/components/watching/WatchingPane", () => ({+ WatchingPane: () => null,+ WATCHING_ASK_EVENT: "dt:watching-ask",+}));++function material(id: string): TimedMediaMaterial {+ return {+ material_id: id,+ source: { url: id },+ playback: { start_seconds: 37 },+ learning: { last_position: 37 },+ } as TimedMediaMaterial;+}+let context: ReturnType<typeof useWatching>;+function Probe() {+ const current = useWatching();+ useEffect(() => {+ context = current;+ }, [current]);+ return <span>{current.material?.material_id || "empty"}</span>;+}+function App({ scope, id }: { scope: string; id: string | null }) {+ return (+ <WatchingProvider>+ <WatchingSessionBridge+ sessionKey={scope}+ materialId={id}+ onMaterial={vi.fn()}+ />+ <Probe />+ </WatchingProvider>+ );+}++describe("Watching conversation restoration", () => {+ it("ignores browser-global video history and does not fetch on ordinary provider mount", () => {+ api.get.mockClear();+ localStorage.setItem("dt:video-learning:last-material", "other-owner");+ render(+ <WatchingProvider>+ <Probe />+ </WatchingProvider>,+ );+ expect(api.get).not.toHaveBeenCalled();+ expect(screen.getByText("empty")).toBeInTheDocument();+ });++ it("drops a late previous-session result and restores the new video's saved position", async () => {+ let finishA!: (value: TimedMediaMaterial) => void;+ api.get.mockImplementation((id: string) =>+ id === "a"+ ? new Promise((resolve) => {+ finishA = resolve;+ })+ : Promise.resolve(material(id)),+ );+ const view = render(<App scope="session-a" id="a" />);+ view.rerender(<App scope="session-b" id="b" />);+ await screen.findByText("b");+ await act(async () => {+ finishA(material("a"));+ });+ expect(screen.getByText("b")).toBeInTheDocument();+ expect(watchingTurnFields("immersive_watching")).toEqual({+ timed_media_id: "b",+ timed_media_viewport: { time_seconds: 37 },+ });+ expect(watchingTurnFields("chat")).toEqual({});+ view.unmount();+ expect(watchingTurnFields("immersive_watching")).toEqual({});+ });++ it("clears the previous video on unavailable or unauthorized materials", async () => {+ api.get+ .mockResolvedValueOnce(material("a"))+ .mockRejectedValueOnce(new Error("Not found"));+ const view = render(<App scope="session-a" id="a" />);+ await screen.findByText("a");+ view.rerender(<App scope="session-b" id="private-b" />);+ await waitFor(() => expect(context.error).toBe("Not found"));+ expect(screen.getByText("empty")).toBeInTheDocument();+ expect(watchingTurnFields("immersive_watching")).toEqual({});+ });++ it("invalidates an open request when leaving the workspace", async () => {+ let finish!: (value: TimedMediaMaterial) => void;+ api.resolve.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const view = render(<App scope="draft" id={null} />);+ await act(async () => {});+ let opening!: Promise<void>;+ act(() => {+ opening = context.openUrl("video");+ });+ view.unmount();+ await act(async () => {+ finish(material("late"));+ await opening;+ });+ expect(watchingTurnFields("immersive_watching")).toEqual({});+ });+});