DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add app updater and unify workspace chat flows
Bingxi Zhao (Frank)f694f204a844
diff --git a/deeptutor/api/routers/system.py b/deeptutor/api/routers/system.pyindex e92290c89..2223173b1 100644--- a/deeptutor/api/routers/system.py+++ b/deeptutor/api/routers/system.py@@ -5,14 +5,31 @@ Manages system status checks and model connection testsimport asynciofrom datetime import datetime+import jsonimport time+from typing import Any, Literal-from fastapi import APIRouter+from fastapi import APIRouter, Depends, HTTPException, statusfrom pydantic import BaseModel+from deeptutor.api.routers.auth import require_adminfrom deeptutor.multi_user.context import get_current_userfrom deeptutor.runtime import memory_probe+from deeptutor.services.app_update import (+ Installation,+ UpdateInProgressError,+ UpdateJob,+ UpdateJobStore,+ UpdateRequestError,+ VersionCheckError,+ VersionCheckResult,+ detect_installation,+ get_version_check_service,+ launcher_available,+ update_store_root,+)from deeptutor.services.config import (+ get_runtime_settings_service,resolve_search_runtime_config,supported_search_providers_hint,)@@ -32,6 +49,203 @@ class TestResponse(BaseModel):error: str | None = None+class UpdateSettingsRequest(BaseModel):+ enabled: bool+++class ManagedUpdateRequest(BaseModel):+ confirmation: Literal["update-and-restart"]+++def get_update_job_store() -> UpdateJobStore:+ return UpdateJobStore(update_store_root())+++def get_update_installation() -> Installation:+ return detect_installation()+++def get_turn_activity():+ from deeptutor.services.session import get_turn_runtime_manager++ return get_turn_runtime_manager()+++def _job_payload(job: UpdateJob | None) -> dict[str, Any] | None:+ if job is None:+ return None+ return {+ "id": job.id,+ "status": job.status,+ "current_version": job.current_version,+ "target_version": job.target_version,+ "created_at": job.created_at,+ "started_at": job.started_at,+ "finished_at": job.finished_at,+ "error": job.error,+ "restart_count": job.restart_count,+ }+++def _stored_job(store: UpdateJobStore | None = None) -> UpdateJob | None:+ try:+ return (store or get_update_job_store()).load()+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ return None+++def _update_payload(+ *,+ result: VersionCheckResult | None,+ installation: Installation,+ check_enabled: bool,+ check_error: str = "",+ store: UpdateJobStore | None = None,+) -> dict[str, Any]:+ release = result.release if result is not None else None+ return {+ "current_version": result.current_version if result else installation.current_version,+ "check_enabled": check_enabled,+ "checked_at": result.checked_at if result else "",+ "cached": result.cached if result else False,+ "check_error": check_error,+ "update_available": result.update_available if result else False,+ "release": (+ {+ "version": release.version,+ "name": release.name,+ "published_at": release.published_at,+ "url": release.url,+ "excerpt": release.excerpt,+ "migration_warning": release.migration_warning,+ }+ if release+ else None+ ),+ "installation": {+ "mode": installation.mode,+ "automatic_update": installation.automatic_update,+ "command": installation.command,+ "reason": installation.reason,+ },+ "launcher_managed": launcher_available(),+ "is_admin": get_current_user().is_admin,+ "job": _job_payload(_stored_job(store)),+ }+++async def _checked_update_payload(*, force: bool = False) -> dict[str, Any]:+ settings = get_runtime_settings_service().load_system()+ enabled = bool(settings["version_check_enabled"])+ installation = get_update_installation()+ service = get_version_check_service()+ if not enabled:+ return _update_payload(+ result=service.cached(),+ installation=installation,+ check_enabled=False,+ )+ try:+ result = await service.check(force=force)+ except VersionCheckError as exc:+ if force:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=str(exc),+ ) from None+ return _update_payload(+ result=service.cached(),+ installation=installation,+ check_enabled=True,+ check_error=str(exc),+ )+ return _update_payload(+ result=result,+ installation=installation,+ check_enabled=True,+ )++[email protected]("/update")+async def get_update_status() -> dict[str, Any]:+ """Return About-page version state, checking at most once per 24 hours."""++ return await _checked_update_payload()++[email protected]("/update/check", dependencies=[Depends(require_admin)])+async def check_for_update() -> dict[str, Any]:+ """Perform an explicit administrator-requested release check."""++ return await _checked_update_payload(force=True)++[email protected]("/update/settings", dependencies=[Depends(require_admin)])+async def update_check_settings(payload: UpdateSettingsRequest) -> dict[str, Any]:+ service = get_runtime_settings_service()+ current = service.load_system(include_process_overrides=False)+ service.save_system({**current, "version_check_enabled": payload.enabled})+ return await _checked_update_payload()++[email protected]("/update/job")+async def get_update_job() -> dict[str, Any] | None:+ return _job_payload(_stored_job())+++ "/update",+ status_code=status.HTTP_202_ACCEPTED,+ dependencies=[Depends(require_admin)],+)+async def request_managed_update(_request: ManagedUpdateRequest) -> dict[str, Any]:+ """Reserve one safe update for the supervising launcher to apply."""++ settings = get_runtime_settings_service().load_system()+ if not settings["version_check_enabled"]:+ raise HTTPException(status_code=409, detail="Version checks are disabled")+ if not launcher_available():+ raise HTTPException(+ status_code=409,+ detail="Web updates require DeepTutor to be running under `deeptutor start`.",+ )+ installation = get_update_installation()+ if installation.mode != "pypi" or not installation.automatic_update:+ raise HTTPException(+ status_code=409,+ detail=installation.reason or "This installation cannot update itself safely.",+ )+ try:+ result = await get_version_check_service().check()+ except VersionCheckError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from None+ if not result.update_available:+ raise HTTPException(status_code=409, detail="No newer DeepTutor release is available")+ # Re-check installation evidence immediately before reserving the job. A+ # deployment changing underneath this request fails closed.+ confirmed = get_update_installation()+ if confirmed.mode != "pypi" or not confirmed.automatic_update:+ raise HTTPException(+ status_code=409, detail="The installation changed during the update check"+ )+ store = get_update_job_store()+ try:+ job = await get_turn_activity().reserve_managed_update(+ lambda: store.create(+ current_version=result.current_version,+ target_version=result.release.version,+ )+ )+ except (UpdateInProgressError, UpdateRequestError, ValueError) as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from None+ if job is None:+ raise HTTPException(+ status_code=409,+ detail="Finish the active conversation before updating DeepTutor.",+ )+ return _job_payload(job) or {}++@router.get("/runtime-topology")async def get_runtime_topology():"""diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.pyindex e28d6f61e..d432948da 100644--- a/deeptutor/runtime/launcher.py+++ b/deeptutor/runtime/launcher.py@@ -28,6 +28,7 @@ from deeptutor.runtime.home import (validate_runtime_home,)from deeptutor.runtime.memory_probe import SUPERVISOR_PID_ENV+from deeptutor.services.app_update import LAUNCHER_PID_ENVBACKEND_READY_TIMEOUT = 60FRONTEND_READY_TIMEOUT = 120@@ -932,6 +933,63 @@ def _install_signal_handlers(request_shutdown: Callable[[str | None], None]) ->continue+def _handoff_pending_update(+ runtime_home: Path,+ *,+ restart_argv: list[str],+ parent_pid: int | None = None,+ worker_launcher: Callable[[Path], None] | None = None,+) -> bool:+ """Hand a pending Web update to a detached worker before shutdown."""++ from deeptutor.services.app_update import (+ UpdateJobStore,+ launch_update_worker,+ update_store_root,+ )++ store = UpdateJobStore(update_store_root(runtime_home))+ try:+ job = store.load()+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ return False+ if job.status != "pending":+ return False+ try:+ store.prepare_handoff(+ job.id,+ home=runtime_home,+ restart_argv=restart_argv,+ )+ if worker_launcher is not None:+ worker_launcher(store.root)+ else:+ launch_update_worker(store.root, parent_pid=parent_pid or os.getpid())+ except Exception as exc:+ try:+ store.mark_failed(job.id, f"Launcher handoff failed: {exc}")+ except Exception:+ pass+ return False+ return True+++def _complete_restarted_update(runtime_home: Path) -> bool:+ """Mark an update successful only after both managed servers are ready."""++ from deeptutor.services.app_update import UpdateJobStore, update_store_root++ store = UpdateJobStore(update_store_root(runtime_home))+ try:+ job = store.load()+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ return False+ if job.status != "restarting" or job.restart_home != str(runtime_home.resolve()):+ return False+ store.mark_succeeded(job.id)+ return True++def start(home: str | Path | None = None, *, dev: bool = False) -> None:_relax_console_encoding()runtime_home = get_runtime_home(home)@@ -940,6 +998,9 @@ def start(home: str | Path | None = None, *, dev: bool = False) -> None:except ValueError as exc:raise SystemExit(str(exc)) from excruntime_home.mkdir(parents=True, exist_ok=True)+ restart_argv = ["start", "--home", str(runtime_home.resolve())]+ if dev:+ restart_argv.append("--dev")os.environ[DEEPTUTOR_HOME_ENV] = str(runtime_home)_reset_runtime_singletons()@@ -1053,6 +1114,7 @@ def start(home: str | Path | None = None, *, dev: bool = False) -> None:# the tree that is "DeepTutor". Without it the probe can only measure the# backend itself.common_env[SUPERVISOR_PID_ENV] = str(os.getpid())+ common_env[LAUNCHER_PID_ENV] = str(os.getpid())_apply_single_user_allocator_env(common_env)if frontend.kind == "source-production":common_env["DEEPTUTOR_NEXT_DIST_DIR"] = SOURCE_PRODUCTION_DIST_DIR@@ -1147,9 +1209,13 @@ def start(home: str | Path | None = None, *, dev: bool = False) -> None:timeout=FRONTEND_READY_TIMEOUT,should_stop=lambda: shutdown_requested,)+ _complete_restarted_update(runtime_home)_log(_t("start.open_in_browser", url=frontend_url))while not shutdown_requested:+ if _handoff_pending_update(runtime_home, restart_argv=restart_argv):+ shutdown_requested = True+ breakfor proc in processes:if proc.process.poll() is not None:_log(_t("start.exited", name=proc.name, code=proc.process.returncode))diff --git a/deeptutor/runtime/update_worker.py b/deeptutor/runtime/update_worker.pynew file mode 100644index 000000000..d5383a9c4--- /dev/null+++ b/deeptutor/runtime/update_worker.py@@ -0,0 +1,161 @@+"""Detached executor for a launcher-managed DeepTutor update."""++from __future__ import annotations++import argparse+import os+from pathlib import Path+import subprocess # nosec B404 - commands are fixed and validated below+import sys+import time+from typing import Callable++from deeptutor.services.app_update import UpdateJob, UpdateJobStore+++def build_update_command(target_version: str) -> list[str]:+ """Return the only package mutation the worker is allowed to execute."""++ # Round-trip through the job validator instead of accepting arbitrary text.+ validated = UpdateJob.from_dict(+ {+ "schema_version": 1,+ "id": "validation",+ "status": "pending",+ "current_version": target_version,+ "target_version": target_version,+ "created_at": "validation",+ }+ ).target_version+ return [+ sys.executable,+ "-m",+ "pip",+ "install",+ "--no-input",+ "--disable-pip-version-check",+ "--upgrade",+ f"deeptutor=={validated}",+ ]+++def build_restart_command(job: UpdateJob) -> tuple[list[str], Path]:+ if not job.restart_home or not job.restart_argv:+ raise ValueError("Update job is missing restart information")+ home = Path(job.restart_home).resolve()+ # UpdateJob.from_dict already restricts restart_argv to+ # `start --home <same-home> [--dev]`; preserve that exact trusted vector.+ return [sys.executable, "-m", "deeptutor_cli.main", *job.restart_argv], home+++def _pid_is_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except PermissionError:+ return True+ except OSError:+ return False+ return True+++def wait_for_process_exit(pid: int, *, timeout: float = 60.0) -> None:+ if pid <= 0 or pid == os.getpid():+ raise ValueError("Invalid launcher process")+ deadline = time.monotonic() + timeout+ while _pid_is_alive(pid):+ if time.monotonic() >= deadline:+ raise TimeoutError("Launcher did not exit before the update timeout")+ time.sleep(0.05)+++def _run_logged(command: list[str], *, cwd: Path, log_path: Path) -> int:+ with log_path.open("a", encoding="utf-8") as log:+ completed = subprocess.run( # nosec B603+ command,+ cwd=cwd,+ stdin=subprocess.DEVNULL,+ stdout=log,+ stderr=subprocess.STDOUT,+ check=False,+ shell=False,+ env={**os.environ, "PIP_DISABLE_PIP_VERSION_CHECK": "1"},+ )+ return completed.returncode+++def _launch_restart(job: UpdateJob, *, log_path: Path) -> None:+ command, home = build_restart_command(job)+ kwargs: dict[str, object] = {+ "cwd": str(home),+ "stdin": subprocess.DEVNULL,+ "stderr": subprocess.STDOUT,+ "close_fds": True,+ "shell": False,+ }+ if os.name == "nt":+ kwargs["creationflags"] = (+ subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]+ | subprocess.DETACHED_PROCESS # type: ignore[attr-defined]+ )+ else:+ kwargs["start_new_session"] = True+ with log_path.open("a", encoding="utf-8") as log:+ subprocess.Popen(command, stdout=log, **kwargs) # type: ignore[arg-type] # nosec B603+++def run_update_worker(+ *,+ store_root: Path,+ parent_pid: int,+ wait_for_parent: Callable[[int], None] = wait_for_process_exit,+ command_runner: Callable[[list[str], Path, Path], int] | None = None,+ restart_launcher: Callable[[UpdateJob, Path], None] | None = None,+) -> int:+ """Install the target, then restore the application on either outcome."""++ store = UpdateJobStore(store_root)+ try:+ job = store.load()+ if job.status != "handoff":+ raise RuntimeError("Update job is not awaiting the worker")+ wait_for_parent(parent_pid)+ job = store.mark_running(job.id)+ runner = command_runner or (+ lambda command, cwd, log_path: _run_logged(command, cwd=cwd, log_path=log_path)+ )+ exit_code = runner(+ build_update_command(job.target_version), Path(job.restart_home or "."), store.log_path+ )+ if exit_code != 0:+ raise RuntimeError(f"pip exited with status {exit_code}")+ job = store.mark_restarting(job.id)+ (restart_launcher or (lambda value, path: _launch_restart(value, log_path=path)))(+ job,+ store.log_path,+ )+ return 0+ except Exception as exc:+ try:+ current = store.load()+ if current.status not in {"succeeded", "failed"}:+ current = store.mark_failed(current.id, str(exc) or type(exc).__name__)+ if current.restart_home and current.restart_argv:+ (restart_launcher or (lambda value, path: _launch_restart(value, log_path=path)))(+ current,+ store.log_path,+ )+ except Exception:+ pass+ return 1+++def main() -> None:+ parser = argparse.ArgumentParser(description="Apply a managed DeepTutor update")+ parser.add_argument("--store-root", type=Path, required=True)+ parser.add_argument("--parent-pid", type=int, required=True)+ args = parser.parse_args()+ raise SystemExit(run_update_worker(store_root=args.store_root, parent_pid=args.parent_pid))+++if __name__ == "__main__":+ main()diff --git a/deeptutor/services/app_update.py b/deeptutor/services/app_update.pynew file mode 100644index 000000000..f81f4d487--- /dev/null+++ b/deeptutor/services/app_update.py@@ -0,0 +1,559 @@+"""Version checks and durable, launcher-managed PyPI updates."""++from __future__ import annotations++import asyncio+from dataclasses import asdict, dataclass, replace+from datetime import datetime, timezone+import importlib.metadata+import json+import os+from pathlib import Path+import re+import subprocess # nosec B404 - every launched argv is generated internally+import sys+import time+from typing import Any, Callable, Literal, Sequence+import uuid++import httpx++from deeptutor.__version__ import __version__+from deeptutor.runtime.home import get_runtime_home+from deeptutor.services.file_io import atomic_write_json++GITHUB_LATEST_RELEASE_URL = "https://api.github.com/repos/HKUDS/DeepTutor/releases/latest"+VERSION_CHECK_TTL_SECONDS = 24 * 60 * 60+LAUNCHER_PID_ENV = "DEEPTUTOR_LAUNCHER_PID"++InstallMode = Literal["pypi", "source", "docker", "unknown"]+JobStatus = Literal["pending", "handoff", "running", "restarting", "succeeded", "failed"]++_STABLE_VERSION = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)$")+_CURRENT_VERSION = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)")+++class VersionCheckError(RuntimeError):+ """Raised when official release metadata cannot be validated."""+++class UpdateRequestError(RuntimeError):+ """Raised when a managed update cannot be scheduled safely."""+++class UpdateInProgressError(UpdateRequestError):+ """Raised when another update already owns the durable active slot."""+++@dataclass(frozen=True, slots=True)+class Installation:+ mode: InstallMode+ current_version: str+ automatic_update: bool+ command: str+ reason: str+++@dataclass(frozen=True, slots=True)+class ReleaseInfo:+ version: str+ name: str+ published_at: str+ url: str+ excerpt: str+ migration_warning: bool+++@dataclass(frozen=True, slots=True)+class VersionCheckResult:+ current_version: str+ release: ReleaseInfo+ checked_at: str+ cached: bool++ @property+ def update_available(self) -> bool:+ return _version_tuple(self.release.version) > _version_tuple(self.current_version)+++@dataclass(frozen=True, slots=True)+class UpdateJob:+ id: str+ status: JobStatus+ current_version: str+ target_version: str+ created_at: str+ started_at: str | None = None+ finished_at: str | None = None+ error: str | None = None+ restart_home: str | None = None+ restart_argv: tuple[str, ...] = ()+ restart_count: int = 0+ schema_version: int = 1++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> UpdateJob:+ if payload.get("schema_version") != 1:+ raise ValueError("Unsupported update job")+ status = str(payload.get("status") or "")+ if status not in {"pending", "handoff", "running", "restarting", "succeeded", "failed"}:+ raise ValueError("Invalid update status")+ restart_home = _optional_string(payload.get("restart_home"))+ restart_argv = _validate_restart_argv(payload.get("restart_argv"), home=restart_home)+ return cls(+ id=str(payload["id"]),+ status=status, # type: ignore[arg-type]+ current_version=_normalise_stable_version(str(payload["current_version"])),+ target_version=_normalise_stable_version(str(payload["target_version"])),+ created_at=str(payload["created_at"]),+ started_at=_optional_string(payload.get("started_at")),+ finished_at=_optional_string(payload.get("finished_at")),+ error=_optional_string(payload.get("error")),+ restart_home=restart_home,+ restart_argv=restart_argv,+ restart_count=int(payload.get("restart_count") or 0),+ )+++def _optional_string(value: object) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _version_tuple(value: str) -> tuple[int, int, int]:+ match = _CURRENT_VERSION.match(value.strip())+ if match is None:+ raise ValueError(f"Invalid DeepTutor version: {value}")+ return tuple(int(part) for part in match.groups()) # type: ignore[return-value]+++def _normalise_stable_version(value: str) -> str:+ match = _STABLE_VERSION.fullmatch(value.strip())+ if match is None:+ raise ValueError("Update target must be a stable semantic version")+ return ".".join(match.groups())+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _running_in_container() -> bool:+ configured = os.getenv("DEEPTUTOR_CONTAINER", "").strip().lower()+ return configured in {"1", "true", "yes", "on"} or any(+ marker.exists() for marker in (Path("/.dockerenv"), Path("/run/.containerenv"))+ )+++def _distribution_direct_url() -> dict[str, Any] | None:+ try:+ distribution = importlib.metadata.distribution("deeptutor")+ except importlib.metadata.PackageNotFoundError:+ return None+ try:+ raw = distribution.read_text("direct_url.json")+ payload = json.loads(raw) if raw else {}+ except (OSError, ValueError):+ payload = {}+ return payload if isinstance(payload, dict) else {}+++def detect_installation() -> Installation:+ """Classify only layouts whose update ownership is unambiguous."""++ if _running_in_container():+ return Installation(+ mode="docker",+ current_version=__version__,+ automatic_update=False,+ command="docker pull ghcr.io/hkuds/deeptutor:latest",+ reason="Container images are updated and recreated by the Docker host.",+ )++ direct_url = _distribution_direct_url()+ if direct_url is None:+ return Installation(+ mode="unknown",+ current_version=__version__,+ automatic_update=False,+ command="pip install -U deeptutor",+ reason="The running DeepTutor distribution could not be identified.",+ )+ if bool((direct_url.get("dir_info") or {}).get("editable")):+ return Installation(+ mode="source",+ current_version=__version__,+ automatic_update=False,+ command="git pull && pip install -e .",+ reason="Source checkouts stay under the developer's Git workflow.",+ )++ in_virtualenv = Path(sys.prefix).resolve() != Path(sys.base_prefix).resolve()+ if not direct_url and in_virtualenv:+ return Installation(+ mode="pypi",+ current_version=__version__,+ automatic_update=True,+ command="pip install -U deeptutor",+ reason="",+ )+ return Installation(+ mode="unknown",+ current_version=__version__,+ automatic_update=False,+ command="pip install -U deeptutor",+ reason=(+ "Automatic updates require a regular PyPI installation in an active virtual environment."+ if not direct_url+ else "This installation came from a local or direct package artifact."+ ),+ )+++class VersionCheckService:+ """Read the latest stable release with a process-local 24-hour cache."""++ def __init__(+ self,+ *,+ api_url: str = GITHUB_LATEST_RELEASE_URL,+ timeout: float = 8.0,+ ttl_seconds: float = VERSION_CHECK_TTL_SECONDS,+ clock: Callable[[], float] = time.time,+ client_factory: Callable[[], httpx.AsyncClient] | None = None,+ ) -> None:+ self._api_url = api_url+ self._timeout = timeout+ self._ttl_seconds = ttl_seconds+ self._clock = clock+ self._client_factory = client_factory+ self._cache: VersionCheckResult | None = None+ self._cached_at: float | None = None+ self._lock = asyncio.Lock()++ def cached(self) -> VersionCheckResult | None:+ if self._cache is None or self._cached_at is None:+ return None+ if self._clock() - self._cached_at >= self._ttl_seconds:+ return None+ return replace(self._cache, cached=True)++ async def check(self, *, force: bool = False) -> VersionCheckResult:+ async with self._lock:+ if not force and (cached := self.cached()) is not None:+ return cached+ release = await self._fetch()+ result = VersionCheckResult(+ current_version=__version__,+ release=release,+ checked_at=_now(),+ cached=False,+ )+ self._cache = result+ self._cached_at = self._clock()+ return result++ async def _fetch(self) -> ReleaseInfo:+ factory = self._client_factory or (+ lambda: httpx.AsyncClient(+ timeout=httpx.Timeout(self._timeout, connect=5.0),+ follow_redirects=True,+ )+ )+ try:+ async with factory() as client:+ response = await client.get(+ self._api_url,+ headers={+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ "User-Agent": "DeepTutor-Version-Check",+ },+ )+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError):+ raise VersionCheckError("Unable to check for updates") from None+ return _release_from_payload(payload)+++def _release_from_payload(payload: Any) -> ReleaseInfo:+ if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):+ raise VersionCheckError("The latest stable release is unavailable")+ try:+ version = _normalise_stable_version(str(payload.get("tag_name") or ""))+ except ValueError:+ raise VersionCheckError("The latest release has an invalid version") from None+ url = str(payload.get("html_url") or "").strip()+ if not url.startswith("https://github.com/HKUDS/DeepTutor/releases/"):+ raise VersionCheckError("The latest release has an invalid URL")+ body = str(payload.get("body") or "").replace("\r\n", "\n").replace("\r", "\n").strip()+ excerpt = _plain_release_excerpt(body)+ lowered = body.lower()+ migration_warning = bool(+ re.search(+ r"breaking chang|migration(?: needed| required)|database migration|run migration|migrate your",+ lowered,+ )+ )+ return ReleaseInfo(+ version=version,+ name=str(payload.get("name") or "").strip(),+ published_at=str(payload.get("published_at") or "").strip(),+ url=url,+ excerpt=excerpt,+ migration_warning=migration_warning,+ )+++def _plain_release_excerpt(body: str) -> str:+ """Turn GitHub-flavoured release notes into a compact settings-page summary."""++ text = re.sub(r"<!--.*?-->", "", body, flags=re.DOTALL)+ text = re.sub(r"```.*?```", "", text, flags=re.DOTALL)+ text = re.sub(r"^\s{0,3}#{1,6}\s+.*$", "", text, flags=re.MULTILINE)+ text = re.sub(r"^\s*(?:-{3,}|\*{3,}|_{3,})\s*$", "", text, flags=re.MULTILINE)+ text = re.sub(r"!\[([^]]*)\]\([^)]+\)", r"\1", text)+ text = re.sub(r"\[([^]]+)\]\([^)]+\)", r"\1", text)+ text = re.sub(r"<https?://[^>]+>", "", text)+ text = re.sub(r"<[^>]+>", "", text)+ text = re.sub(r"(?m)^\s*(?:>|[-+*]|\d+[.)])\s+", "", text)+ text = re.sub(r"[*_~`]", "", text)++ lines: list[str] = []+ for line in text.splitlines():+ clean = re.sub(r"\s+", " ", line).strip()+ if re.match(r"^(?:release date|published)\s*:", clean, flags=re.IGNORECASE):+ continue+ if clean:+ lines.append(clean)+ summary = "\n\n".join(lines)+ return summary if len(summary) <= 640 else f"{summary[:637].rstrip()}..."+++def update_store_root(home: str | Path | None = None) -> Path:+ return get_runtime_home(home) / "data" / "user" / "update"+++class UpdateJobStore:+ """Persist one update job across the launcher restart boundary."""++ def __init__(self, root: Path) -> None:+ self.root = Path(root)+ self.state_path = self.root / "state.json"+ self.active_path = self.root / "active"+ self.log_path = self.root / "worker.log"++ def create(self, *, current_version: str, target_version: str) -> UpdateJob:+ current = _normalise_stable_version(current_version)+ target = _normalise_stable_version(target_version)+ if _version_tuple(target) <= _version_tuple(current):+ raise UpdateRequestError("No newer DeepTutor release is available")+ self.root.mkdir(parents=True, exist_ok=True)+ job = UpdateJob(+ id=uuid.uuid4().hex,+ status="pending",+ current_version=current,+ target_version=target,+ created_at=_now(),+ )+ try:+ descriptor = os.open(self.active_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)+ except FileExistsError as exc:+ raise UpdateInProgressError("Another update is already in progress") from exc+ try:+ os.write(descriptor, job.id.encode("ascii"))+ finally:+ os.close(descriptor)+ try:+ self._write(job)+ except Exception:+ self.release(job.id)+ raise+ return job++ def load(self) -> UpdateJob:+ payload = json.loads(self.state_path.read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ raise ValueError("Invalid update job")+ return UpdateJob.from_dict(payload)++ def prepare_handoff(+ self,+ job_id: str,+ *,+ home: Path,+ restart_argv: Sequence[str],+ ) -> UpdateJob:+ current = self.load()+ resolved_home = str(home.resolve())+ if current.id != job_id or current.status != "pending":+ raise RuntimeError("Update job is not awaiting launcher handoff")+ updated = replace(+ current,+ status="handoff",+ restart_home=resolved_home,+ restart_argv=_validate_restart_argv(tuple(restart_argv), home=resolved_home),+ )+ self._write(updated)+ return updated++ def mark_running(self, job_id: str) -> UpdateJob:+ return self._transition(job_id, expected={"handoff"}, status="running")++ def mark_restarting(self, job_id: str) -> UpdateJob:+ current = self.load()+ if current.id != job_id or current.status != "running":+ raise RuntimeError("Update job is not ready to restart")+ updated = replace(+ current,+ status="restarting",+ restart_count=current.restart_count + 1,+ )+ self._write(updated)+ return updated++ def mark_succeeded(self, job_id: str) -> UpdateJob:+ return self._transition(job_id, expected={"restarting"}, status="succeeded")++ def mark_failed(self, job_id: str, error: str) -> UpdateJob:+ return self._transition(+ job_id,+ expected={"pending", "handoff", "running", "restarting"},+ status="failed",+ error=(error or "Update failed")[:1000],+ )++ def _transition(+ self,+ job_id: str,+ *,+ expected: set[JobStatus],+ status: JobStatus,+ error: str | None = None,+ ) -> UpdateJob:+ current = self.load()+ if current.id != job_id or current.status not in expected:+ raise RuntimeError("Update job changed while it was running")+ timestamp = _now()+ updated = replace(+ current,+ status=status,+ started_at=timestamp if status == "running" else current.started_at,+ finished_at=timestamp if status in {"succeeded", "failed"} else current.finished_at,+ error=error,+ )+ self._write(updated)+ if status in {"succeeded", "failed"}:+ self.release(job_id)+ return updated++ def release(self, job_id: str) -> None:+ try:+ owner = self.active_path.read_text(encoding="ascii")+ except OSError:+ return+ if owner == job_id:+ self.active_path.unlink(missing_ok=True)++ def _write(self, job: UpdateJob) -> None:+ atomic_write_json(self.state_path, job.to_dict())+++def _validate_restart_argv(value: object, *, home: str | None) -> tuple[str, ...]:+ if value in (None, (), []):+ return ()+ if not isinstance(value, (list, tuple)) or any(+ not isinstance(argument, str) or not argument for argument in value+ ):+ raise ValueError("Invalid restart arguments")+ argv = tuple(value)+ valid = home is not None and argv[:3] == ("start", "--home", home)+ if not valid or argv[3:] not in {(), ("--dev",)}:+ raise ValueError("Invalid restart arguments")+ return argv+++def launcher_available() -> bool:+ raw = os.getenv(LAUNCHER_PID_ENV, "").strip()+ try:+ pid = int(raw)+ except ValueError:+ return False+ if pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ except PermissionError:+ return True+ except OSError:+ return False+ return True+++def launch_update_worker(store_root: Path, *, parent_pid: int) -> None:+ """Launch the trusted worker outside the process tree being replaced."""++ command = [+ sys.executable,+ "-m",+ "deeptutor.runtime.update_worker",+ "--store-root",+ str(store_root.resolve()),+ "--parent-pid",+ str(parent_pid),+ ]+ store_root.mkdir(parents=True, exist_ok=True)+ log_path = store_root / "worker.log"+ kwargs: dict[str, Any] = {+ "stdin": subprocess.DEVNULL,+ "stderr": subprocess.STDOUT,+ "close_fds": True,+ "shell": False,+ }+ if os.name == "nt":+ kwargs["creationflags"] = (+ subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]+ | subprocess.DETACHED_PROCESS # type: ignore[attr-defined]+ )+ else:+ kwargs["start_new_session"] = True+ with log_path.open("a", encoding="utf-8") as log:+ subprocess.Popen(command, stdout=log, **kwargs) # nosec B603+++_version_service = VersionCheckService()+++def get_version_check_service() -> VersionCheckService:+ return _version_service+++def reset_version_check_service_for_tests(service: VersionCheckService | None = None) -> None:+ global _version_service+ _version_service = service or VersionCheckService()+++__all__ = [+ "Installation",+ "LAUNCHER_PID_ENV",+ "ReleaseInfo",+ "UpdateInProgressError",+ "UpdateJob",+ "UpdateJobStore",+ "UpdateRequestError",+ "VersionCheckError",+ "VersionCheckResult",+ "VersionCheckService",+ "detect_installation",+ "get_version_check_service",+ "launch_update_worker",+ "launcher_available",+ "reset_version_check_service_for_tests",+ "update_store_root",+]diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 15205015d..079bfb76e 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -14,6 +14,11 @@ from .origins import normalize_originsDEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {"version": 1,+ # About → Updates performs at most one release lookup per process/day.+ # Operators may disable even that explicit network boundary for offline or+ # audited deployments; DEEPTUTOR_VERSION_CHECK_ENABLED is the deployment+ # override for read-only settings volumes.+ "version_check_enabled": True,"backend_port": 8001,"frontend_port": 3782,"next_public_api_base_external": "",@@ -579,6 +584,7 @@ class RuntimeSettingsService:auth = self.load_auth()integrations = self.load_integrations()return {+ "DEEPTUTOR_VERSION_CHECK_ENABLED": _bool_env(system["version_check_enabled"]),"BACKEND_PORT": str(system["backend_port"]),"FRONTEND_PORT": str(system["frontend_port"]),"NEXT_PUBLIC_API_BASE_EXTERNAL": system["next_public_api_base_external"],@@ -687,6 +693,8 @@ class RuntimeSettingsService:def _apply_system_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:payload = dict(settings)+ if value := self._process_env_value("DEEPTUTOR_VERSION_CHECK_ENABLED"):+ payload["version_check_enabled"] = valueif value := self._process_env_value("BACKEND_PORT"):payload["backend_port"] = valueif value := self._process_env_value("FRONTEND_PORT"):@@ -1035,6 +1043,7 @@ class RuntimeSettingsService:max_total_mb = max(max_total_mb, max_file_mb)return {"version": 1,+ "version_check_enabled": _coerce_bool(settings.get("version_check_enabled"), True),"backend_port": _coerce_port(settings.get("backend_port"), 8001),"frontend_port": _coerce_port(settings.get("frontend_port"), 3782),"next_public_api_base_external": public_api_base,diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 1065368a6..917e77a06 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -25,6 +25,7 @@ from deeptutor.services.session.protocol import SessionStoreProtocolif TYPE_CHECKING:from deeptutor.learning.storage import MasteryPathLease+ from deeptutor.services.app_update import UpdateJobfrom deeptutor.services.llm.config import LLMConfiglogger = logging.getLogger(__name__)@@ -253,6 +254,38 @@ def _mastery_path_id(value: Any) -> str:return str(value or "").strip()+WORKSPACE_MODE_READING = "immersive_reading"+WORKSPACE_MODE_MASTERY = "mastery_path"+_WORKSPACE_MODES = {WORKSPACE_MODE_READING, WORKSPACE_MODE_MASTERY}+_MASTERY_AGENTIC_ACTIONS = {+ "chat",+ "ask_questions",+ "deep_solve",+ "course_study",+ # Backward-compatible top-level workspace capabilities.+ "mastery_path",+ "immersive_reading",+}+++def _workspace_mode(value: Any, *, capability: str = "") -> str:+ """Normalize the stable workspace independently of the per-turn action.++ Older clients sent Reading/Mastery as the capability itself, so those two+ values remain a fallback while stored sessions migrate naturally.+ """+ candidate = str(value or "").strip()+ if candidate in _WORKSPACE_MODES:+ return candidate+ legacy = str(capability or "").strip()+ return legacy if legacy in _WORKSPACE_MODES else ""+++def _mastery_loop_managed(workspace_mode: str, capability: str) -> bool:+ """Whether this action can mutate mastery state and therefore needs a lease."""+ return workspace_mode == WORKSPACE_MODE_MASTERY and capability in _MASTERY_AGENTIC_ACTIONS++def _topic_material_manifest(path_id: str) -> tuple[str, dict[str, str]]:"""Load a mastery topic's materials as (manifest, read_source index).@@ -288,6 +321,92 @@ def _topic_material_manifest(path_id: str) -> tuple[str, dict[str, str]]:return "", {}+def _reading_action_context(+ material_id: str,+ viewport: dict[str, Any],+ question: str,+) -> str:+ """Bounded document evidence for non-agentic Reading actions."""+ if not material_id:+ return "The Reading workspace has no material open."+ try:+ from deeptutor.reading import ReadingStore, material_summary, search_material++ store = ReadingStore()+ manifest = store.manifest(material_id)+ lines = [f"Open material: {material_summary(manifest)}"]+ locator = int(viewport.get("locator") or 0)+ selection = str(viewport.get("selection") or "").strip()+ if selection:+ lines.append(f"Selected quote at {manifest.unit} {locator or '?'}: {selection}")+ if 1 <= locator <= manifest.unit_count:+ visible = _clip_text(store.unit_text(material_id, locator), limit=5_000)+ lines.append(f"Visible {manifest.unit} {locator}:\n{visible}")+ result = search_material(store, material_id, question, limit=4)+ if result.hits:+ lines.append("Relevant matches:")+ lines.extend(f"- {manifest.unit} {hit.locator}: {hit.snippet}" for hit in result.hits)+ lines.append(f"Treat these excerpts as source evidence and cite {manifest.unit} locators.")+ return "\n\n".join(lines)+ except Exception:+ logger.info("Reading action context unavailable for %s", material_id, exc_info=True)+ return "The open Reading material is unavailable."+++def _mastery_action_context(+ path_id: str,+ manifest: str,+ source_index: dict[str, str],+) -> str:+ """Bounded topic/progress context for Quiz/Research/Visualize actions."""+ if not path_id:+ return ""+ lines = [f"Mastery topic id: {path_id}"]+ try:+ from deeptutor.learning.storage import LearningStore++ store = LearningStore()+ progress = store.load(path_id)+ topic = store.get_topic(path_id, progress=progress) if progress else None+ if topic is not None:+ lines.append(+ f"Goal: {topic.metadata.goal or topic.metadata.description or progress.name}"+ )+ if progress is not None:+ lines.append(f"Current learning stage: {progress.current_stage.value}")+ module = next(+ (item for item in progress.modules if item.id == progress.current_module_id),+ None,+ )+ if module is not None:+ lines.append(f"Current module: {module.name}")+ if 0 <= progress.current_kp_index < len(module.knowledge_points):+ lines.append(+ "Current knowledge point: "+ + module.knowledge_points[progress.current_kp_index].name+ )+ except Exception:+ logger.info("Mastery action state unavailable for %s", path_id, exc_info=True)+ if manifest:+ lines.append("Topic source manifest:\n" + manifest)+ remaining = 12_000+ excerpts: list[str] = []+ for source_id, text in source_index.items():+ if remaining <= 0:+ break+ excerpt = _clip_text(text, limit=min(4_000, remaining))+ if excerpt:+ excerpts.append(f"--- {source_id} ---\n{excerpt}")+ remaining -= len(excerpt)+ if excerpts:+ lines.append("Topic source excerpts:\n" + "\n\n".join(excerpts))+ lines.append(+ "Use this topic as context for the requested action. Do not change mastery progress "+ "unless the turn is running the guided tutor loop."+ )+ return "\n\n".join(lines)++# Reading material ids are content hashes; anything else is a client bug or an# injection attempt, so the shape is enforced here rather than deeper in._READING_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")@@ -470,6 +589,9 @@ def _request_snapshot_metadata("knowledgeBases": _string_list(payload.get("knowledge_bases")),"language": str(payload.get("language", "en") or "en"),}+ workspace_mode = _workspace_mode(payload.get("workspace_mode"), capability=capability)+ if workspace_mode:+ snapshot["workspaceMode"] = workspace_modeif attachments:snapshot["attachments"] = attachmentsif config:@@ -1070,6 +1192,7 @@ class TurnRuntimeManager:self.store = store or get_session_store()self._lock = asyncio.Lock()self._executions: dict[str, _TurnExecution] = {}+ self._accepting_turns = True# Per-turn reply queues used by tools that pause the agentic# loop (e.g. ``ask_user``). Queue is created in ``_run_turn``# before the orchestrator is invoked and cleaned up in the@@ -1090,6 +1213,72 @@ class TurnRuntimeManager:"""return await self._has_live_execution(turn_id)+ async def has_live_executions(self) -> bool:+ """Return whether any turn is still owned by this process.++ Managed application updates use this coarse process-level signal before+ stopping the server. Placeholders without a task still count as live:+ they represent turns paused between setup and execution or awaiting a+ resume path, and interrupting either would lose learner-visible work.+ """+ async with self._lock:+ return any(+ execution.task is None or not execution.task.done()+ for execution in self._executions.values()+ )++ async def reserve_managed_update(+ self,+ reserve: Callable[[], UpdateJob],+ ) -> UpdateJob | None:+ """Atomically reserve an update only while this process is idle.++ The same lock publishes new turn ownership. Once ``reserve`` creates+ the durable update marker, later turns are rejected until the launcher+ replaces this process. A failed handoff removes that marker, allowing+ the next turn request to thaw the runtime automatically.+ """+ async with self._lock:+ if any(+ execution.task is None or not execution.task.done()+ for execution in self._executions.values()+ ):+ return None+ job = reserve()+ self._accepting_turns = False+ return job++ @staticmethod+ def _managed_update_is_active() -> bool:+ from deeptutor.services.app_update import UpdateJobStore, update_store_root++ store = UpdateJobStore(update_store_root())+ try:+ job = store.load()+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ return False+ return store.active_path.exists() and job.status in {+ "pending",+ "handoff",+ "running",+ "restarting",+ }++ def _turns_blocked_for_update_locked(self) -> bool:+ if self._accepting_turns:+ return False+ if not self._managed_update_is_active():+ self._accepting_turns = True+ return False+ return True++ async def _ensure_accepting_turns(self) -> None:+ async with self._lock:+ if self._turns_blocked_for_update_locked():+ raise RuntimeError(+ "DeepTutor is preparing an update; try again after it reconnects"+ )+async def _has_live_execution(self, turn_id: str) -> bool:"""Whether this process still owns the turn's in-memory runner."""async with self._lock:@@ -1226,6 +1415,7 @@ class TurnRuntimeManager:)async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:+ await self._ensure_accepting_turns()persona_explicit = "persona" in payloadif not payload.get("language"):from deeptutor.services.settings.interface_settings import (@@ -1285,6 +1475,13 @@ class TurnRuntimeManager:)capability = str(payload.get("capability") or "chat")+ workspace_mode_explicit = "workspace_mode" in payload+ workspace_mode = _workspace_mode(+ payload.get("workspace_mode")+ if workspace_mode_explicit+ else preferences.get("workspace_mode"),+ capability=capability,+ )try:from deeptutor.runtime.request_contracts import validate_capability_config@@ -1294,6 +1491,7 @@ class TurnRuntimeManager:payload = {**payload,"capability": capability,+ "workspace_mode": workspace_mode,"course_id": requested_course_id,# Rendered here, where the course is already loaded and validated,# and carried on the payload so the run phase needs no second read.@@ -1308,7 +1506,7 @@ class TurnRuntimeManager:}reading_workspace_id = _reading_workspace_id(payload.get("reading_workspace_id"))reading_material_id = _reading_material_id(payload.get("reading_material_id"))- if capability == "immersive_reading" and reading_workspace_id:+ if workspace_mode == WORKSPACE_MODE_READING and reading_workspace_id:from deeptutor.reading import ReadingCatalogStorereading_catalog = ReadingCatalogStore()@@ -1343,7 +1541,7 @@ class TurnRuntimeManager:else preferences.get("mastery_path_id"))mastery_binding = None- if capability == "mastery_path":+ if workspace_mode == WORKSPACE_MODE_MASTERY:from deeptutor.learning.identity import resolve_mastery_path_bindingmastery_binding = resolve_mastery_path_binding(@@ -1359,7 +1557,14 @@ class TurnRuntimeManager:)else:mastery_path_id = configured_mastery_path_id- payload = {**payload, "mastery_path_id": mastery_path_id}+ mastery_lease_managed = bool(+ mastery_binding is not None and _mastery_loop_managed(workspace_mode, capability)+ )+ payload = {+ **payload,+ "mastery_path_id": mastery_path_id,+ "mastery_path_lease_managed": mastery_lease_managed,+ }# Persona is a session-level preference (mirrors llm_selection): an# explicit ``persona`` key in the payload — including an empty string,# which means "Default" / no persona — wins and is persisted below.@@ -1461,6 +1666,7 @@ class TurnRuntimeManager:await self._recover_orphan_running_turns_for_session(session["id"])preference_update: dict[str, Any] = {"capability": capability,+ "workspace_mode": workspace_mode,"tools": list(payload.get("tools") or []),"knowledge_bases": list(payload.get("knowledge_bases") or []),"language": str(payload.get("language") or "en"),@@ -1517,7 +1723,7 @@ class TurnRuntimeManager:# Mastery turns persist their fully resolved path so a later turn# cannot silently fall back to a different aggregate.preference_update["mastery_path_id"] = mastery_path_id- if capability == "immersive_reading" and reading_workspace_id:+ if workspace_mode == WORKSPACE_MODE_READING and reading_workspace_id:preference_update.update({"session_kind": "immersive_reading",@@ -1525,6 +1731,18 @@ class TurnRuntimeManager:"reading_material_id": reading_material_id,})+ elif (+ workspace_mode_explicit+ and not workspace_mode+ and preferences.get("session_kind") == "immersive_reading"+ ):+ preference_update.update(+ {+ "session_kind": "chat",+ "reading_workspace_id": "",+ "reading_material_id": "",+ }+ )await self.store.update_session_preferences(session["id"], preference_update)turn = await self.store.create_turn(session["id"], capability=capability)execution = _TurnExecution(@@ -1538,9 +1756,19 @@ class TurnRuntimeManager:# turn row is created but before its task is registered, causing the# second caller to misclassify that healthy turn as a restart orphan.async with self._lock:- self._executions[turn["id"]] = execution+ update_blocked = self._turns_blocked_for_update_locked()+ if not update_blocked:+ self._executions[turn["id"]] = execution+ if update_blocked:+ with contextlib.suppress(Exception):+ await self.store.update_turn_status(+ turn["id"],+ "rejected",+ "DeepTutor is preparing an update; try again after it reconnects",+ )+ raise RuntimeError("DeepTutor is preparing an update; try again after it reconnects")mastery_lease_acquired = False- if mastery_binding is not None:+ if mastery_binding is not None and mastery_lease_managed:try:await self._acquire_mastery_path_lease(path_id=mastery_binding.path_id,@@ -1696,10 +1924,17 @@ class TurnRuntimeManager:if "mastery_path_id" in overrideselse snapshot.get("masteryPathId") or preferences.get("mastery_path_id"))+ workspace_mode = _workspace_mode(+ overrides.get("workspace_mode")+ if "workspace_mode" in overrides+ else snapshot.get("workspaceMode") or preferences.get("workspace_mode"),+ capability=capability,+ )payload: dict[str, Any] = {"session_id": session_id,"capability": capability,+ "workspace_mode": workspace_mode,"content": str(last_user.get("content", "") or ""),"tools": tools,"knowledge_bases": knowledge_bases,@@ -1959,6 +2194,8 @@ class TurnRuntimeManager:payload = execution.payloadsession_id = execution.session_idcapability_name = execution.capability+ workspace_mode = _workspace_mode(payload.get("workspace_mode"), capability=capability_name)+ mastery_lease_managed = bool(payload.get("mastery_path_lease_managed"))turn_id = execution.turn_idattachments = []attachment_records = []@@ -2420,13 +2657,45 @@ class TurnRuntimeManager:# Guarded on an empty chat-path index so materials the learner# attached to *this turn* (which took the chat path above) always win.mastery_topic_source_index: dict[str, str] = {}- if capability_name == "mastery_path" and not source_index:+ if workspace_mode == WORKSPACE_MODE_MASTERY and not source_index:topic_path_id = _mastery_path_id(payload.get("mastery_path_id"))if topic_path_id:source_manifest_text, mastery_topic_source_index = await asyncio.to_thread(_topic_material_manifest, topic_path_id)+ # Agentic actions receive workspace behavior through loop+ # capabilities and tools. Standalone pipelines (Quiz, Research,+ # Visualize) cannot call those hooks, so give them a bounded,+ # explicit snapshot of the same workspace instead.+ if not is_chat_capability and capability_name not in {+ "ask_questions",+ "deep_solve",+ "immersive_reading",+ "mastery_path",+ "course_study",+ }:+ workspace_context = ""+ if workspace_mode == WORKSPACE_MODE_READING:+ workspace_context = await asyncio.to_thread(+ _reading_action_context,+ _reading_material_id(payload.get("reading_material_id")),+ _reading_viewport(payload.get("reading_viewport")),+ raw_user_content,+ )+ elif workspace_mode == WORKSPACE_MODE_MASTERY:+ workspace_context = await asyncio.to_thread(+ _mastery_action_context,+ _mastery_path_id(payload.get("mastery_path_id")),+ source_manifest_text,+ mastery_topic_source_index,+ )+ if workspace_context:+ effective_user_message = (+ f"[Workspace Context]\n{workspace_context}\n\n"+ f"[User Question]\n{effective_user_message}"+ )+conversation_history = list(history_result.conversation_history)conversation_context_text = history_result.context_text@@ -2499,7 +2768,8 @@ class TurnRuntimeManager:"course_id": str(payload.get("course_id") or ""),"course_conventions": str(payload.get("course_conventions") or ""),"mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),- "mastery_path_lease_managed": capability_name == "mastery_path",+ "mastery_mode": workspace_mode == WORKSPACE_MODE_MASTERY,+ "mastery_path_lease_managed": mastery_lease_managed,# Immersive reading: the open material activates the reading# capability and binds its tools; the viewport tells the# model where the user is actually looking.@@ -2507,6 +2777,7 @@ class TurnRuntimeManager:"reading_workspace_id": _reading_workspace_id(payload.get("reading_workspace_id")),+ "immersive_reading_mode": workspace_mode == WORKSPACE_MODE_READING,"reading_viewport": _reading_viewport(payload.get("reading_viewport")),"book_context": book_context,"book_context_warnings": book_context_result.warnings,@@ -2575,6 +2846,7 @@ class TurnRuntimeManager:capability_name=capability_name,started_on=_mastery_path_id(payload.get("mastery_path_id")),ended_on=str(context.metadata.get("mastery_path_id") or ""),+ mastery_mode=mastery_lease_managed,)# Office binaries the browser cannot render need their text pulled@@ -2769,7 +3041,7 @@ class TurnRuntimeManager:# that finds the queue gone will return ``False`` rather than# accumulating on a dead turn.self._reply_queues.pop(turn_id, None)- if capability_name == "mastery_path":+ if bool(payload.get("mastery_path_lease_managed")):from deeptutor.learning.storage import LearningStore# By turn, not by the path the turn started on: mastery_switch@@ -2801,9 +3073,14 @@ class TurnRuntimeManager:capability_name: str,started_on: str,ended_on: str,+ mastery_mode: bool = False,) -> None:"""Announce a path the turn moved onto, so the client stops lying."""- if capability_name != "mastery_path" or not ended_on or ended_on == started_on:+ if (+ not (capability_name == "mastery_path" or mastery_mode)+ or not ended_on+ or ended_on == started_on+ ):returnawait self._publish_live_event(execution,diff --git a/tests/api/test_system_router.py b/tests/api/test_system_router.pyindex 328d14ba5..1dc40501c 100644--- a/tests/api/test_system_router.py+++ b/tests/api/test_system_router.py@@ -6,6 +6,12 @@ import pytestfrom deeptutor.api.routers import system as system_routerfrom deeptutor.runtime.memory_probe import MemorySnapshot, ProcessMemory+from deeptutor.services.app_update import (+ Installation,+ ReleaseInfo,+ UpdateJobStore,+ VersionCheckResult,+)def _snapshot(*processes: ProcessMemory, **overrides: object) -> MemorySnapshot:@@ -21,6 +27,136 @@ def _snapshot(*processes: ProcessMemory, **overrides: object) -> MemorySnapshot:return MemorySnapshot(**fields) # type: ignore[arg-type]+class _UpdateSettings:+ def __init__(self, enabled: bool = True) -> None:+ self.enabled = enabled++ def load_system(self, *, include_process_overrides: bool = True) -> dict[str, object]:+ del include_process_overrides+ return {"version_check_enabled": self.enabled}++ def save_system(self, payload: dict[str, object]) -> dict[str, object]:+ self.enabled = bool(payload["version_check_enabled"])+ return payload+++class _VersionService:+ def __init__(self, result: VersionCheckResult) -> None:+ self.result = result+ self.forces: list[bool] = []++ async def check(self, *, force: bool = False) -> VersionCheckResult:+ self.forces.append(force)+ return self.result++ def cached(self) -> VersionCheckResult:+ return self.result+++def _update_result() -> VersionCheckResult:+ return VersionCheckResult(+ current_version="1.6.1",+ release=ReleaseInfo(+ version="1.7.0",+ name="DeepTutor 1.7",+ published_at="2026-08-30T00:00:00Z",+ url="https://github.com/HKUDS/DeepTutor/releases/tag/v1.7.0",+ excerpt="A stable release.",+ migration_warning=False,+ ),+ checked_at="2026-08-30T00:00:00+00:00",+ cached=False,+ )+++def _pypi_installation() -> Installation:+ return Installation(+ mode="pypi",+ current_version="1.6.1",+ automatic_update=True,+ command="pip install -U deeptutor",+ reason="",+ )+++async def test_update_status_combines_cached_release_and_installation(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ version_service = _VersionService(_update_result())+ monkeypatch.setattr(system_router, "get_runtime_settings_service", _UpdateSettings)+ monkeypatch.setattr(system_router, "get_version_check_service", lambda: version_service)+ monkeypatch.setattr(system_router, "get_update_installation", _pypi_installation)+ monkeypatch.setattr(system_router, "launcher_available", lambda: True)+ monkeypatch.setattr(+ system_router,+ "get_update_job_store",+ lambda: UpdateJobStore(tmp_path / "update"),+ )+ monkeypatch.setattr(+ system_router,+ "get_current_user",+ lambda: SimpleNamespace(is_admin=True),+ )++ payload = await system_router.get_update_status()++ assert payload["current_version"] == "1.6.1"+ assert payload["release"]["version"] == "1.7.0"+ assert payload["update_available"] is True+ assert payload["installation"]["mode"] == "pypi"+ assert version_service.forces == [False]+++async def test_managed_update_refuses_live_conversation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _Activity:+ async def reserve_managed_update(self, _reserve):+ return None++ monkeypatch.setattr(system_router, "get_runtime_settings_service", _UpdateSettings)+ monkeypatch.setattr(system_router, "launcher_available", lambda: True)+ monkeypatch.setattr(system_router, "get_turn_activity", _Activity)++ with pytest.raises(Exception) as raised:+ await system_router.request_managed_update(+ system_router.ManagedUpdateRequest(confirmation="update-and-restart")+ )++ assert getattr(raised.value, "status_code", None) == 409+++async def test_managed_update_creates_durable_job(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ class _Activity:+ async def reserve_managed_update(self, reserve):+ return reserve()++ store = UpdateJobStore(tmp_path / "update")+ monkeypatch.setattr(system_router, "get_runtime_settings_service", _UpdateSettings)+ monkeypatch.setattr(system_router, "launcher_available", lambda: True)+ monkeypatch.setattr(system_router, "get_turn_activity", _Activity)+ monkeypatch.setattr(system_router, "get_update_installation", _pypi_installation)+ monkeypatch.setattr(+ system_router, "get_version_check_service", lambda: _VersionService(_update_result())+ )+ monkeypatch.setattr(system_router, "get_update_job_store", lambda: store)++ payload = await system_router.request_managed_update(+ system_router.ManagedUpdateRequest(confirmation="update-and-restart")+ )++ assert payload["status"] == "pending"+ assert payload["target_version"] == "1.7.0"+ assert store.load().id == payload["id"]++@pytest.mark.asyncioasync def test_embeddings_connection_uses_batch_probe(monkeypatch: pytest.MonkeyPatch) -> None:captured: dict[str, list[str]] = {}diff --git a/tests/reading/test_turn_wiring.py b/tests/reading/test_turn_wiring.pyindex 5522389ed..9ee5a95a4 100644--- a/tests/reading/test_turn_wiring.py+++ b/tests/reading/test_turn_wiring.py@@ -22,6 +22,7 @@ from deeptutor.services.session.turn_runtime import (_reading_material_id,_reading_viewport,_request_snapshot_metadata,+ _workspace_mode,)# ---------------------------------------------------------------------------@@ -123,6 +124,32 @@ def test_open_material_is_persisted_with_the_user_message() -> None:assert snapshot["readingMaterialId"] == "0123456789abcdef"+def test_workspace_mode_is_persisted_independently_of_the_action() -> None:+ snapshot = _snapshot(+ {+ "workspace_mode": "immersive_reading",+ "reading_material_id": "0123456789abcdef",+ }+ )+ assert snapshot["workspaceMode"] == "immersive_reading"+++ ("value", "capability", "expected"),+ [+ ("immersive_reading", "deep_research", "immersive_reading"),+ ("mastery_path", "visualize", "mastery_path"),+ (None, "immersive_reading", "immersive_reading"),+ (None, "mastery_path", "mastery_path"),+ ("unknown", "chat", ""),+ ],+)+def test_workspace_mode_is_orthogonal_with_legacy_fallback(+ value: object, capability: str, expected: str+) -> None:+ assert _workspace_mode(value, capability=capability) == expected++def test_a_plain_chat_turn_carries_no_reading_key() -> None:assert "readingMaterialId" not in _snapshot({})assert "readingMaterialId" not in _snapshot({"reading_material_id": ""})@@ -150,7 +177,8 @@ async def test_empty_workspace_starts_in_no_material_mode(_session, turn = await runtime.start_turn({"type": "start_turn",- "capability": "immersive_reading",+ "capability": "chat",+ "workspace_mode": "immersive_reading","reading_workspace_id": workspace.workspace_id,"content": "What can I read here?","tools": [],@@ -162,5 +190,9 @@ async def test_empty_workspace_starts_in_no_material_mode()assert runtime._executions[turn["id"]].payload["reading_material_id"] == ""+ detail = await runtime.store.get_session(_session["id"])+ assert detail is not None+ assert detail["preferences"]["workspace_mode"] == "immersive_reading"+ assert detail["preferences"]["capability"] == "chat"finally:PathService.reset_instance()diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.pyindex a6a4e365c..5d330e5db 100644--- a/tests/runtime/test_launcher.py+++ b/tests/runtime/test_launcher.py@@ -7,6 +7,7 @@ import pytestfrom deeptutor.runtime import launcherfrom deeptutor.runtime.home import validate_runtime_home+from deeptutor.services.app_update import UpdateJobStore, update_store_rootclass _FakeTty:@@ -61,6 +62,40 @@ def test_start_does_not_create_nested_data_tree(monkeypatch, tmp_path: Path) ->assert not bad_home.exists()+def test_launcher_hands_pending_update_to_worker(tmp_path: Path) -> None:+ store = UpdateJobStore(update_store_root(tmp_path))+ pending = store.create(current_version="1.6.1", target_version="1.7.0")+ launched: list[Path] = []++ handed_off = launcher._handoff_pending_update(+ tmp_path,+ restart_argv=["start", "--home", str(tmp_path.resolve())],+ worker_launcher=launched.append,+ )++ assert handed_off is True+ assert launched == [store.root]+ job = store.load()+ assert job.id == pending.id+ assert job.status == "handoff"+ assert job.restart_home == str(tmp_path.resolve())+++def test_launcher_completes_update_only_after_restart(tmp_path: Path) -> None:+ store = UpdateJobStore(update_store_root(tmp_path))+ pending = store.create(current_version="1.6.1", target_version="1.7.0")+ store.prepare_handoff(+ pending.id,+ home=tmp_path,+ restart_argv=["start", "--home", str(tmp_path.resolve())],+ )+ store.mark_running(pending.id)+ store.mark_restarting(pending.id)++ assert launcher._complete_restarted_update(tmp_path) is True+ assert store.load().status == "succeeded"++def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path) -> None:packaged = tmp_path / "pkg"(packaged / ".next").mkdir(parents=True)diff --git a/tests/runtime/test_update_worker.py b/tests/runtime/test_update_worker.pynew file mode 100644index 000000000..4463ce10e--- /dev/null+++ b/tests/runtime/test_update_worker.py@@ -0,0 +1,73 @@+from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.runtime.update_worker import build_update_command, run_update_worker+from deeptutor.services.app_update import UpdateJob, UpdateJobStore+++def _handoff_job(tmp_path: Path) -> tuple[UpdateJobStore, UpdateJob]:+ store = UpdateJobStore(tmp_path / "update")+ pending = store.create(current_version="1.6.1", target_version="1.7.0")+ home = tmp_path / "home"+ home.mkdir()+ job = store.prepare_handoff(+ pending.id,+ home=home,+ restart_argv=["start", "--home", str(home.resolve())],+ )+ return store, job+++def test_worker_updates_then_restarts(tmp_path: Path) -> None:+ store, job = _handoff_job(tmp_path)+ captured: dict[str, object] = {}++ def run(command: list[str], cwd: Path, log_path: Path) -> int:+ captured.update(command=command, cwd=cwd, log_path=log_path)+ return 0++ def restart(value: UpdateJob, log_path: Path) -> None:+ captured.update(restart=value, restart_log=log_path)++ result = run_update_worker(+ store_root=store.root,+ parent_pid=123,+ wait_for_parent=lambda pid: captured.update(parent_pid=pid),+ command_runner=run,+ restart_launcher=restart,+ )++ assert result == 0+ assert captured["parent_pid"] == 123+ assert captured["command"] == build_update_command("1.7.0")+ assert isinstance(captured["restart"], UpdateJob)+ assert store.load().status == "restarting"+ assert store.load().restart_count == 1+++def test_worker_failure_is_durable_and_restores_app(tmp_path: Path) -> None:+ store, _job = _handoff_job(tmp_path)+ restarted: list[UpdateJob] = []++ result = run_update_worker(+ store_root=store.root,+ parent_pid=123,+ wait_for_parent=lambda _pid: None,+ command_runner=lambda _command, _cwd, _log: 7,+ restart_launcher=lambda value, _log: restarted.append(value),+ )++ assert result == 1+ assert store.load().status == "failed"+ assert store.load().error == "pip exited with status 7"+ assert restarted and restarted[0].status == "failed"+++def test_update_command_rejects_non_stable_or_injected_versions() -> None:+ with pytest.raises(ValueError):+ build_update_command("1.7.0rc1")+ with pytest.raises(ValueError):+ build_update_command("1.7.0; touch /tmp/nope")diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.pyindex 98a6657cb..7f0a81a43 100644--- a/tests/services/config/test_runtime_settings.py+++ b/tests/services/config/test_runtime_settings.py@@ -10,6 +10,7 @@ from deeptutor.services.config.runtime_settings import ()RUNTIME_ENV_KEYS = (+ "DEEPTUTOR_VERSION_CHECK_ENABLED","BACKEND_PORT","FRONTEND_PORT","NEXT_PUBLIC_API_BASE_EXTERNAL",@@ -51,6 +52,7 @@ def test_runtime_settings_creates_defaults_without_reading_dotenv(tmp_path: Pathservice = RuntimeSettingsService(tmp_path / "settings")assert service.load_system(include_process_overrides=False)["backend_port"] == 8001+ assert service.load_system(include_process_overrides=False)["version_check_enabled"] is Trueassert service.load_auth(include_process_overrides=False)["enabled"] is Falseassert service.load_integrations(include_process_overrides=False)["pocketbase_url"] == ""@@ -62,6 +64,7 @@ def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:service = RuntimeSettingsService(tmp_path / "settings",process_env={+ "DEEPTUTOR_VERSION_CHECK_ENABLED": "false","BACKEND_PORT": "9100","AUTH_ENABLED": "true","POCKETBASE_PORT": "9090",@@ -72,6 +75,7 @@ def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:service.save_integrations({"pocketbase_port": 8090})assert service.load_system()["backend_port"] == 9100+ assert service.load_system()["version_check_enabled"] is Falseassert service.load_auth()["enabled"] is Trueassert service.load_integrations()["pocketbase_port"] == 9090assert _read_json(service.path_for("system"))["backend_port"] == 8001@@ -101,6 +105,7 @@ def test_render_environment_uses_json_backed_runtime_names(monkeypatch, tmp_pathenv = service.render_environment()assert env["BACKEND_PORT"] == "8010"+ assert env["DEEPTUTOR_VERSION_CHECK_ENABLED"] == "true"assert env["FRONTEND_PORT"] == "3790"assert env["CORS_ORIGINS"] == "https://app.example"assert env["DISABLE_SSL_VERIFY"] == "true"diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.pyindex 1d162ae14..768c0327b 100644--- a/tests/services/session/test_turn_runtime_subscribe.py+++ b/tests/services/session/test_turn_runtime_subscribe.py@@ -40,6 +40,14 @@ def _mastery_payload(session_id: str, path_id: str) -> dict:}+def _mastery_chat_payload(session_id: str, path_id: str) -> dict:+ return {+ **_mastery_payload(session_id, path_id),+ "capability": "chat",+ "workspace_mode": "mastery_path",+ }++def test_terminal_error_marks_turn_failed() -> None:error_message = "provider authentication failed"status, error = _resolve_turn_outcome(@@ -81,6 +89,35 @@ def test_non_terminal_error_keeps_completed_done_status() -> None:assert error == ""+async def test_has_live_executions_counts_placeholders_and_running_tasks(tmp_path) -> None:+ runtime = TurnRuntimeManager(SQLiteSessionStore(tmp_path / "chat_history.db"))+ runtime._executions["placeholder"] = SimpleNamespace(task=None) # type: ignore[assignment]+ assert await runtime.has_live_executions() is True++ runtime._executions.clear()+ task = asyncio.create_task(asyncio.sleep(0))+ runtime._executions["running"] = SimpleNamespace(task=task) # type: ignore[assignment]+ assert await runtime.has_live_executions() is True++ await task+ assert await runtime.has_live_executions() is False+++async def test_managed_update_reservation_is_atomic_with_turn_ownership(tmp_path) -> None:+ runtime = TurnRuntimeManager(SQLiteSessionStore(tmp_path / "chat_history.db"))+ reserved = object()++ assert await runtime.reserve_managed_update(lambda: reserved) is reserved+ runtime._managed_update_is_active = lambda: True # type: ignore[method-assign]+ with pytest.raises(RuntimeError, match="preparing an update"):+ await runtime._ensure_accepting_turns()++ runtime._managed_update_is_active = lambda: False # type: ignore[method-assign]+ await runtime._ensure_accepting_turns()++@pytest.mark.asyncioasync def test_subscribe_turn_does_not_synthesize_done_for_running_turn(tmp_path) -> None:"""A paused/replaced subscription must not make the UI think the turn ended."""@@ -422,6 +459,34 @@ async def test_mastery_path_allows_only_one_live_turn_across_sessions(LearningStore().release_path_lease("shared", turn_id=first_turn["id"])+async def test_chat_action_inside_mastery_keeps_path_binding_and_lease(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ _isolate_learning_store(monkeypatch, tmp_path)+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ session = await store.ensure_session("session-1")+ hold = asyncio.Event()++ async def _hold_turn(_execution):+ await hold.wait()++ monkeypatch.setattr(runtime, "_run_turn", _hold_turn)+ _, turn = await runtime.start_turn(_mastery_chat_payload(session["id"], "shared"))++ lease = LearningStore().get_path_lease("shared")+ assert lease is not None+ assert lease.turn_id == turn["id"]+ detail = await store.get_session(session["id"])+ assert detail is not None+ assert detail["preferences"]["workspace_mode"] == "mastery_path"+ assert detail["preferences"]["capability"] == "chat"++ await runtime.cancel_turn(turn["id"])+ LearningStore().release_path_lease("shared", turn_id=turn["id"])++@pytest.mark.asyncioasync def test_mastery_turn_rejects_session_from_an_unrelated_topic(monkeypatch: pytest.MonkeyPatch, tmp_pathdiff --git a/tests/services/test_app_update.py b/tests/services/test_app_update.pynew file mode 100644index 000000000..1280ea6d1--- /dev/null+++ b/tests/services/test_app_update.py@@ -0,0 +1,157 @@+from __future__ import annotations++import json+from pathlib import Path++import httpx+import pytest++from deeptutor.services import app_update+from deeptutor.services.app_update import UpdateJobStore, VersionCheckError, VersionCheckService+++def _client_factory(payload: dict, *, status_code: int = 200):+ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(status_code, json=payload)++ return lambda: httpx.AsyncClient(transport=httpx.MockTransport(handler))+++def _release(**overrides: object) -> dict:+ payload = {+ "tag_name": "v1.7.0",+ "name": "DeepTutor 1.7",+ "published_at": "2026-08-30T00:00:00Z",+ "html_url": "https://github.com/HKUDS/DeepTutor/releases/tag/v1.7.0",+ "body": "A stable release.",+ "draft": False,+ "prerelease": False,+ }+ payload.update(overrides)+ return payload+++async def test_version_check_caches_success_for_the_ttl() -> None:+ calls = 0++ def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ return httpx.Response(200, json=_release())++ service = VersionCheckService(+ client_factory=lambda: httpx.AsyncClient(transport=httpx.MockTransport(handler)),+ clock=lambda: 100,+ )++ first = await service.check()+ second = await service.check()++ assert calls == 1+ assert first.cached is False+ assert second.cached is True+ assert second.release.version == "1.7.0"+ assert second.update_available is True+++async def test_version_check_rejects_prereleases_and_untrusted_urls() -> None:+ prerelease = VersionCheckService(+ client_factory=_client_factory(_release(prerelease=True)),+ )+ bad_url = VersionCheckService(+ client_factory=_client_factory(_release(html_url="https://example.com/v1.7.0")),+ )++ with pytest.raises(VersionCheckError):+ await prerelease.check()+ with pytest.raises(VersionCheckError):+ await bad_url.check()+++async def test_release_marks_migration_notes() -> None:+ service = VersionCheckService(+ client_factory=_client_factory(_release(body="Breaking changes: run migration first.")),+ )++ result = await service.check()++ assert result.release.migration_warning is True+++async def test_release_excerpt_is_clean_plain_text() -> None:+ service = VersionCheckService(+ client_factory=_client_factory(+ _release(+ body=(+ "# DeepTutor release notes\n\n"+ "**Release Date:** 2026.08.30\n\n"+ "Use the [new updater](https://example.com) with **one confirmation**."+ )+ )+ ),+ )++ result = await service.check()++ assert result.release.excerpt == "Use the new updater with one confirmation."+++def test_detect_installation_keeps_source_and_docker_host_managed(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setattr(app_update, "_running_in_container", lambda: True)+ assert app_update.detect_installation().mode == "docker"++ monkeypatch.setattr(app_update, "_running_in_container", lambda: False)+ monkeypatch.setattr(+ app_update,+ "_distribution_direct_url",+ lambda: {"dir_info": {"editable": True}},+ )+ assert app_update.detect_installation().mode == "source"++ monkeypatch.setattr(app_update, "_distribution_direct_url", lambda: {})+ monkeypatch.setattr(app_update.sys, "prefix", str(tmp_path / "venv"))+ monkeypatch.setattr(app_update.sys, "base_prefix", str(tmp_path / "base"))+ installation = app_update.detect_installation()+ assert installation.mode == "pypi"+ assert installation.automatic_update is True+++def test_update_job_store_persists_trusted_lifecycle(tmp_path: Path) -> None:+ store = UpdateJobStore(tmp_path / "update")+ job = store.create(current_version="1.6.1", target_version="1.7.0")+ home = tmp_path / "home"++ handoff = store.prepare_handoff(+ job.id,+ home=home,+ restart_argv=["start", "--home", str(home.resolve())],+ )+ running = store.mark_running(job.id)+ restarting = store.mark_restarting(job.id)+ succeeded = store.mark_succeeded(job.id)++ assert handoff.status == "handoff"+ assert running.started_at+ assert restarting.restart_count == 1+ assert succeeded.status == "succeeded"+ assert not store.active_path.exists()+++def test_update_job_rejects_tampered_restart_arguments(tmp_path: Path) -> None:+ store = UpdateJobStore(tmp_path / "update")+ job = store.create(current_version="1.6.1", target_version="1.7.0")+ home = tmp_path / "home"++ with pytest.raises(ValueError, match="Invalid restart arguments"):+ store.prepare_handoff(+ job.id,+ home=home,+ restart_argv=["start", "--home", str(home.resolve()), "--port", "9999"],+ )diff --git a/web/app/(utility)/mastery/[pathId]/study/layout.tsx b/web/app/(utility)/mastery/[pathId]/study/layout.tsxindex b5652d6fb..4eb55d3a8 100644--- a/web/app/(utility)/mastery/[pathId]/study/layout.tsx+++ b/web/app/(utility)/mastery/[pathId]/study/layout.tsx@@ -1,3 +1,5 @@+import { GeogebraTabProvider } from "@/context/GeogebraTabContext";+import { QuizFollowupProvider } from "@/context/QuizFollowupContext";import { UnifiedChatProvider } from "@/context/UnifiedChatContext";/**@@ -9,5 +11,11 @@ import { UnifiedChatProvider } from "@/context/UnifiedChatContext";export default function MasteryStudyLayout({children,}: Readonly<{ children: React.ReactNode }>) {- return <UnifiedChatProvider>{children}</UnifiedChatProvider>;+ return (+ <UnifiedChatProvider>+ <QuizFollowupProvider>+ <GeogebraTabProvider>{children}</GeogebraTabProvider>+ </QuizFollowupProvider>+ </UnifiedChatProvider>+ );}diff --git a/web/app/(utility)/settings/about/page.tsx b/web/app/(utility)/settings/about/page.tsxnew file mode 100644index 000000000..e88fb6c67--- /dev/null+++ b/web/app/(utility)/settings/about/page.tsx@@ -0,0 +1,448 @@+'use client'++import { useCallback, useEffect, useMemo, useState } from 'react'+import {+ ArrowUpRight,+ Check,+ CircleAlert,+ Download,+ Github,+ RefreshCw,+ RotateCw,+ ShieldCheck,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Toggle } from '@/components/settings/Toggle'+import { SettingRow, SettingSection, SettingsPageHeader } from '@/components/settings/shared'+import { ConfirmDialog } from '@/components/ui/ConfirmDialog'+import Button from '@/components/ui/Button'+import {+ checkAppUpdate,+ fetchAppUpdateJob,+ fetchAppUpdateStatus,+ requestAppUpdate,+ setAppUpdateChecks,+ updateJobIsActive,+ type AppUpdateStatus,+ type InstallMode,+ type UpdateJob,+ type UpdateJobStatus,+} from '@/lib/app-update'+import { normalizeVersionTag } from '@/lib/version'++const POLL_INTERVAL_MS = 800+const POLL_TIMEOUT_MS = 120_000++const INSTALLATION_LABELS: Record<InstallMode, string> = {+ pypi: 'PyPI package',+ source: 'Source checkout',+ docker: 'Docker container',+ unknown: 'Unknown installation',+}++function jobTone(status: UpdateJobStatus) {+ if (status === 'failed') return 'text-red-600 dark:text-red-400'+ if (status === 'succeeded') return 'text-emerald-700 dark:text-emerald-400'+ return 'text-sky-700 dark:text-sky-400'+}++export default function AboutSettingsPage() {+ const { t, i18n } = useTranslation()+ const [status, setStatus] = useState<AppUpdateStatus | null>(null)+ const [job, setJob] = useState<UpdateJob | null>(null)+ const [loading, setLoading] = useState(true)+ const [checking, setChecking] = useState(false)+ const [savingChecks, setSavingChecks] = useState(false)+ const [requesting, setRequesting] = useState(false)+ const [confirmOpen, setConfirmOpen] = useState(false)+ const [error, setError] = useState('')++ const load = useCallback(async () => {+ try {+ const next = await fetchAppUpdateStatus()+ setStatus(next)+ setJob(next.job)+ setError(next.check_error || '')+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : (t('Unable to load version information.') as string)+ )+ } finally {+ setLoading(false)+ }+ }, [t])++ useEffect(() => {+ void load()+ }, [load])++ const activeJob = Boolean(job && updateJobIsActive(job.status))+ useEffect(() => {+ if (!activeJob) return+ let cancelled = false+ let timer: ReturnType<typeof setTimeout> | undefined+ const deadline = Date.now() + POLL_TIMEOUT_MS++ const poll = async () => {+ try {+ const next = await fetchAppUpdateJob()+ if (cancelled) return+ if (next) {+ setJob(next)+ if (!updateJobIsActive(next.status)) {+ if (next.status === 'succeeded') await load()+ return+ }+ }+ } catch {+ // The backend is expected to disappear while the launcher updates and+ // restarts it. Keep polling until it reconnects or the deadline passes.+ }+ if (cancelled) return+ if (Date.now() >= deadline) {+ setError(t('DeepTutor did not reconnect before the update timeout.'))+ return+ }+ timer = setTimeout(poll, POLL_INTERVAL_MS)+ }++ void poll()+ return () => {+ cancelled = true+ if (timer) clearTimeout(timer)+ }+ }, [activeJob, load, t])++ const check = useCallback(async () => {+ setChecking(true)+ setError('')+ try {+ const next = await checkAppUpdate()+ setStatus(next)+ setJob(next.job)+ } catch (cause) {+ setError(+ cause instanceof Error ? cause.message : (t('Unable to check for updates.') as string)+ )+ } finally {+ setChecking(false)+ }+ }, [t])++ const changeChecks = useCallback(+ async (enabled: boolean) => {+ setSavingChecks(true)+ setError('')+ try {+ const next = await setAppUpdateChecks(enabled)+ setStatus(next)+ setJob(next.job)+ } catch (cause) {+ setError(+ cause instanceof Error ? cause.message : (t('Unable to save update settings.') as string)+ )+ } finally {+ setSavingChecks(false)+ }+ },+ [t]+ )++ const update = useCallback(async () => {+ setRequesting(true)+ setError('')+ try {+ const next = await requestAppUpdate()+ setJob(next)+ setConfirmOpen(false)+ } catch (cause) {+ setError(+ cause instanceof Error ? cause.message : (t('Unable to start the update.') as string)+ )+ } finally {+ setRequesting(false)+ }+ }, [t])++ const currentVersion =+ normalizeVersionTag(status?.current_version) ??+ normalizeVersionTag(process.env.NEXT_PUBLIC_APP_VERSION) ??+ '—'+ const latestVersion = normalizeVersionTag(status?.release?.version)+ const checkedAt = useMemo(() => {+ if (!status?.checked_at) return ''+ const parsed = new Date(status.checked_at)+ if (Number.isNaN(parsed.getTime())) return ''+ return parsed.toLocaleString(+ i18n.language?.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US',+ { dateStyle: 'medium', timeStyle: 'short' }+ )+ }, [i18n.language, status?.checked_at])++ const installMode = status?.installation.mode ?? 'unknown'+ const canUpdate = Boolean(+ status?.is_admin &&+ status.check_enabled &&+ status.update_available &&+ status.installation.automatic_update &&+ status.launcher_managed &&+ !activeJob+ )+ const upToDate = Boolean(status?.release && !status.update_available)++ return (+ <div data-tour="tour-about" className="pb-8">+ <SettingsPageHeader+ title={t('About')}+ description={t(+ 'DeepTutor version, release channel, and the safest update path for this installation.'+ )}+ />++ <section className="relative mb-10 overflow-hidden border-y border-[var(--border)]/60 py-7">+ <div+ aria-hidden+ className="pointer-events-none absolute -right-12 -top-16 h-40 w-40 rounded-full border-[28px] border-[var(--foreground)]/[0.025]"+ />+ <div className="relative flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">+ <div>+ <div className="mb-2 flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />+ {t('Running version')}+ </div>+ <div className="font-serif text-[38px] font-semibold leading-none tracking-[-0.035em] text-[var(--foreground)]">+ {currentVersion}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {status?.release?.url && (+ <a+ href={status.release.url}+ target="_blank"+ rel="noreferrer noopener"+ className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ {t('Release notes')}+ <ArrowUpRight className="h-3.5 w-3.5" />+ </a>+ )}+ {status?.is_admin && (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ loading={checking}+ disabled={!status.check_enabled || activeJob}+ icon={<RefreshCw className="h-3.5 w-3.5" />}+ onClick={() => void check()}+ >+ {t('Check now')}+ </Button>+ )}+ {canUpdate && (+ <Button+ type="button"+ size="sm"+ icon={<Download className="h-3.5 w-3.5" />}+ onClick={() => setConfirmOpen(true)}+ >+ {t('Update to {{version}}', { version: latestVersion ?? '' })}+ </Button>+ )}+ </div>+ </div>+ </section>++ {error && (+ <div className="mb-7 flex items-start gap-2 border-l-2 border-red-500/70 py-1 pl-3 text-[12.5px] leading-relaxed text-red-600 dark:text-red-400">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />+ <span>{error}</span>+ </div>+ )}++ <SettingSection title={t('Software')}>+ <SettingRow title={t('Current version')} control={<CodeValue value={currentVersion} />} />+ <SettingRow+ title={t('Installation')}+ description={t(status?.installation.reason || 'How DeepTutor is installed here.')}+ control={+ <span className="text-[12.5px] text-[var(--foreground)]">+ {t(INSTALLATION_LABELS[installMode])}+ </span>+ }+ />+ <SettingRow+ title={t('Release channel')}+ description={t('Only stable, published DeepTutor releases are considered.')}+ control={<span className="text-[12.5px] text-[var(--foreground)]">{t('Stable')}</span>}+ />+ </SettingSection>++ <SettingSection+ title={t('Updates')}+ description={t(+ 'Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.'+ )}+ >+ <SettingRow+ title={t('Check for updates')}+ description={t('Turn this off for offline or controlled deployments.')}+ control={+ status?.is_admin ? (+ <Toggle+ checked={status?.check_enabled ?? true}+ disabled={loading || savingChecks || activeJob}+ onChange={enabled => void changeChecks(enabled)}+ />+ ) : (+ <span className="text-[12.5px] text-[var(--muted-foreground)]">+ {status?.check_enabled ? t('On') : t('Off')}+ </span>+ )+ }+ />+ <SettingRow+ title={t('Latest stable release')}+ description={+ checkedAt+ ? t('Last checked {{time}}', { time: checkedAt })+ : status?.check_enabled+ ? t('Not checked yet')+ : t('Version checks are disabled.')+ }+ control={+ <div className="flex items-center gap-2">+ {upToDate && <Check className="h-3.5 w-3.5 text-emerald-500" />}+ <CodeValue value={latestVersion ?? '—'} />+ </div>+ }+ />++ {status?.release?.migration_warning && (+ <div className="flex items-start gap-2 border-t border-[var(--border)]/50 py-3.5 text-[12.5px] leading-relaxed text-amber-700 dark:text-amber-400">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />+ {t(+ 'This release mentions migrations or breaking changes. Read the release notes before updating.'+ )}+ </div>+ )}++ {status?.release?.excerpt && (+ <div className="border-t border-[var(--border)]/50 py-4">+ <div className="mb-2 text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">+ {status.release.name || t('What changed')}+ </div>+ <p className="max-w-2xl whitespace-pre-line text-[12.5px] leading-6 text-[var(--muted-foreground)]">+ {status.release.excerpt}+ </p>+ </div>+ )}++ {status && !status.installation.automatic_update && (+ <div className="border-t border-[var(--border)]/50 py-4">+ <div className="mb-2 flex items-center gap-2 text-[12.5px] font-medium text-[var(--foreground)]">+ <ShieldCheck className="h-4 w-4 text-[var(--muted-foreground)]" />+ {t('Managed by your installation')}+ </div>+ <p className="mb-3 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(status.installation.reason)}+ </p>+ <code className="block overflow-x-auto rounded-lg bg-[var(--accent)]/60 px-3 py-2 text-[11.5px] text-[var(--foreground)]">+ {status.installation.command}+ </code>+ </div>+ )}++ {job && (+ <div className="border-t border-[var(--border)]/50 py-4" aria-live="polite">+ <div+ className={`flex items-center gap-2 text-[12.5px] font-medium ${jobTone(job.status)}`}+ >+ {updateJobIsActive(job.status) ? (+ <RotateCw className="h-3.5 w-3.5 animate-spin" />+ ) : job.status === 'succeeded' ? (+ <Check className="h-3.5 w-3.5" />+ ) : (+ <CircleAlert className="h-3.5 w-3.5" />+ )}+ {t(`updateJob.${job.status}`)}+ </div>+ {job.error && (+ <p className="mt-2 text-[12px] text-red-600 dark:text-red-400">{job.error}</p>+ )}+ </div>+ )}+ </SettingSection>++ <SettingSection title={t('Project')}>+ <ResourceRow+ title={t('GitHub')}+ description={t('Source code, issues, and contributions')}+ href="https://github.com/HKUDS/DeepTutor"+ icon={<Github className="h-4 w-4" />}+ />+ <ResourceRow+ title={t('Documentation')}+ description={t('Installation, configuration, and guides')}+ href="https://docs.deeptutor.info"+ icon={<ArrowUpRight className="h-4 w-4" />}+ />+ </SettingSection>++ <ConfirmDialog+ open={confirmOpen}+ title={t('Update and restart DeepTutor?')}+ confirmLabel={t('Update and restart')}+ busy={requesting}+ busyLabel={t('Preparing update…')}+ onConfirm={() => void update()}+ onCancel={() => setConfirmOpen(false)}+ >+ {t(+ 'DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.',+ { version: latestVersion ?? '' }+ )}+ </ConfirmDialog>+ </div>+ )+}++function CodeValue({ value }: { value: string }) {+ return (+ <code className="rounded-md bg-[var(--accent)]/60 px-2 py-1 text-[11.5px] tabular-nums text-[var(--foreground)]">+ {value}+ </code>+ )+}++function ResourceRow({+ title,+ description,+ href,+ icon,+}: {+ title: string+ description: string+ href: string+ icon: React.ReactNode+}) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ className="group flex items-center justify-between gap-5 border-t border-[var(--border)]/50 py-3.5 first:border-t-0"+ >+ <div>+ <div className="text-[13.5px] font-medium text-[var(--foreground)]">{title}</div>+ <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">{description}</p>+ </div>+ <span className="text-[var(--muted-foreground)] transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 group-hover:text-[var(--foreground)]">+ {icon}+ </span>+ </a>+ )+}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 21b2981da..21604d198 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -12,23 +12,8 @@ import {import { useParams, useRouter } from "next/navigation";import {- BarChart3,- BrainCircuit,- CircleHelp,- Clapperboard,- Code2,- Compass,- Database,- FileSearch,- Globe,GraduationCap,- Image as ImageIcon,- Lightbulb,- MessageSquare,- Microscope,PenLine,- Signpost,- Sparkles,type LucideIcon,} from "lucide-react";import { useTranslation } from "react-i18next";@@ -118,6 +103,13 @@ import {getEnabledOptionalTools,invalidateEnabledOptionalToolsCache,} from "@/lib/tools-settings";+import {+ ALL_TOOLS,+ CHAT_CAPABILITIES,+ VISIBLE_CHAT_CAPABILITIES,+ getChatCapability,+ type ToolName,+} from "@/lib/chat-capabilities";import { downloadChatMarkdown } from "@/lib/chat-export";import { buildChatOutline } from "@/lib/chat-outline";import { isPlaceholderSessionTitle } from "@/lib/session-title";@@ -200,171 +192,6 @@ const ResearchConfigPanel = dynamic(/* Type & data definitions *//* ------------------------------------------------------------------ */-type ToolName =- | "brainstorm"- | "geogebra_analysis"- | "web_search"- | "code_execution"- | "reason"- | "paper_search"- | "imagegen"- | "videogen";--interface ToolDef {- name: ToolName;- label: string;- icon: LucideIcon;-}--const ALL_TOOLS: ToolDef[] = [- { name: "brainstorm", label: "Brainstorm", icon: Lightbulb },- { name: "geogebra_analysis", label: "GeoGebra", icon: Compass },- { name: "web_search", label: "Web Search", icon: Globe },- { name: "code_execution", label: "Code", icon: Code2 },- { name: "reason", label: "Reason", icon: Sparkles },- { name: "paper_search", label: "Arxiv Search", icon: FileSearch },- { name: "imagegen", label: "Image Gen", icon: ImageIcon },- { name: "videogen", label: "Video Gen", icon: Clapperboard },-];--interface CapabilityDef {- value: string;- label: string;- description: string;- icon: LucideIcon;- allowedTools: ToolName[];- defaultTools: ToolName[];- /**- * Collapse this capability into the picker's "More" flyout instead of listing- * it directly.- *- * Purely about presentation — which handful of modes deserve to be one click- * away. It used to key off whether a capability ran on the chat agent loop,- * which conflated an implementation detail with menu order and meant the menu- * could not be reordered without lying about the engine.- */- secondary?: boolean;-- /**- * Keep this capability resolvable but stop offering it as a new choice.- *- * A capability that graduated into its own workspace still has sessions in- * people's history. Deleting the entry outright would make those sessions- * render under the wrong label while still sending the old capability to the- * server. So the definition stays — for naming and icons — and only the- * picker hides it.- */- legacy?: boolean;-}--const CAPABILITIES: CapabilityDef[] = [- {- value: "",- label: "Chat",- description: "Flexible conversation with any tool",- icon: MessageSquare,- allowedTools: [- "brainstorm",- "geogebra_analysis",- "web_search",- "code_execution",- "reason",- "paper_search",- "imagegen",- "videogen",- ],- defaultTools: [],- },- {- value: "deep_solve",- label: "Solve",- description: "Multi-step reasoning & problem solving",- icon: BrainCircuit,- allowedTools: ["web_search", "code_execution", "reason"],- defaultTools: ["web_search", "code_execution", "reason"],- secondary: true,- },- {- value: "ask_questions",- label: "Ask Questions",- description: "Let the model ask you questions to fill in missing context",- icon: CircleHelp,- allowedTools: [- "brainstorm",- "geogebra_analysis",- "web_search",- "code_execution",- "reason",- "paper_search",- "imagegen",- "videogen",- ],- defaultTools: [],- },- {- value: "deep_question",- label: "Quiz",- description: "Auto-validated question generation",- icon: PenLine,- allowedTools: ["web_search", "code_execution"],- defaultTools: ["web_search", "code_execution"],- },- {- value: "deep_research",- label: "Research",- description: "Comprehensive multi-agent research",- icon: Microscope,- allowedTools: ["web_search", "paper_search", "code_execution"],- defaultTools: ["web_search", "paper_search", "code_execution"],- secondary: true,- },- {- value: "visualize",- label: "Visualize",- description:- "Generate charts, diagrams, interactive pages, or math animations",- icon: BarChart3,- allowedTools: [],- defaultTools: [],- },- {- value: "course_study",- label: "Course Study",- description: "See where a course stands and what to do next",- icon: Signpost,- // The four course tools auto-mount server-side once the conversation- // belongs to a course; this mode orchestrates and hands off, so it keeps- // the ordinary tools for understanding a request well enough to route it.- allowedTools: ["web_search", "code_execution", "reason"],- defaultTools: [],- },- {- value: "mastery_path",- label: "Mastery Path",- description: "Mastery-based tutoring with a hard gate",- icon: GraduationCap,- // The mastery tools (status/quiz/grade/assess/build) auto-mount server-side- // when this capability is active; rag auto-mounts when a KB is attached.- // These are only the extra optional tools the tutor may also reach for.- allowedTools: ["web_search", "code_execution"],- defaultTools: [],- // Mastery Path is its own workspace now (/mastery). Started from- // here it had no topic to belong to, so `resolve_mastery_path_id` minted a- // path keyed by the session id — a learning path whose identity was an- // accident of whichever chat happened to open it, and whose map, review- // trail and evidence lived on a screen the learner was not looking at.- // Existing sessions keep working; the picker just no longer starts new ones.- legacy: true,- },-];--// Course Study hidden from the mode picker pending further product work; the-// entry stays in CAPABILITIES so a conversation already bound to it (e.g. via-// the course page's deep link) still resolves correctly.-const VISIBLE_CAPABILITIES = CAPABILITIES.filter(- (cap) => cap.value !== "course_study",-);-interface KnowledgeBase {name: string;is_default?: boolean;@@ -393,10 +220,6 @@ interface PendingAttachment {/* Helpers *//* ------------------------------------------------------------------ */-function getCapability(value: string | null): CapabilityDef {- return CAPABILITIES.find((c) => c.value === (value || "")) ?? CAPABILITIES[0];-}-/*** Read the context-window measurement a finished turn attached to its* `result` event. Scanned newest-first because one turn can emit several@@ -750,7 +573,7 @@ export default function ChatPage() {}, [handlePrefillComposer]);const activeCap = useMemo(- () => getCapability(state.activeCapability),+ () => getChatCapability(state.activeCapability),[state.activeCapability],);const isQuizMode = activeCap.value === "deep_question";@@ -1517,7 +1340,7 @@ export default function ChatPage() {const handleSelectCapability = useCallback((value: string) => {const cap =- CAPABILITIES.find((c) => c.value === value) ?? CAPABILITIES[0];+ CHAT_CAPABILITIES.find((c) => c.value === value) ?? CHAT_CAPABILITIES[0];const storageKey = cap.value || "chat";const config = resolveCapabilityPlaygroundConfig(capabilityConfigs,@@ -2606,7 +2429,7 @@ export default function ChatPage() {capabilityNeedsConfig={capabilityNeedsConfig}capabilityConfigConfirmed={capabilityConfigConfirmed}onRequestConfigConfirm={ensureActivityPanelOpen}- capabilities={VISIBLE_CAPABILITIES}+ capabilities={VISIBLE_CHAT_CAPABILITIES}onSetCapMenuOpen={setCapMenuOpen}onSetSpaceMenuOpen={setSpaceMenuOpen}onToggleKB={handleToggleKB}diff --git a/web/app/(workspace)/reading/layout.tsx b/web/app/(workspace)/reading/layout.tsxnew file mode 100644index 000000000..0094d7ddb--- /dev/null+++ b/web/app/(workspace)/reading/layout.tsx@@ -0,0 +1,20 @@+import { GeogebraTabProvider } from "@/context/GeogebraTabContext";+import { QuizFollowupProvider } from "@/context/QuizFollowupContext";+import { UnifiedChatProvider } from "@/context/UnifiedChatContext";++/**+ * Reading owns its conversation runtime. The workspace shell above also hosts+ * Home's provider so Home can keep a turn alive while navigation occurs, but a+ * reader must never render that provider's transcript or live stream.+ */+export default function ReadingLayout({+ children,+}: Readonly<{ children: React.ReactNode }>) {+ return (+ <UnifiedChatProvider>+ <QuizFollowupProvider>+ <GeogebraTabProvider>{children}</GeogebraTabProvider>+ </QuizFollowupProvider>+ </UnifiedChatProvider>+ );+}diff --git a/web/components/chat/home/ChatViewerBridges.tsx b/web/components/chat/home/ChatViewerBridges.tsxnew file mode 100644index 000000000..bd2e3ebbb--- /dev/null+++ b/web/components/chat/home/ChatViewerBridges.tsx@@ -0,0 +1,34 @@+"use client";++import { useEffect } from "react";++import type { SessionViewerPanelHandle } from "@/components/chat/home/SessionViewerPanel";+import { useGeogebraTabOpener } from "@/context/GeogebraTabContext";+import { useQuizFollowupController } from "@/context/QuizFollowupContext";++/** Connect in-message Quiz/GeoGebra actions to a surface's shared viewer. */+export function ChatViewerBridges({+ viewerPanelRef,+}: {+ viewerPanelRef: React.MutableRefObject<SessionViewerPanelHandle | null>;+}) {+ const quiz = useQuizFollowupController();+ const geogebra = useGeogebraTabOpener();++ useEffect(() => {+ quiz.setOpenTabHandler((context) => {+ viewerPanelRef.current?.openQuizFollowupTab(context);+ });+ return () => quiz.setOpenTabHandler(null);+ }, [quiz, viewerPanelRef]);++ useEffect(() => {+ if (!geogebra) return;+ geogebra.setOpenHandler((payload) => {+ viewerPanelRef.current?.openGeogebraTab(payload);+ });+ return () => geogebra.setOpenHandler(null);+ }, [geogebra, viewerPanelRef]);++ return null;+}diff --git a/web/components/chat/home/StandaloneComposer.tsx b/web/components/chat/home/StandaloneComposer.tsxindex 3b76a276f..7a237b6d9 100644--- a/web/components/chat/home/StandaloneComposer.tsx+++ b/web/components/chat/home/StandaloneComposer.tsx@@ -47,6 +47,23 @@ import type { SelectedRecord } from "@/lib/notebook-selection-types";import type { SpaceMemoryFile } from "@/lib/space-items";import { getSubagentSettings } from "@/lib/subagents-api";import type { LLMSelection } from "@/lib/unified-ws";+import {+ DEFAULT_QUIZ_CONFIG,+ buildQuizWSConfig,+ type DeepQuestionFormConfig,+} from "@/lib/quiz-types";+import {+ DEFAULT_VISUALIZE_CONFIG,+ buildVisualizeWSConfig,+ type VisualizeFormConfig,+} from "@/lib/visualize-types";+import {+ buildResearchWSConfig,+ createEmptyResearchConfig,+ validateResearchConfig,+ type DeepResearchFormConfig,+} from "@/lib/research-types";+import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"),@@ -70,6 +87,22 @@ const BookReferencePicker = dynamic(() => import("@/components/chat/BookReferencePicker"),{ ssr: false },);+const CapabilityConfigCard = dynamic(+ () => import("@/components/chat/home/CapabilityConfigCard"),+ { ssr: false },+);+const QuizConfigPanel = dynamic(+ () => import("@/components/quiz/QuizConfigPanel"),+ { ssr: false },+);+const VisualizeConfigPanel = dynamic(+ () => import("@/components/visualize/VisualizeConfigPanel"),+ { ssr: false },+);+const ResearchConfigPanel = dynamic(+ () => import("@/components/research/ResearchConfigPanel"),+ { ssr: false },+);interface PendingAttachment {type: string;@@ -83,6 +116,8 @@ interface PendingAttachment {/** Everything the user attached to this send, already in wire shape. */export interface StandaloneComposerSubmission {content: string;+ /** Configuration for Quiz, Visualize, or Research. */+ config?: Record<string, unknown>;attachments: Array<{type: string;filename?: string;@@ -201,6 +236,18 @@ function StandaloneComposerImpl({const [dragging, setDragging] = useState(false);const [capMenuOpen, setCapMenuOpen] = useState(false);const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);+ const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({+ ...DEFAULT_QUIZ_CONFIG,+ });+ const [quizPdf, setQuizPdf] = useState<File | null>(null);+ const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({+ ...DEFAULT_VISUALIZE_CONFIG,+ });+ const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(+ createEmptyResearchConfig(),+ );+ const [capabilityConfigConfirmed, setCapabilityConfigConfirmed] =+ useState(false);const [ownKnowledgeBases, setOwnKnowledgeBases] = useState<string[]>([]);const selectedKnowledgeBases = controlledKnowledgeBases ?? ownKnowledgeBases;@@ -625,8 +672,41 @@ function StandaloneComposerImpl({[notebookReferencesPayload, selectedNotebookRecords],);+ const resolvedCapabilities = useMemo(() => {+ const list = capabilities?.length ? capabilities : [CHAT_ONLY_CAPABILITY];+ return list.map((capability) => ({+ ...capability,+ label: t(capability.label),+ description: t(capability.description),+ }));+ }, [capabilities, t]);+ const activeCap =+ resolvedCapabilities.find((capability) => capability.value === activeCapValue) ??+ resolvedCapabilities[0];+ const isQuizMode = activeCap.value === "deep_question";+ const isVisualizeMode = activeCap.value === "visualize";+ const isResearchMode = activeCap.value === "deep_research";+ const capabilityNeedsConfig = workspaceActionNeedsConfiguration(activeCap.value);+ const researchValidation = useMemo(+ () => validateResearchConfig(researchConfig),+ [researchConfig],+ );+ const quizValidationErrors =+ quizConfig.mode === "mimic" && !quizPdf+ ? [t("Upload a PDF to mimic its question style.")]+ : [];++ const selectCapability = useCallback(+ (value: string) => {+ setCapabilityConfigConfirmed(false);+ setCapMenuOpen(false);+ onSelectCapability?.(value);+ },+ [onSelectCapability],+ );+const handleSend = useCallback(- (content: string) => {+ async (content: string) => {if (isStreaming && !awaitingUserReply) return;const hasReferences =attachments.length > 0 ||@@ -638,14 +718,38 @@ function StandaloneComposerImpl({selectedMemoryFiles.length > 0;if (!content.trim() && !hasReferences) return;+ let config: Record<string, unknown> | undefined;+ let outgoingAttachments = attachments.map((attachment) => ({+ type: attachment.type,+ filename: attachment.filename,+ base64: attachment.base64,+ mime_type: attachment.mimeType,+ }));+ if (isQuizMode) {+ config = buildQuizWSConfig(quizConfig);+ if (quizConfig.mode === "mimic" && quizPdf) {+ const raw = await readFileAsDataUrl(quizPdf);+ outgoingAttachments = [+ ...outgoingAttachments,+ {+ type: "pdf",+ filename: quizPdf.name,+ base64: extractBase64FromDataUrl(raw),+ mime_type: "application/pdf",+ },+ ];+ }+ } else if (isVisualizeMode) {+ config = buildVisualizeWSConfig(visualizeConfig);+ } else if (isResearchMode) {+ if (!researchValidation.valid) return;+ config = buildResearchWSConfig(researchConfig);+ }+onSubmit({content,- attachments: attachments.map((a) => ({- type: a.type,- filename: a.filename,- base64: a.base64,- mime_type: a.mimeType,- })),+ config,+ attachments: outgoingAttachments,knowledgeBases: selectedKnowledgeBases,notebookReferences: notebookReferencesPayload,historyReferences: selectedHistorySessions.map((s) => s.sessionId),@@ -671,9 +775,16 @@ function StandaloneComposerImpl({attachments,awaitingUserReply,isStreaming,+ isQuizMode,+ isResearchMode,+ isVisualizeMode,llmSelection,notebookReferencesPayload,onSubmit,+ quizConfig,+ quizPdf,+ researchConfig,+ researchValidation.valid,selectedAgent,selectedBookReferences,selectedHistorySessions,@@ -683,23 +794,72 @@ function StandaloneComposerImpl({selectedPersona,selectedQuestionEntries,subagentBudget,+ visualizeConfig,],);- const resolvedCapabilities = useMemo(() => {- const list = capabilities?.length ? capabilities : [CHAT_ONLY_CAPABILITY];- return list.map((cap) => ({- ...cap,- label: t(cap.label),- description: t(cap.description),- }));- }, [capabilities, t]);- const activeCap =- resolvedCapabilities.find((cap) => cap.value === activeCapValue) ??- resolvedCapabilities[0];+ const capabilityConfigSection = capabilityNeedsConfig ? (+ <div className="mx-auto mb-2 w-full max-w-[720px] px-3">+ {isQuizMode ? (+ <CapabilityConfigCard+ capability="deep_question"+ confirmed={capabilityConfigConfirmed}+ canConfirm={quizValidationErrors.length === 0}+ validationErrors={quizValidationErrors}+ onConfirm={() => setCapabilityConfigConfirmed(true)}+ >+ <QuizConfigPanel+ value={quizConfig}+ onChange={(next) => {+ setQuizConfig(next);+ setCapabilityConfigConfirmed(false);+ }}+ uploadedPdf={quizPdf}+ onUploadPdf={(file) => {+ setQuizPdf(file);+ setCapabilityConfigConfirmed(false);+ }}+ />+ </CapabilityConfigCard>+ ) : isVisualizeMode ? (+ <CapabilityConfigCard+ capability="visualize"+ confirmed={capabilityConfigConfirmed}+ canConfirm+ onConfirm={() => setCapabilityConfigConfirmed(true)}+ >+ <VisualizeConfigPanel+ value={visualizeConfig}+ onChange={(next) => {+ setVisualizeConfig(next);+ setCapabilityConfigConfirmed(false);+ }}+ />+ </CapabilityConfigCard>+ ) : (+ <CapabilityConfigCard+ capability="deep_research"+ confirmed={capabilityConfigConfirmed}+ canConfirm={researchValidation.valid}+ validationErrors={Object.values(researchValidation.errors)}+ onConfirm={() => setCapabilityConfigConfirmed(true)}+ >+ <ResearchConfigPanel+ value={researchConfig}+ errors={researchValidation.errors}+ onChange={(next) => {+ setResearchConfig(next);+ setCapabilityConfigConfirmed(false);+ }}+ />+ </CapabilityConfigCard>+ )}+ </div>+ ) : null;return (<>+ {capabilityConfigSection}<ChatComposercomposerRef={composerRef}capMenuRef={capMenuRef}@@ -740,10 +900,10 @@ function StandaloneComposerImpl({selectedKnowledgeBases={selectedKbOnly}isStreaming={isStreaming}awaitingUserReply={awaitingUserReply}- isVisualizeMode={false}- capabilityNeedsConfig={false}- capabilityConfigConfirmed={true}- onRequestConfigConfirm={() => {}}+ isVisualizeMode={isVisualizeMode}+ capabilityNeedsConfig={capabilityNeedsConfig}+ capabilityConfigConfirmed={capabilityConfigConfirmed}+ onRequestConfigConfirm={() => setCapabilityConfigConfirmed(false)}capabilities={resolvedCapabilities}onSetCapMenuOpen={setCapMenuOpen}onSetSpaceMenuOpen={setSpaceMenuOpen}@@ -772,7 +932,7 @@ function StandaloneComposerImpl({onDrop={handleDrop}onPaste={handlePaste}onAddFiles={handleAddFiles}- onSelectCapability={onSelectCapability ?? (() => {})}+ onSelectCapability={selectCapability}showCapabilityChip={showCapabilityChip}onCancelStreaming={onCancelStreaming}prefillInputRef={prefillInputRef}diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsxindex 50291e538..504ddd47d 100644--- a/web/components/reading/workspace/ReadingCompanion.tsx+++ b/web/components/reading/workspace/ReadingCompanion.tsx@@ -39,14 +39,19 @@ import { useTranslation } from "react-i18next";import { ChatMessageList } from "@/components/chat/home/ChatMessages";import { buildSessionActivity } from "@/components/chat/home/SessionActivityPanel";-import SessionViewerPanel from "@/components/chat/home/SessionViewerPanel";+import SessionViewerPanel, {+ type SessionViewerPanelHandle,+} from "@/components/chat/home/SessionViewerPanel";+import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";import Tooltip from "@/components/common/Tooltip";import { useUnifiedChat } from "@/context/UnifiedChatContext";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";+import { useResearchOutlineContinuation } from "@/hooks/useResearchOutlineContinuation";import { buildChatOutline } from "@/lib/chat-outline";import { downloadChatMarkdown } from "@/lib/chat-export";import { setReadingViewport } from "@/lib/reading-turn-state";+import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";import {fetchReadingAskHint,fetchReadingOpeners,@@ -113,18 +118,31 @@ export function ReadingCompanion({editMessage,switchBranch,} = useUnifiedChat();+ const confirmResearchOutline = useResearchOutlineContinuation();const [showSessions, setShowSessions] = useState(false);const [menuOpen, setMenuOpen] = useState(false);const [menuView, setMenuView] = useState<MenuView>("actions");const [showSaveModal, setShowSaveModal] = useState(false);const [viewerOpen, setViewerOpen] = useState(false);+ const viewerPanelRef = useRef<SessionViewerPanelHandle | null>(null);const closeMenu = useCallback(() => {setMenuOpen(false);setMenuView("actions");}, []);+ const handleWelcomeAction = useCallback(+ (prompt: string) => {+ if (workspaceActionNeedsConfiguration(state.activeCapability)) {+ prefillInputRef.current?.(prompt);+ return;+ }+ onQuickPrompt(prompt);+ },+ [onQuickPrompt, prefillInputRef, state.activeCapability],+ );+/* ── Transcript scrolling ────────────────────────────────────────────The pin-to-bottom hook /home uses. The companion used to be a bare`overflow-y-auto`, so a streaming reply grew below the fold while the@@ -530,12 +548,13 @@ export function ReadingCompanion({onEditMessage={editMessage}onSwitchBranch={switchBranch}onSubmitUserReply={submitUserReply}+ onConfirmOutline={confirmResearchOutline}showModeBadge={false}/>) : (<CompanionWelcometitle={material?.title ?? ""}- onAction={onQuickPrompt}+ onAction={handleWelcomeAction}suggestions={openers}/>)}@@ -594,12 +613,14 @@ export function ReadingCompanion({the companion rather than squeezing it: at this width a third columnwould leave nothing readable. */}<SessionViewerPanel+ ref={viewerPanelRef}open={viewerOpen}sessionId={state.sessionId}activity={sessionActivity}onClose={() => setViewerOpen(false)}onAutoOpen={() => setViewerOpen(true)}/>+ <ChatViewerBridges viewerPanelRef={viewerPanelRef} /></aside>);}diff --git a/web/components/reading/workspace/ReadingComposer.tsx b/web/components/reading/workspace/ReadingComposer.tsxindex 91912d34c..7edec26d4 100644--- a/web/components/reading/workspace/ReadingComposer.tsx+++ b/web/components/reading/workspace/ReadingComposer.tsx@@ -18,6 +18,7 @@ import StandaloneComposer, {type StandaloneComposerSubmission,} from "@/components/chat/home/StandaloneComposer";import { useUnifiedChat } from "@/context/UnifiedChatContext";+import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";import { hasPendingAskUser } from "@/lib/ask-user-state";import { setReadingViewport } from "@/lib/reading-turn-state";@@ -49,6 +50,11 @@ export function ReadingComposer({setLLMSelection,setPersonaSelection,} = useUnifiedChat();+ const {+ capabilities,+ activeCapabilityValue,+ selectCapability,+ } = useWorkspaceChatActions();const awaitingUserReply = hasPendingAskUser(state.messages[state.messages.length - 1]?.events,@@ -82,8 +88,11 @@ export function ReadingComposer({// How many times the companion may consult the selected agent this// turn. Absent when no agent is picked, which is the ordinary case.submission.subagentBudget- ? { subagent_consult_budget: submission.subagentBudget }- : undefined,+ ? {+ ...(submission.config ?? {}),+ subagent_consult_budget: submission.subagentBudget,+ }+ : submission.config,submission.notebookReferences,historyReferences,{ bookReferences: submission.bookReferences },@@ -106,9 +115,10 @@ export function ReadingComposer({return (<StandaloneComposer- // The active material is named in the header above; a capability chip- // here would only repeat it.- showCapabilityChip={false}+ capabilities={capabilities}+ activeCapValue={activeCapabilityValue}+ onSelectCapability={selectCapability}+ showCapabilityChiphasMessages={state.messages.length > 0}isStreaming={state.isStreaming}awaitingUserReply={awaitingUserReply}diff --git a/web/components/reading/workspace/useReadingWorkspace.ts b/web/components/reading/workspace/useReadingWorkspace.tsindex 829174c18..48fa78f75 100644--- a/web/components/reading/workspace/useReadingWorkspace.ts+++ b/web/components/reading/workspace/useReadingWorkspace.ts@@ -12,9 +12,9 @@ import {type ReaderActionPayload,} from "@/lib/reading-reader-action";import {- READING_CAPABILITY,setReadingWorkspace,} from "@/lib/reading-turn-state";+import { READING_WORKSPACE_MODE } from "@/lib/workspace-mode";import {activateReadingMaterial,deleteReadingConversation,@@ -50,8 +50,7 @@ export function useReadingWorkspace(useReading();const {state,- setCapability,- setTools,+ configureSession,loadSession,newSession,cancelStreamingTurn,@@ -100,13 +99,16 @@ export function useReadingWorkspace(useEffect(() => {setReadingWorkspace(workspaceId);- setCapability(READING_CAPABILITY);- setTools(["web_search", "reason"]);return () => {setReadingWorkspace(null);closeMaterial();};- }, [closeMaterial, setCapability, setTools, workspaceId]);+ }, [closeMaterial, workspaceId]);++ const sessionConfiguration = useMemo(+ () => ({ workspaceMode: READING_WORKSPACE_MODE }),+ [],+ );const activeTab = useMemo(() =>@@ -186,9 +188,12 @@ export function useReadingWorkspace(// the backend attaches the session to this workspace when the first// turn runs (see `turn_runtime`), so opening a collection and walking// away no longer litters it with empty conversations.- if (sessionIdParam) await loadSession(sessionIdParam);- else newSession();- setCapability(READING_CAPABILITY);+ if (sessionIdParam) {+ await loadSession(sessionIdParam);+ configureSession(sessionConfiguration, sessionIdParam);+ } else {+ newSession({ ...sessionConfiguration, capability: null });+ }} catch (caught) {setError(caught instanceof Error@@ -198,11 +203,12 @@ export function useReadingWorkspace(}})();}, [+ configureSession,loadSession,loading,newSession,sessionIdParam,- setCapability,+ sessionConfiguration,t,workspace,workspaceId,@@ -320,9 +326,9 @@ export function useReadingWorkspace(const newConversation = useCallback(() => {if (!workspace) return;cancelStreamingTurn();- newSession();+ newSession({ ...sessionConfiguration, capability: null });router.push(`/reading/${workspace.workspace_id}`);- }, [cancelStreamingTurn, newSession, router, workspace]);+ }, [cancelStreamingTurn, newSession, router, sessionConfiguration, workspace]);// When the first turn assigns a session id, put it in the URL and let the// conversation menu see the row the backend just attached. Mirrors the@@ -355,20 +361,27 @@ export function useReadingWorkspace(setConversations(await listReadingConversations(workspaceId));if (sessionId === sessionIdParam) {cancelStreamingTurn();- newSession();+ newSession({ ...sessionConfiguration, capability: null });router.push(`/reading/${workspaceId}`);}},- [cancelStreamingTurn, newSession, router, sessionIdParam, workspaceId],+ [+ cancelStreamingTurn,+ newSession,+ router,+ sessionConfiguration,+ sessionIdParam,+ workspaceId,+ ],);const openConversation = useCallback(async (sessionId: string) => {router.push(`/reading/${workspaceId}/${sessionId}`);await loadSession(sessionId);- setCapability(READING_CAPABILITY);+ configureSession(sessionConfiguration, sessionId);},- [loadSession, router, setCapability, workspaceId],+ [configureSession, loadSession, router, sessionConfiguration, workspaceId],);const organizeNotes = useCallback(async () => {diff --git a/web/components/settings/ModelCards.tsx b/web/components/settings/ModelCards.tsxindex 59d0a1bc4..2df4e5de9 100644--- a/web/components/settings/ModelCards.tsx+++ b/web/components/settings/ModelCards.tsx@@ -1,13 +1,6 @@"use client";-import {- ArrowLeft,- Check,- ChevronDown,- ChevronRight,- Plus,- Trash2,-} from "lucide-react";+import { Check, ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";import { useTranslation } from "react-i18next";import ProviderIcon from "@/components/common/ProviderIcon";@@ -75,35 +68,6 @@ export function CardGrid({ children }: { children: React.ReactNode }) {);}-export function BackRow({- label,- current,- onBack,-}: {- label: string;- current: string;- onBack: () => void;-}) {- return (- <div className="mb-4 flex items-center gap-1.5 text-[12px]">- <button- type="button"- onClick={onBack}- className="inline-flex items-center gap-1 rounded-md py-0.5 pr-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"- >- <ArrowLeft className="h-3.5 w-3.5" />- {label}- </button>- <span aria-hidden className="text-[var(--muted-foreground)]/40">- /- </span>- <span className="min-w-0 truncate font-medium text-[var(--foreground)]">- {current}- </span>- </div>- );-}-export function AddCard({label,onClick,@@ -202,9 +166,11 @@ function NameRow({onRenameCommit: () => void;onRenameCancel: () => void;onRenameStart: () => void;- expanded: boolean;- onToggleExpand: () => void;- expandLabel: string;+ /** Absent when this card has nothing to expand in place (e.g. a provider+ * card, which opens a dialog instead). */+ expanded?: boolean;+ onToggleExpand?: () => void;+ expandLabel?: string;}) {if (renaming) {return (@@ -237,26 +203,28 @@ function NameRow({>{name}</span>- <button- type="button"- aria-label={expandLabel}- aria-expanded={expanded}- onClick={(event) => {- event.stopPropagation();- onToggleExpand();- }}- className="-mr-1 -mt-0.5 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"- >- <ChevronDown- className={`h-3.5 w-3.5 transition-transform ${expanded ? "rotate-180" : ""}`}- />- </button>+ {onToggleExpand && (+ <button+ type="button"+ aria-label={expandLabel}+ aria-expanded={expanded}+ onClick={(event) => {+ event.stopPropagation();+ onToggleExpand();+ }}+ className="-mr-1 -mt-0.5 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ <ChevronDown+ className={`h-3.5 w-3.5 transition-transform ${expanded ? "rotate-180" : ""}`}+ />+ </button>+ )}</div>);}/** "In use" is stated; everything else offers to become it. */-function UseRow({+export function UseRow({inUse,onUse,detail,@@ -296,7 +264,7 @@ export function ProfileCard({profile,service,inUse,- expanded,+ open,renaming,renameValue,onRenameChange,@@ -304,22 +272,21 @@ export function ProfileCard({onRenameCancel,onRenameStart,onOpen,- onToggleExpand,onUse,}: {profile: CatalogProfile;service: ServiceName;inUse: boolean;- expanded: boolean;+ /** Whether this card's dialog is currently open — a purely visual cue,+ * distinct from `inUse` (which provider is actually running). */+ open: boolean;renaming: boolean;renameValue: string;onRenameChange: (value: string) => void;onRenameCommit: () => void;onRenameCancel: () => void;onRenameStart: () => void;- /** Absent for search, which has no models to drill into. */- onOpen?: () => void;- onToggleExpand: () => void;+ onOpen: () => void;onUse: () => void;}) {const { t } = useTranslation();@@ -329,7 +296,7 @@ export function ProfileCard({const count = profile.models.length;return (- <CardShell expanded={expanded} inUse={inUse} onOpen={onOpen}>+ <CardShell expanded={open} inUse={inUse} onOpen={onOpen}><NameRowicon={<ProviderIcon provider={provider} size={15} className="mt-0.5" />}name={profile.name}@@ -339,16 +306,13 @@ export function ProfileCard({onRenameCommit={onRenameCommit}onRenameCancel={onRenameCancel}onRenameStart={onRenameStart}- expanded={expanded}- onToggleExpand={onToggleExpand}- expandLabel={t("Edit connection")}/><div className="min-w-0"><p className="truncate font-mono text-[10.5px] text-[var(--muted-foreground)]/80">{endpoint || t("Provider default endpoint")}</p></div>- <div className={onOpen ? "pr-5" : ""}>+ <div className="pr-5"><UseRowinUse={inUse}onUse={onUse}diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex 1c239a5e8..27976d2a4 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -4,14 +4,12 @@ import { useCallback, useEffect, useRef, useState } from "react";import Link from "next/link";import {ArrowUpRight,- ArrowLeft,CheckCircle2,ChevronDown,Eye,EyeOff,Info,Loader2,- Pencil,Plus,RefreshCw,Terminal,@@ -20,7 +18,9 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";+import Modal from "@/components/common/Modal";import ProviderIcon from "@/components/common/ProviderIcon";+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";import { apiFetch, apiUrl } from "@/lib/api";import {reasoningEffortOptions,@@ -46,12 +46,12 @@ import {import { DimensionField } from "./DimensionField";import {AddCard,- BackRow,CardAction,CardGrid,ModelCard,ProfileCard,SectionHead,+ UseRow,} from "./ModelCards";import { nextProfileName } from "./profile-naming";import { searchProviderFields } from "./search-providers";@@ -109,25 +109,19 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {// ── Browsing vs using ───────────────────────────────────────────────────//- // A page opens on its providers. Opening one drills into its models;- // expanding one edits its connection in place. Neither adopts it — "in use"- // is now a separate, deliberate act, which is what lets you look at a+ // The page always shows its providers. Opening one pops a dialog with its+ // connection fields and its models; nothing in that dialog adopts it — "in+ // use" is a separate, deliberate act, which is what lets you look at a// provider you are not currently running on without switching to it.const [openProfileId, setOpenProfileId] = useState<string | null>(null);- const [expandedProfileId, setExpandedProfileId] = useState<string | null>(- null,- );const [expandedModelId, setExpandedModelId] = useState<string | null>(null);const openedProfile =profiles.find((item) => item.id === openProfileId) ?? null;- const expandedProfile =- profiles.find((item) => item.id === expandedProfileId) ?? null;// Whatever the field editors below are pointed at. Falling back to the// profile in use keeps every reference working before anything is opened.- const activeProfile =- openedProfile ?? expandedProfile ?? getActiveProfile(draft, service);+ const activeProfile = openedProfile ?? getActiveProfile(draft, service);const activeModel = openedProfile? ((expandedModelId? openedProfile.models.find((item) => item.id === expandedModelId)@@ -179,19 +173,14 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {activeProfile,);- // Arriving from Settings > Connections with ?profile=<id>: open on the- // profile that link was aimed at instead of whichever one happens to be- // selected. Selecting a profile in this editor is also what puts it in use,- // so the switch is announced with a one-click way back rather than done- // quietly — the click asked to see a provider, not to adopt it.+ // Arriving from Settings > Connections with ?profile=<id>: open that+ // provider's dialog directly. It used to have to *adopt* the profile to+ // show it, because selecting and using were the same act — with the two+ // separated, following the link costs nothing and needs no warning.//// The query is read from `window.location` rather than `useSearchParams()`// so no settings page needs a Suspense boundary for something that only// exists after hydration.- // Arriving from Settings > Connections with ?profile=<id>: open that- // provider's connection panel. It used to have to *adopt* the profile to- // show it, because selecting and using were the same act — with the two- // separated, following the link costs nothing and needs no warning.const deepLinkHandled = useRef(false);useEffect(() => {if (deepLinkHandled.current) return;@@ -207,11 +196,13 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {deepLinkHandled.current = true;// Drop the query so a refresh does not re-open something already closed.window.history.replaceState(null, "", window.location.pathname);- setExpandedProfileId(requested);+ setOpenProfileId(requested);}, [profiles]);const [showApiKey, setShowApiKey] = useState(false);- const [confirmingProfileDelete, setConfirmingProfileDelete] = useState(false);+ const [deletingProfile, setDeletingProfile] = useState<CatalogProfile | null>(+ null,+ );const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);const [editingModelId, setEditingModelId] = useState<string | null>(null);const [editingModelName, setEditingModelName] = useState("");@@ -228,8 +219,6 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {if (lastProfileKey !== profileKey) {setLastProfileKey(profileKey);if (showApiKey) setShowApiKey(false);- // A pending confirmation must not carry over to a different profile.- if (confirmingProfileDelete) setConfirmingProfileDelete(false);}const searchProviderRaw =@@ -429,169 +418,117 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {<div data-tour={`tour-${service}`} className="space-y-5">{activeProfile ? (<div>- {/* ── Level 1: the providers configured for this service ──────────- A card is a place, not a switch: opening one drills into its- models, the chevron edits its connection in place, and- neither one changes which provider the app is running on.- That is what "In use" is for. */}- {!openedProfile && (- <>- <SectionHead- title={t("Providers")}- action={- <CardAction onClick={() => addProfile(service)}>- <Plus className="h-3 w-3" />- {t("Add provider")}- </CardAction>+ {/* ── The providers configured for this service ──────────────────+ A card is a place, not a switch: opening one pops a dialog+ with its connection fields and its models, and nothing in+ there changes which provider the app is running on. That+ is what "In use" is for. */}+ <SectionHead+ title={t("Providers")}+ action={+ <CardAction onClick={() => addProfile(service)}>+ <Plus className="h-3 w-3" />+ {t("Add provider")}+ </CardAction>+ }+ />+ <CardGrid>+ {profiles.map((profile) => (+ <ProfileCard+ key={profile.id}+ profile={profile}+ service={service}+ inUse={profile.id === inUseProfileId}+ open={profile.id === openProfileId}+ renaming={editingProfileId === profile.id}+ renameValue={editingProfileName}+ onRenameChange={setEditingProfileName}+ onRenameCommit={() => commitProfileRename(profile.id)}+ onRenameCancel={cancelProfileRename}+ onRenameStart={() => startProfileRename(profile)}+ onOpen={() => {+ setOpenProfileId(profile.id);+ setExpandedModelId(+ profile.id === inUseProfileId+ ? (inUseModelId ?? null)+ : (profile.models[0]?.id ?? null),+ );+ }}+ onUse={() =>+ mutateCatalog((next) => {+ next.services[service].active_profile_id = profile.id;+ if (service !== "search") {+ next.services[service].active_model_id =+ profile.models[0]?.id ?? null;+ }+ })}/>- <CardGrid>- {profiles.map((profile) => (- <ProfileCard- key={profile.id}- profile={profile}- service={service}- inUse={profile.id === inUseProfileId}- expanded={profile.id === expandedProfileId}- renaming={editingProfileId === profile.id}- renameValue={editingProfileName}- onRenameChange={setEditingProfileName}- onRenameCommit={() => commitProfileRename(profile.id)}- onRenameCancel={cancelProfileRename}- onRenameStart={() => startProfileRename(profile)}- onOpen={- service === "search"- ? undefined- : () => {- setOpenProfileId(profile.id);- setExpandedProfileId(null);- setExpandedModelId(- profile.id === inUseProfileId- ? (inUseModelId ?? null)- : (profile.models[0]?.id ?? null),- );- }- }- onToggleExpand={() => {- setExpandedProfileId(- profile.id === expandedProfileId ? null : profile.id,- );- }}- onUse={() =>- mutateCatalog((next) => {- next.services[service].active_profile_id = profile.id;- if (service !== "search") {- next.services[service].active_model_id =- profile.models[0]?.id ?? null;- }- })- }- />- ))}- <AddCard- label={t("Add provider")}- onClick={() => addProfile(service)}- />- </CardGrid>- </>- )}+ ))}+ <AddCard+ label={t("Add provider")}+ onClick={() => addProfile(service)}+ />+ </CardGrid>- {/* ── Level 2: the models under one provider ─────────────────── */}+ {/* ── One provider, in a dialog: its connection, then its models ── */}{openedProfile && (- <>- <BackRow- label={t("All providers")}- current={openedProfile.name}- onBack={() => {- setOpenProfileId(null);- setExpandedModelId(null);- }}- />- <SectionHead- title={t("Models")}- action={- <span className="flex items-center gap-2">- {service === "llm" &&- openedProfile.binding === "codebuddy" && (- <CardAction- onClick={() => void syncProviderModels()}- disabled={modelsSyncing}- >- <RefreshCw- className={`h-3 w-3 ${modelsSyncing ? "animate-spin" : ""}`}- />- {t("Sync models")}- </CardAction>- )}- <CardAction- onClick={() => addModel(service, openedProfile.id)}- >- <Plus className="h-3 w-3" />- {t("Add model")}- </CardAction>- </span>- }- />- <CardGrid>- {openedProfile.models.map((model, index) => (- <ModelCard- key={model.id}- model={model}- service={service}- language={language}- index={index}- inUse={- openedProfile.id === inUseProfileId &&- model.id === inUseModelId- }- expanded={model.id === expandedModelId}- renaming={editingModelId === model.id}- renameValue={editingModelName}- onRenameChange={setEditingModelName}- onRenameCommit={() => commitModelRename(model.id)}- onRenameCancel={cancelModelRename}- onRenameStart={() => startModelRename(model)}- onToggleExpand={() =>- setExpandedModelId(- model.id === expandedModelId ? null : model.id,- )- }- onUse={() =>- mutateCatalog((next) => {- next.services[service].active_profile_id =- openedProfile.id;- next.services[service].active_model_id = model.id;- })- }- onDelete={() =>- removeActiveModel(service, openedProfile.id, model.id)- }- />- ))}- <AddCard- label={t("Add model")}- onClick={() => addModel(service, openedProfile.id)}+ <Modal+ isOpen+ onClose={() => {+ setOpenProfileId(null);+ setExpandedModelId(null);+ }}+ title={openedProfile.name}+ titleIcon={+ <ProviderIcon+ provider={+ service === "search"+ ? openedProfile.provider || ""+ : openedProfile.binding || ""+ }+ size={15}/>- </CardGrid>- </>- )}-- <div className="mt-7 min-w-0 space-y-7">- {expandedProfile && !openedProfile && (- <div className="mt-4">- <div className="mb-2.5 flex items-center justify-between gap-2 border-b border-[var(--border)]/60 pb-2">- <div className="text-[13px] font-medium text-[var(--foreground)]">- {t("Provider connection")}- </div>+ }+ width="lg"+ footer={+ <div className="flex items-center justify-between gap-3"><buttontype="button"- onClick={() => setExpandedProfileId(null)}- className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ onClick={() => setDeletingProfile(openedProfile)}+ className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12.5px] text-red-500/80 transition-colors hover:bg-red-500/10 hover:text-red-500">- <X className="h-3 w-3" />- {t("Close")}+ <Trash2 className="h-3.5 w-3.5" />+ {t("Delete provider")}+ </button>+ <button+ type="button"+ onClick={() => {+ setOpenProfileId(null);+ setExpandedModelId(null);+ }}+ className="rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12.5px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40"+ >+ {t("Done")}</button></div>+ }+ >+ <div className="space-y-6 p-5">+ <UseRow+ inUse={openedProfile.id === inUseProfileId}+ onUse={() =>+ mutateCatalog((next) => {+ next.services[service].active_profile_id =+ openedProfile.id;+ if (service !== "search") {+ next.services[service].active_model_id =+ openedProfile.models[0]?.id ?? null;+ }+ })+ }+ />+<ProfileFieldsservice={service}profile={activeProfile}@@ -641,28 +578,106 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {}}}/>- </div>- )}- {service !== "search" && openedProfile && (- <div>- {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (- <div className="mb-2.5 flex items-center justify-between gap-2 border-b border-[var(--border)]/60 pb-2">- <div className="min-w-0 truncate text-[13px] font-medium text-[var(--foreground)]">- {(activeModel.name || "").trim() || t("Model")}+ {service !== "search" && (+ <div>+ <SectionHead+ title={t("Models")}+ action={+ <span className="flex items-center gap-2">+ {service === "llm" &&+ openedProfile.binding === "codebuddy" && (+ <CardAction+ onClick={() => void syncProviderModels()}+ disabled={modelsSyncing}+ >+ <RefreshCw+ className={`h-3 w-3 ${modelsSyncing ? "animate-spin" : ""}`}+ />+ {t("Sync models")}+ </CardAction>+ )}+ <CardAction+ onClick={() => addModel(service, openedProfile.id)}+ >+ <Plus className="h-3 w-3" />+ {t("Add model")}+ </CardAction>+ </span>+ }+ />+ {/* Capped at 2 columns rather than the page grid's+ `xl:grid-cols-3` — that breakpoint reads the browser+ viewport, not this dialog's fixed width, and would+ force 3 columns into a 600px box on a large screen. */}+ <div className="grid gap-2.5 sm:grid-cols-2">+ {openedProfile.models.map((model, index) => (+ <ModelCard+ key={model.id}+ model={model}+ service={service}+ language={language}+ index={index}+ inUse={+ openedProfile.id === inUseProfileId &&+ model.id === inUseModelId+ }+ expanded={model.id === expandedModelId}+ renaming={editingModelId === model.id}+ renameValue={editingModelName}+ onRenameChange={setEditingModelName}+ onRenameCommit={() => commitModelRename(model.id)}+ onRenameCancel={cancelModelRename}+ onRenameStart={() => startModelRename(model)}+ onToggleExpand={() =>+ setExpandedModelId(+ model.id === expandedModelId ? null : model.id,+ )+ }+ onUse={() =>+ mutateCatalog((next) => {+ next.services[service].active_profile_id =+ openedProfile.id;+ next.services[service].active_model_id =+ model.id;+ })+ }+ onDelete={() =>+ removeActiveModel(+ service,+ openedProfile.id,+ model.id,+ )+ }+ />+ ))}+ <AddCard+ label={t("Add model")}+ onClick={() => addModel(service, openedProfile.id)}+ /></div>- <button- type="button"- onClick={() => setExpandedModelId(null)}- className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"- >- <X className="h-3 w-3" />- {t("Close")}- </button></div>)}- {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (- <div className="grid gap-4 sm:grid-cols-2">++ {service !== "search" && (+ <div>+ {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (+ <div className="mb-2.5 flex items-center justify-between gap-2 border-b border-[var(--border)]/60 pb-2">+ <div className="min-w-0 truncate text-[13px] font-medium text-[var(--foreground)]">+ {(activeModel.name || "").trim() || t("Model")}+ </div>+ <button+ type="button"+ onClick={() => setExpandedModelId(null)}+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ >+ <X className="h-3 w-3" />+ {t("Close")}+ </button>+ </div>+ )}+ {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (+ <div className="grid gap-4 sm:grid-cols-2">{!isCodexOAuth && (<div><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">@@ -954,7 +969,11 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {)}</div>)}+ </div>+ </Modal>+ )}+ <div className="mt-7 min-w-0">{/* ── Diagnostics — per-service, inline ── */}<div className="border-t border-[var(--border)]/60"><div className="flex items-center justify-between py-2.5">@@ -1032,6 +1051,37 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {</CardGrid></div>)}++ {deletingProfile && (+ <ConfirmDialog+ open+ title={t("Delete this provider?")}+ tone="danger"+ confirmLabel={t("Delete")}+ onConfirm={() => {+ removeActiveProfile(service, deletingProfile.id);+ setDeletingProfile(null);+ setOpenProfileId(null);+ setExpandedModelId(null);+ }}+ onCancel={() => setDeletingProfile(null)}+ >+ {deletingProfile.id === inUseProfileId+ ? t(+ "This is your active {{service}} provider — deleting it switches to {{next}}.",+ {+ service: t(SERVICE_LABEL[service]),+ next:+ profiles.find((item) => item.id !== deletingProfile.id)+ ?.name ?? t("nothing configured"),+ },+ )+ : t(+ "This removes {{count}} model(s) and its saved credentials. This can't be undone.",+ { count: deletingProfile.models.length },+ )}+ </ConfirmDialog>+ )}</div>);}diff --git a/web/components/sidebar/VersionBadge.tsx b/web/components/sidebar/VersionBadge.tsxindex 10e0b4811..7ad049ac4 100644--- a/web/components/sidebar/VersionBadge.tsx+++ b/web/components/sidebar/VersionBadge.tsx@@ -1,5 +1,7 @@"use client";+import Link from "next/link";+import { normalizeVersionTag } from "@/lib/version";interface VersionBadgeProps {@@ -7,8 +9,6 @@ interface VersionBadgeProps {collapsed?: boolean;}-const RELEASES_URL = "https://github.com/HKUDS/DeepTutor/releases";-export function VersionBadge({ collapsed = false }: VersionBadgeProps) {// Keep the collapsed sidebar entirely free of version chrome.if (collapsed) return null;@@ -17,16 +17,14 @@ export function VersionBadge({ collapsed = false }: VersionBadgeProps) {const displayTag = tag ?? "—";return (- <a- href={RELEASES_URL}- target="_blank"- rel="noreferrer noopener"+ <Link+ href="/settings/about"title={displayTag}className="group/ver flex min-w-0 flex-1 items-center rounded-lg px-3 py-1.5 text-[11px] font-mono tabular-nums tracking-tight text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"><span className="truncate leading-none decoration-[var(--muted-foreground)]/40 decoration-dotted underline-offset-[3px] group-hover/ver:underline">{displayTag}</span>- </a>+ </Link>);}diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsxindex b5fa9115d..b5cf376f3 100644--- a/web/components/space/learning/MasteryComposer.tsx+++ b/web/components/space/learning/MasteryComposer.tsx@@ -18,6 +18,7 @@ import StandaloneComposer, {type StandaloneComposerSubmission,} from "@/components/chat/home/StandaloneComposer";import { useUnifiedChat } from "@/context/UnifiedChatContext";+import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";import { hasPendingAskUser } from "@/lib/ask-user-state";export function MasteryComposer({@@ -43,6 +44,11 @@ export function MasteryComposer({setLLMSelection,setPersonaSelection,} = useUnifiedChat();+ const {+ capabilities,+ activeCapabilityValue,+ selectCapability,+ } = useWorkspaceChatActions();// A turn paused on an ask_user card is still "streaming", but typing an// answer is exactly how it moves forward — the composer stays live.@@ -67,8 +73,11 @@ export function MasteryComposer({// How many times the tutor may consult the selected agent this turn.// Absent when no agent is picked, which is the ordinary case.submission.subagentBudget- ? { subagent_consult_budget: submission.subagentBudget }- : undefined,+ ? {+ ...(submission.config ?? {}),+ subagent_consult_budget: submission.subagentBudget,+ }+ : submission.config,submission.notebookReferences,submission.historyReferences,{ bookReferences: submission.bookReferences },@@ -82,9 +91,10 @@ export function MasteryComposer({return (<StandaloneComposer- // No capability chip: this screen only ever runs the mastery tutor and- // says so in its own header, so a picker that cannot pick is noise.- showCapabilityChip={false}+ capabilities={capabilities}+ activeCapValue={activeCapabilityValue}+ onSelectCapability={selectCapability}+ showCapabilityChiphasMessages={state.messages.length > 0}isStreaming={state.isStreaming}awaitingUserReply={awaitingUserReply}diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsxindex 42c0b3469..4f4e77548 100644--- a/web/components/space/learning/MasteryStudy.tsx+++ b/web/components/space/learning/MasteryStudy.tsx@@ -8,18 +8,26 @@ import {Loader2,Map as MapIcon,MessageCircle,+ PanelRight,Sparkles,} from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { ChatMessageList } from "@/components/chat/home/ChatMessages";+import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";+import { buildSessionActivity } from "@/components/chat/home/SessionActivityPanel";+import SessionViewerPanel, {+ type SessionViewerPanelHandle,+} from "@/components/chat/home/SessionViewerPanel";import { useUnifiedChat } from "@/context/UnifiedChatContext";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useMasteryStudySession } from "@/hooks/useMasteryStudySession";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";+import { useResearchOutlineContinuation } from "@/hooks/useResearchOutlineContinuation";import { fetchMasteryAskHint, type MasteryTopic } from "@/lib/learning-api";import { consumePendingPrompt } from "@/lib/pending-prompt";+import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";import { topicDisplayName, type Translate } from "./format";import { LevelUpCelebration } from "./LevelUpCelebration";@@ -76,10 +84,14 @@ export function MasteryStudy({editMessage,switchBranch,} = useUnifiedChat();+ const confirmResearchOutline = useResearchOutlineContinuation();const { topic, topicError, knowledgeBases, sessionError, sessionLoading } =useMasteryStudySession(pathId, routeSessionId);const hasMessages = state.messages.length > 0;const prefillInputRef = useRef<((text: string) => void) | null>(null);+ const viewerPanelRef = useRef<SessionViewerPanelHandle | null>(null);+ const [viewerOpen, setViewerOpen] = useState(false);+ const sessionActivity = buildSessionActivity(state.messages);/* ── Transcript scrolling ────────────────────────────────────────────Was a bare `scrollIntoView` keyed on message count — no notion of theuser having scrolled away, so it yanked the view back to the bottom@@ -226,6 +238,17 @@ export function MasteryStudy({[sendMessage, sessionError, sessionLoading, state.isStreaming],);+ const startFromPrompt = useCallback(+ (prompt: string) => {+ if (workspaceActionNeedsConfiguration(state.activeCapability)) {+ prefillInputRef.current?.(prompt);+ return;+ }+ submit(prompt);+ },+ [state.activeCapability, submit],+ );+const copyAssistantMessage = useCallback(async (content: string) => {if (content.trim()) await navigator.clipboard.writeText(content);}, []);@@ -295,6 +318,15 @@ export function MasteryStudy({</div><div className="flex shrink-0 items-center gap-1.5 pl-2">+ <button+ type="button"+ onClick={() => setViewerOpen((open) => !open)}+ className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"+ aria-label={t("Activity")}+ aria-pressed={viewerOpen}+ >+ <PanelRight className="h-4 w-4" />+ </button><ProgressRingvalue={total ? completed / total : 0}size={18}@@ -391,7 +423,7 @@ export function MasteryStudy({<buttonkey={starter.key}type="button"- onClick={() => submit(label)}+ onClick={() => startFromPrompt(label)}disabled={state.isStreaming || sessionLoading}className="group rounded-lg border border-[var(--border)] bg-[var(--card)] p-4 text-left transition hover:-translate-y-0.5 hover:border-[var(--primary)]/35 disabled:opacity-50">@@ -418,6 +450,7 @@ export function MasteryStudy({onEditMessage={editMessage}onSwitchBranch={switchBranch}onSubmitUserReply={submitUserReply}+ onConfirmOutline={confirmResearchOutline}availableKbNames={new Set(knowledgeBases)}showModeBadge={false}/>@@ -451,6 +484,15 @@ export function MasteryStudy({onDone={() => setCelebration(null)}/>)}+ <SessionViewerPanel+ ref={viewerPanelRef}+ open={viewerOpen}+ sessionId={state.sessionId}+ activity={sessionActivity}+ onClose={() => setViewerOpen(false)}+ onAutoOpen={() => setViewerOpen(true)}+ />+ <ChatViewerBridges viewerPanelRef={viewerPanelRef} /></main>);}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex b4647c7b2..b0eba6c8c 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -51,6 +51,10 @@ import {normalizeBookReferences,type BookReferencePayload,} from "@/lib/book-references";+import {+ normalizeWorkspaceMode,+ type WorkspaceMode,+} from "@/lib/workspace-mode";type SessionRuntimeStatus =| "idle"@@ -95,6 +99,8 @@ export interface ChatState {sessionTitle: string;enabledTools: string[];activeCapability: string | null;+ /** Stable product surface; per-turn capability selection is orthogonal. */+ workspaceMode: WorkspaceMode | null;knowledgeBases: string[];llmSelection: LLMSelection | null;/** Persistent mastery state associated with this conversation. */@@ -117,6 +123,7 @@ export interface ChatState {export interface SessionConfiguration {capability?: string | null;+ workspaceMode?: WorkspaceMode | null;knowledgeBases?: string[];masteryPathId?: string | null;courseId?: string;@@ -152,6 +159,7 @@ export interface MessageAttachment {export interface MessageRequestSnapshot {content: string;capability?: string | null;+ workspaceMode?: WorkspaceMode | null;enabledTools: string[];knowledgeBases: string[];language: string;@@ -208,6 +216,7 @@ interface SessionSnapshot {status?: SessionRuntimeStatus;tools?: string[];capability?: string | null;+ workspaceMode?: WorkspaceMode | null;knowledgeBases?: string[];llmSelection?: LLMSelection | null;masteryPathId?: string | null;@@ -300,6 +309,7 @@ function createSessionEntry(sessionTitle: "",enabledTools: [],activeCapability: null,+ workspaceMode: null,knowledgeBases: [],llmSelection: null,masteryPathId: null,@@ -353,6 +363,10 @@ function applySessionConfiguration(configuration.capability !== undefined? configuration.capability: session.activeCapability,+ workspaceMode:+ configuration.workspaceMode !== undefined+ ? configuration.workspaceMode+ : session.workspaceMode,knowledgeBases:configuration.knowledgeBases !== undefined? [...configuration.knowledgeBases]@@ -724,6 +738,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {action.capability !== undefined? action.capability: existing.activeCapability,+ workspaceMode:+ action.workspaceMode !== undefined+ ? action.workspaceMode+ : existing.workspaceMode,knowledgeBases: action.knowledgeBases ?? existing.knowledgeBases,llmSelection:action.llmSelection !== undefined@@ -1089,6 +1107,10 @@ function hydrateRequestSnapshot(typeof stored.capability === "string"? stored.capability: message.capability || "",+ workspaceMode: normalizeWorkspaceMode(+ stored.workspaceMode ?? stored.workspace_mode,+ stored.capability ?? message.capability,+ ),enabledTools: asStringArray(stored.enabledTools),knowledgeBases: asStringArray(stored.knowledgeBases),language: typeof stored.language === "string" ? stored.language : "en",@@ -1500,6 +1522,10 @@ export function UnifiedChatProvider({if (!local || local.isStreaming || local.status === "running") return;}const messages = hydrateMessages(session.messages ?? []);+ const loadedWorkspaceMode = normalizeWorkspaceMode(+ session.preferences?.workspace_mode,+ session.preferences?.capability,+ );dispatch({type: options?.revalidate ? "REVALIDATE_SESSION" : "LOAD_SESSION",key,@@ -1513,7 +1539,14 @@ export function UnifiedChatProvider({tools: Array.isArray(session.preferences?.tools)? session.preferences.tools: [],- capability: session.preferences?.capability || null,+ // Old sessions stored Reading/Mastery as the capability itself. Once+ // 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+ ? null+ : session.preferences?.capability || null,+ workspaceMode: loadedWorkspaceMode,knowledgeBases: Array.isArray(session.preferences?.knowledge_bases)? session.preferences.knowledge_bases: [],@@ -1678,6 +1711,8 @@ export function UnifiedChatProvider({const replaySnapshot = options?.requestSnapshotOverride;const effectiveCapability =replaySnapshot?.capability ?? session.activeCapability;+ const effectiveWorkspaceMode =+ replaySnapshot?.workspaceMode ?? session.workspaceMode;const effectiveTools =replaySnapshot?.enabledTools ?? session.enabledTools;const effectiveKnowledgeBases =@@ -1718,6 +1753,7 @@ export function UnifiedChatProvider({const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {content,capability: effectiveCapability,+ workspaceMode: effectiveWorkspaceMode,enabledTools: [...effectiveTools],knowledgeBases: [...effectiveKnowledgeBases],language: effectiveLanguage,@@ -1796,6 +1832,7 @@ export function UnifiedChatProvider({content,tools: effectiveTools,capability: effectiveCapability,+ workspace_mode: effectiveWorkspaceMode ?? "",knowledge_bases: effectiveKnowledgeBases,session_id: session.sessionId,attachments: effectiveAttachments,@@ -1817,12 +1854,12 @@ export function UnifiedChatProvider({...(effectiveMasteryPathId? { mastery_path_id: effectiveMasteryPathId }: {}),- // Immersive reading. Gated on the capability as well as on an open- // document: the reader outlives both a mode switch and a new session, so- // without the capability check every later turn would still carry it.+ // Immersive reading. Gated on the stable workspace mode as well as on+ // an open document: the reader outlives action switches and new+ // sessions, so Home must never inherit its source context.// Read from a module cell rather than context state so scrolling the// reader never re-renders the chat.- ...readingTurnFields(effectiveCapability),+ ...readingTurnFields(effectiveWorkspaceMode),// Always sent (possibly ""): an explicit key is the backend's signal// to persist the value into session.preferences — "" clears back to// Default. Omitting the key would make the backend fall back to the@@ -1947,6 +1984,7 @@ export function UnifiedChatProvider({sessionTitle: current.sessionTitle,enabledTools: current.enabledTools,activeCapability: current.activeCapability,+ workspaceMode: current.workspaceMode,knowledgeBases: current.knowledgeBases,llmSelection: current.llmSelection,masteryPathId: current.masteryPathId,diff --git a/web/hooks/useMasteryStudySession.ts b/web/hooks/useMasteryStudySession.tsindex ddaa8339f..78e894533 100644--- a/web/hooks/useMasteryStudySession.ts+++ b/web/hooks/useMasteryStudySession.ts@@ -18,6 +18,7 @@ import {isMasteryDraftSessionReady,type MasteryDraftRouteGuard,} from "@/lib/mastery-study-route";+import { MASTERY_WORKSPACE_MODE } from "@/lib/workspace-mode";/*** Resolves which topic and which chat session a study route is showing.@@ -88,7 +89,8 @@ export function useMasteryStudySession();const sessionConfiguration = useMemo<SessionConfiguration>(() => ({- capability: "mastery_path",+ workspaceMode: MASTERY_WORKSPACE_MODE,+ capability: null,masteryPathId: pathId,knowledgeBases,}),diff --git a/web/hooks/useResearchOutlineContinuation.ts b/web/hooks/useResearchOutlineContinuation.tsnew file mode 100644index 000000000..615a6ee62--- /dev/null+++ b/web/hooks/useResearchOutlineContinuation.ts@@ -0,0 +1,52 @@+"use client";++import { useCallback } from "react";++import {+ type MessageRequestSnapshot,+ useUnifiedChat,+} from "@/context/UnifiedChatContext";+import type { OutlineItem } from "@/lib/research-types";++/** Resume Deep Research after its editable outline, on any chat surface. */+export function useResearchOutlineContinuation() {+ const { sendMessage } = useUnifiedChat();+ return useCallback(+ (+ outline: OutlineItem[],+ topic: string,+ originalConfig?: Record<string, unknown> | null,+ originalSnapshot?: MessageRequestSnapshot | null,+ ) => {+ const config: Record<string, unknown> = {+ ...(originalConfig ?? {}),+ confirmed_outline: outline,+ };+ const requestSnapshotOverride = originalSnapshot+ ? {+ ...originalSnapshot,+ content: topic,+ capability: "deep_research",+ config,+ }+ : undefined;+ sendMessage(+ topic,+ originalSnapshot?.attachments ?? [],+ config,+ originalSnapshot?.notebookReferences,+ originalSnapshot?.historyReferences,+ {+ displayUserMessage: false,+ persistUserMessage: false,+ requestSnapshotOverride,+ bookReferences: originalSnapshot?.bookReferences,+ },+ originalSnapshot?.questionNotebookReferences,+ originalSnapshot?.persona,+ originalSnapshot?.memoryReferences,+ );+ },+ [sendMessage],+ );+}diff --git a/web/hooks/useWorkspaceChatActions.ts b/web/hooks/useWorkspaceChatActions.tsnew file mode 100644index 000000000..554fa6910--- /dev/null+++ b/web/hooks/useWorkspaceChatActions.ts@@ -0,0 +1,78 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";++import { useUnifiedChat } from "@/context/UnifiedChatContext";+import {+ WORKSPACE_CHAT_CAPABILITIES,+ getChatCapability,+} from "@/lib/chat-capabilities";+import { getEnabledOptionalTools } from "@/lib/tools-settings";++/** Keep Reading/Mastery action selection on the same tool policy as Home. */+export function useWorkspaceChatActions() {+ const { state, setCapability, setTools } = useUnifiedChat();+ const [enabledOptionalTools, setEnabledOptionalTools] = useState<+ string[] | null+ >(null);++ const activeValue = WORKSPACE_CHAT_CAPABILITIES.some(+ (capability) => capability.value === (state.activeCapability || ""),+ )+ ? state.activeCapability || ""+ : "";+ const activeCapability = useMemo(+ () => getChatCapability(activeValue),+ [activeValue],+ );++ useEffect(() => {+ let cancelled = false;+ void getEnabledOptionalTools()+ .then((tools) => {+ if (!cancelled) setEnabledOptionalTools(tools);+ })+ .catch(() => {+ if (!cancelled) setEnabledOptionalTools([]);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ useEffect(() => {+ if (enabledOptionalTools === null) return;+ const allowed = new Set<string>(activeCapability.allowedTools);+ const next = enabledOptionalTools.filter((tool) => allowed.has(tool));+ const same =+ next.length === state.enabledTools.length &&+ next.every((tool, index) => tool === state.enabledTools[index]);+ if (!same) setTools(next);+ }, [+ activeCapability.allowedTools,+ enabledOptionalTools,+ setTools,+ state.enabledTools,+ ]);++ const selectCapability = useCallback(+ (value: string) => {+ const selected = WORKSPACE_CHAT_CAPABILITIES.find(+ (capability) => capability.value === value,+ );+ const next = selected ?? WORKSPACE_CHAT_CAPABILITIES[0];+ setCapability(next.value || null);+ if (enabledOptionalTools !== null) {+ const allowed = new Set<string>(next.allowedTools);+ setTools(enabledOptionalTools.filter((tool) => allowed.has(tool)));+ }+ },+ [enabledOptionalTools, setCapability, setTools],+ );++ return {+ capabilities: WORKSPACE_CHAT_CAPABILITIES,+ activeCapabilityValue: activeValue,+ selectCapability,+ };+}diff --git a/web/lib/app-update.ts b/web/lib/app-update.tsnew file mode 100644index 000000000..c2ff16cfc--- /dev/null+++ b/web/lib/app-update.ts@@ -0,0 +1,110 @@+import { apiFetch, apiUrl } from '@/lib/api'++export type InstallMode = 'pypi' | 'source' | 'docker' | 'unknown'+export type UpdateJobStatus =+ 'pending' | 'handoff' | 'running' | 'restarting' | 'succeeded' | 'failed'++export interface UpdateRelease {+ version: string+ name: string+ published_at: string+ url: string+ excerpt: string+ migration_warning: boolean+}++export interface UpdateJob {+ id: string+ status: UpdateJobStatus+ current_version: string+ target_version: string+ created_at: string+ started_at: string | null+ finished_at: string | null+ error: string | null+ restart_count: number+}++export interface AppUpdateStatus {+ current_version: string+ check_enabled: boolean+ checked_at: string+ cached: boolean+ check_error: string+ update_available: boolean+ release: UpdateRelease | null+ installation: {+ mode: InstallMode+ automatic_update: boolean+ command: string+ reason: string+ }+ launcher_managed: boolean+ is_admin: boolean+ job: UpdateJob | null+}++async function responseError(response: Response): Promise<Error> {+ try {+ const payload = (await response.json()) as { detail?: unknown }+ if (typeof payload.detail === 'string') return new Error(payload.detail)+ } catch {+ // Fall through to the status-only message for non-JSON responses.+ }+ return new Error(`Update request failed (HTTP ${response.status})`)+}++async function readStatus(response: Response): Promise<AppUpdateStatus> {+ if (!response.ok) throw await responseError(response)+ return (await response.json()) as AppUpdateStatus+}++export async function fetchAppUpdateStatus(signal?: AbortSignal): Promise<AppUpdateStatus> {+ return readStatus(+ await apiFetch(apiUrl('/api/v1/system/update'), {+ cache: 'no-store',+ signal,+ })+ )+}++export async function checkAppUpdate(): Promise<AppUpdateStatus> {+ return readStatus(+ await apiFetch(apiUrl('/api/v1/system/update/check'), {+ method: 'POST',+ })+ )+}++export async function setAppUpdateChecks(enabled: boolean): Promise<AppUpdateStatus> {+ return readStatus(+ await apiFetch(apiUrl('/api/v1/system/update/settings'), {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ enabled }),+ })+ )+}++export async function requestAppUpdate(): Promise<UpdateJob> {+ const response = await apiFetch(apiUrl('/api/v1/system/update'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ confirmation: 'update-and-restart' }),+ })+ if (!response.ok) throw await responseError(response)+ return (await response.json()) as UpdateJob+}++export async function fetchAppUpdateJob(signal?: AbortSignal): Promise<UpdateJob | null> {+ const response = await apiFetch(apiUrl('/api/v1/system/update/job'), {+ cache: 'no-store',+ signal,+ })+ if (!response.ok) throw await responseError(response)+ return (await response.json()) as UpdateJob | null+}++export function updateJobIsActive(status: UpdateJobStatus): boolean {+ return ['pending', 'handoff', 'running', 'restarting'].includes(status)+}diff --git a/web/lib/chat-capabilities.ts b/web/lib/chat-capabilities.tsnew file mode 100644index 000000000..18cfb1f27--- /dev/null+++ b/web/lib/chat-capabilities.ts@@ -0,0 +1,162 @@+import {+ BarChart3,+ BrainCircuit,+ CircleHelp,+ Clapperboard,+ Code2,+ Compass,+ FileSearch,+ Globe,+ GraduationCap,+ Image as ImageIcon,+ Lightbulb,+ MessageSquare,+ Microscope,+ PenLine,+ Signpost,+ Sparkles,+ type LucideIcon,+} from "lucide-react";++import type { CapabilityDef } from "@/components/chat/home/ChatComposer";++export type ToolName =+ | "brainstorm"+ | "geogebra_analysis"+ | "web_search"+ | "code_execution"+ | "reason"+ | "paper_search"+ | "imagegen"+ | "videogen";++export interface ToolDef {+ name: ToolName;+ label: string;+ icon: LucideIcon;+}++export const ALL_TOOLS: ToolDef[] = [+ { name: "brainstorm", label: "Brainstorm", icon: Lightbulb },+ { name: "geogebra_analysis", label: "GeoGebra", icon: Compass },+ { name: "web_search", label: "Web Search", icon: Globe },+ { name: "code_execution", label: "Code", icon: Code2 },+ { name: "reason", label: "Reason", icon: Sparkles },+ { name: "paper_search", label: "Arxiv Search", icon: FileSearch },+ { name: "imagegen", label: "Image Gen", icon: ImageIcon },+ { name: "videogen", label: "Video Gen", icon: Clapperboard },+];++export interface ChatCapabilityDef extends CapabilityDef {+ allowedTools: ToolName[];+ defaultTools: ToolName[];+ /** Historical capability that remains resolvable but is not newly offered. */+ legacy?: boolean;+}++/** Authoritative capability catalog shared by Home and learning workspaces. */+export const CHAT_CAPABILITIES: ChatCapabilityDef[] = [+ {+ value: "",+ label: "Chat",+ description: "Flexible conversation with any tool",+ icon: MessageSquare,+ allowedTools: [+ "brainstorm",+ "geogebra_analysis",+ "web_search",+ "code_execution",+ "reason",+ "paper_search",+ "imagegen",+ "videogen",+ ],+ defaultTools: [],+ },+ {+ value: "deep_solve",+ label: "Solve",+ description: "Multi-step reasoning & problem solving",+ icon: BrainCircuit,+ allowedTools: ["web_search", "code_execution", "reason"],+ defaultTools: ["web_search", "code_execution", "reason"],+ secondary: true,+ },+ {+ value: "ask_questions",+ label: "Ask Questions",+ description: "Let the model ask you questions to fill in missing context",+ icon: CircleHelp,+ allowedTools: [+ "brainstorm",+ "geogebra_analysis",+ "web_search",+ "code_execution",+ "reason",+ "paper_search",+ "imagegen",+ "videogen",+ ],+ defaultTools: [],+ },+ {+ value: "deep_question",+ label: "Quiz",+ description: "Auto-validated question generation",+ icon: PenLine,+ allowedTools: ["web_search", "code_execution"],+ defaultTools: ["web_search", "code_execution"],+ },+ {+ value: "deep_research",+ label: "Research",+ description: "Comprehensive multi-agent research",+ icon: Microscope,+ allowedTools: ["web_search", "paper_search", "code_execution"],+ defaultTools: ["web_search", "paper_search", "code_execution"],+ secondary: true,+ },+ {+ value: "visualize",+ label: "Visualize",+ description:+ "Generate charts, diagrams, interactive pages, or math animations",+ icon: BarChart3,+ allowedTools: [],+ defaultTools: [],+ },+ {+ value: "course_study",+ label: "Course Study",+ description: "See where a course stands and what to do next",+ icon: Signpost,+ allowedTools: ["web_search", "code_execution", "reason"],+ defaultTools: [],+ },+ {+ value: "mastery_path",+ label: "Mastery Path",+ description: "Mastery-based tutoring with a hard gate",+ icon: GraduationCap,+ allowedTools: ["web_search", "code_execution"],+ defaultTools: [],+ legacy: true,+ },+];++export const VISIBLE_CHAT_CAPABILITIES = CHAT_CAPABILITIES.filter(+ (capability) => capability.value !== "course_study",+);++/** Actions offered inside Reading and Mastery; workspace identity is separate. */+export const WORKSPACE_CHAT_CAPABILITIES = CHAT_CAPABILITIES.filter(+ (capability) =>+ capability.value !== "course_study" && capability.value !== "mastery_path",+);++export function getChatCapability(value: string | null): ChatCapabilityDef {+ return (+ CHAT_CAPABILITIES.find((capability) => capability.value === (value || "")) ??+ CHAT_CAPABILITIES[0]+ );+}diff --git a/web/lib/mastery-session.ts b/web/lib/mastery-session.tsindex 97b67a284..b033e552e 100644--- a/web/lib/mastery-session.ts+++ b/web/lib/mastery-session.ts@@ -8,10 +8,10 @@* If those two ever disagreed, a conversation would render under a topic and* then navigate somewhere else — so the rule lives here and neither owns it.*- * Both signals are required. `capability` says the last turn actually ran the- * mastery tutor, and `mastery_path_id` says which path it ran against; a- * session that switched capability mid-conversation keeps the stale id, and a- * course-study conversation about a path carries neither.+ * Workspace mode and path id are both required. The capability is now a+ * per-turn action (Chat, Quiz, Research, ...), so it must not decide which+ * product surface owns the conversation. Legacy sessions that predate+ * `workspace_mode` still fall back to their old capability value.** Immersive Reading conversations answer the same question with their own* pair of signals, and land on their collection instead. They are here rather@@ -25,7 +25,11 @@ import type { SessionSummary } from "@/lib/session-api";export function masteryPathIdOf(session: SessionSummary): string {const preferences = session.preferences;if (!preferences) return "";- if (preferences.capability !== "mastery_path") return "";+ if (+ preferences.workspace_mode !== "mastery_path" &&+ preferences.capability !== "mastery_path"+ )+ return "";return String(preferences.mastery_path_id || "");}@@ -40,7 +44,11 @@ export function masteryPathIdOf(session: SessionSummary): string {export function readingWorkspaceIdOf(session: SessionSummary): string {const preferences = session.preferences;if (!preferences) return "";- if (preferences.session_kind !== "immersive_reading") return "";+ if (+ preferences.workspace_mode !== "immersive_reading" &&+ preferences.session_kind !== "immersive_reading"+ )+ return "";return String(preferences.reading_workspace_id || "");}diff --git a/web/lib/reading-turn-state.ts b/web/lib/reading-turn-state.tsindex eab0196a3..1be971284 100644--- a/web/lib/reading-turn-state.ts+++ b/web/lib/reading-turn-state.ts@@ -10,8 +10,14 @@* Written by the reader pane; read by the chat's turn builder.*/-/** The capability value the composer sends for immersive reading. */-export const READING_CAPABILITY = "immersive_reading";+import {+ READING_WORKSPACE_MODE,+ type WorkspaceMode,+} from "@/lib/workspace-mode";++/** Backward-compatible name for callers that still label the old capability. */+export const READING_CAPABILITY = READING_WORKSPACE_MODE;+export { READING_WORKSPACE_MODE };export interface ReadingTurnState {workspaceId: string | null;@@ -78,8 +84,9 @@ export function getReadingTurnState(): ReadingTurnState {/*** Turn fields to merge into a `start_turn` payload.*- * Empty unless the turn is *actually* an immersive-reading turn — the caller- * passes the capability it is about to send, and anything else gets nothing.+ * Empty unless the conversation belongs to the immersive-reading workspace.+ * The per-turn action is deliberately irrelevant: Research and Visualize need+ * the same open document and viewport that Chat and Solve receive.** Both halves of that condition are load-bearing. The open document lives in a* provider mounted in the workspace layout so it survives the remount that@@ -89,7 +96,9 @@ export function getReadingTurnState(): ReadingTurnState {* would open with "I see you're reading …" and cite pages from a document the* user had moved on from.*/-export function readingTurnFields(capability: string | null | undefined): {+export function readingTurnFields(+ workspaceMode: WorkspaceMode | null | undefined,+): {reading_workspace_id?: string;reading_material_id?: string;reading_viewport?: {@@ -98,7 +107,7 @@ export function readingTurnFields(capability: string | null | undefined): {time_seconds?: number;};} {- if (capability !== READING_CAPABILITY) return {};+ if (workspaceMode !== READING_WORKSPACE_MODE) return {};const viewport: {locator?: number;selection?: string;diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 4f5343b7f..dfb803122 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -29,6 +29,8 @@ export interface SessionMessage {export interface SessionPreferences {capability?: string;+ /** Stable learning surface, independent of the action used for a turn. */+ workspace_mode?: "immersive_reading" | "mastery_path" | "";tools?: string[];knowledge_bases?: string[];language?: string;diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex 8dd18c307..0e1cb0a0c 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -10,6 +10,7 @@ import {Database,FileScan,Image as ImageIcon,+ Info,KeyRound,Library,ListChecks,@@ -390,13 +391,26 @@ export const SETTINGS_CATEGORIES: SettingsCategory[] = [icon: BrainCircuit,href: "/settings/memory",},+ {+ key: "about",+ label: { zh: "关于", en: "About" },+ blurb: {+ zh: "版本、更新与项目资源",+ en: "Version, updates, and project resources",+ },+ icon: Info,+ href: "/settings/about",+ },];export const SETTINGS_HUB_HREF = "/settings";const HUB_LABEL: Lang = { zh: "设置", en: "Settings" };/** Routes that are pure navigation (the hub) — no Save/Apply toolbar. */-const NAV_ONLY_ROUTES = new Set<string>([SETTINGS_HUB_HREF]);+const NAV_ONLY_ROUTES = new Set<string>([+ SETTINGS_HUB_HREF,+ "/settings/about",+]);export function isNavOnlyRoute(pathname: string): boolean {return NAV_ONLY_ROUTES.has(pathname);diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 693f0f93d..bd0a959cf 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -54,6 +54,8 @@ export interface StartTurnMessage {content: string;tools?: string[];capability?: string | null;+ /** Stable product surface; capability remains the action for this turn. */+ workspace_mode?: "immersive_reading" | "mastery_path" | "";knowledge_bases?: string[];session_id?: string | null;attachments?: {diff --git a/web/lib/workspace-mode.ts b/web/lib/workspace-mode.tsnew file mode 100644index 000000000..61838e304--- /dev/null+++ b/web/lib/workspace-mode.ts@@ -0,0 +1,33 @@+export type WorkspaceMode = "immersive_reading" | "mastery_path";++export const READING_WORKSPACE_MODE = "immersive_reading" as const;+export const MASTERY_WORKSPACE_MODE = "mastery_path" as const;++const CONFIGURED_WORKSPACE_ACTIONS = new Set([+ "deep_question",+ "visualize",+ "deep_research",+]);++/** Actions whose prompt must wait for the learner to confirm their settings. */+export function workspaceActionNeedsConfiguration(+ value: string | null | undefined,+): boolean {+ return CONFIGURED_WORKSPACE_ACTIONS.has(value ?? "");+}++export function normalizeWorkspaceMode(+ value: unknown,+ legacyCapability?: unknown,+): WorkspaceMode | null {+ if (value === READING_WORKSPACE_MODE || value === MASTERY_WORKSPACE_MODE) {+ return value;+ }+ if (+ legacyCapability === READING_WORKSPACE_MODE ||+ legacyCapability === MASTERY_WORKSPACE_MODE+ ) {+ return legacyCapability;+ }+ return null;+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 300b8d93c..db2076bb1 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -125,6 +125,58 @@"Intelligent markdown editor with AI-powered writing assistance.": "Intelligent markdown editor with AI-powered writing assistance.","Knowledge": "Knowledge","Memory": "Memory",+ "About": "About",+ "DeepTutor version, release channel, and the safest update path for this installation.": "DeepTutor version, release channel, and the safest update path for this installation.",+ "Running version": "Running version",+ "Release notes": "Release notes",+ "Check now": "Check now",+ "Update to {{version}}": "Update to {{version}}",+ "Unable to load version information.": "Unable to load version information.",+ "Unable to check for updates.": "Unable to check for updates.",+ "Unable to save update settings.": "Unable to save update settings.",+ "Unable to start the update.": "Unable to start the update.",+ "DeepTutor did not reconnect before the update timeout.": "DeepTutor did not reconnect before the update timeout.",+ "Software": "Software",+ "Current version": "Current version",+ "Installation": "Installation",+ "How DeepTutor is installed here.": "How DeepTutor is installed here.",+ "Release channel": "Release channel",+ "Only stable, published DeepTutor releases are considered.": "Only stable, published DeepTutor releases are considered.",+ "Stable": "Stable",+ "Updates": "Updates",+ "Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.": "Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.",+ "Check for updates": "Check for updates",+ "Turn this off for offline or controlled deployments.": "Turn this off for offline or controlled deployments.",+ "Latest stable release": "Latest stable release",+ "Last checked {{time}}": "Last checked {{time}}",+ "Not checked yet": "Not checked yet",+ "Version checks are disabled.": "Version checks are disabled.",+ "This release mentions migrations or breaking changes. Read the release notes before updating.": "This release mentions migrations or breaking changes. Read the release notes before updating.",+ "What changed": "What changed",+ "Managed by your installation": "Managed by your installation",+ "Project": "Project",+ "GitHub": "GitHub",+ "Source code, issues, and contributions": "Source code, issues, and contributions",+ "Installation, configuration, and guides": "Installation, configuration, and guides",+ "Update and restart DeepTutor?": "Update and restart DeepTutor?",+ "Update and restart": "Update and restart",+ "Preparing update…": "Preparing update…",+ "DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.": "DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.",+ "PyPI package": "PyPI package",+ "Source checkout": "Source checkout",+ "Docker container": "Docker container",+ "Unknown installation": "Unknown installation",+ "Container images are updated and recreated by the Docker host.": "Container images are updated and recreated by the Docker host.",+ "Source checkouts stay under the developer's Git workflow.": "Source checkouts stay under the developer's Git workflow.",+ "The running DeepTutor distribution could not be identified.": "The running DeepTutor distribution could not be identified.",+ "Automatic updates require a regular PyPI installation in an active virtual environment.": "Automatic updates require a regular PyPI installation in an active virtual environment.",+ "This installation came from a local or direct package artifact.": "This installation came from a local or direct package artifact.",+ "updateJob.pending": "Update queued. DeepTutor will restart shortly.",+ "updateJob.handoff": "Stopping DeepTutor safely…",+ "updateJob.running": "Installing the update…",+ "updateJob.restarting": "Update installed. Reconnecting…",+ "updateJob.succeeded": "DeepTutor updated and reconnected.",+ "updateJob.failed": "The update did not complete.","Knowledge Bases": "Knowledge Bases","Refresh knowledge bases": "Refresh knowledge bases","New Knowledge Base": "New Knowledge Base",@@ -4119,5 +4171,10 @@"Move to More": "Move to More","Move out of More": "Move out of More","Reset sidebar order": "Reset sidebar order",- "Reset chat order": "Reset chat order"+ "Reset chat order": "Reset chat order",+ "Delete provider": "Delete provider",+ "Delete this provider?": "Delete this provider?",+ "This is your active {{service}} provider — deleting it switches to {{next}}.": "This is your active {{service}} provider — deleting it switches to {{next}}.",+ "This removes {{count}} model(s) and its saved credentials. This can't be undone.": "This removes {{count}} model(s) and its saved credentials. This can't be undone.",+ "nothing configured": "nothing configured"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 85b1d8031..4b92bcc71 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -125,6 +125,58 @@"Intelligent markdown editor with AI-powered writing assistance.": "带 AI 写作辅助的智能 Markdown 编辑器。","Knowledge": "知识库","Memory": "记忆",+ "About": "关于",+ "DeepTutor version, release channel, and the safest update path for this installation.": "查看 DeepTutor 版本、发布通道,以及适合当前安装方式的安全更新路径。",+ "Running version": "当前运行版本",+ "Release notes": "发布说明",+ "Check now": "立即检查",+ "Update to {{version}}": "更新到 {{version}}",+ "Unable to load version information.": "无法加载版本信息。",+ "Unable to check for updates.": "无法检查更新。",+ "Unable to save update settings.": "无法保存更新设置。",+ "Unable to start the update.": "无法启动更新。",+ "DeepTutor did not reconnect before the update timeout.": "DeepTutor 未能在更新超时前重新连接。",+ "Software": "软件信息",+ "Current version": "当前版本",+ "Installation": "安装方式",+ "How DeepTutor is installed here.": "当前 DeepTutor 的安装来源。",+ "Release channel": "发布通道",+ "Only stable, published DeepTutor releases are considered.": "只检查已经正式发布的 DeepTutor 稳定版本。",+ "Stable": "稳定版",+ "Updates": "版本更新",+ "Version checks are cached for 24 hours. DeepTutor never installs an update without confirmation.": "版本检查结果缓存 24 小时;未经确认,DeepTutor 绝不会自行安装更新。",+ "Check for updates": "检查更新",+ "Turn this off for offline or controlled deployments.": "离线或受控部署可以关闭此项。",+ "Latest stable release": "最新稳定版",+ "Last checked {{time}}": "上次检查:{{time}}",+ "Not checked yet": "尚未检查",+ "Version checks are disabled.": "版本检查已关闭。",+ "This release mentions migrations or breaking changes. Read the release notes before updating.": "此版本包含迁移或破坏性变更;更新前请先阅读发布说明。",+ "What changed": "更新内容",+ "Managed by your installation": "由当前安装方式管理",+ "Project": "项目资源",+ "GitHub": "GitHub",+ "Source code, issues, and contributions": "源代码、问题反馈与参与贡献",+ "Installation, configuration, and guides": "安装、配置与使用指南",+ "Update and restart DeepTutor?": "更新并重启 DeepTutor?",+ "Update and restart": "更新并重启",+ "Preparing update…": "正在准备更新…",+ "DeepTutor will briefly stop, install {{version}}, and reopen with the same settings. Active conversations must finish first.": "DeepTutor 将短暂停止,安装 {{version}},并使用相同设置重新启动。请先完成正在进行的对话。",+ "PyPI package": "PyPI 软件包",+ "Source checkout": "源码工作区",+ "Docker container": "Docker 容器",+ "Unknown installation": "未知安装方式",+ "Container images are updated and recreated by the Docker host.": "容器镜像应由 Docker 宿主机更新并重新创建。",+ "Source checkouts stay under the developer's Git workflow.": "源码工作区继续由开发者的 Git 工作流管理。",+ "The running DeepTutor distribution could not be identified.": "无法识别当前运行的 DeepTutor 安装来源。",+ "Automatic updates require a regular PyPI installation in an active virtual environment.": "自动更新需要在已激活的虚拟环境中使用常规 PyPI 安装。",+ "This installation came from a local or direct package artifact.": "当前 DeepTutor 来自本地或直接安装的软件包。",+ "updateJob.pending": "更新已排队,DeepTutor 即将重启。",+ "updateJob.handoff": "正在安全停止 DeepTutor…",+ "updateJob.running": "正在安装更新…",+ "updateJob.restarting": "更新已安装,正在重新连接…",+ "updateJob.succeeded": "DeepTutor 已更新并重新连接。",+ "updateJob.failed": "更新未能完成。","Knowledge Bases": "知识库","Refresh knowledge bases": "刷新知识库列表","New Knowledge Base": "新建知识库",@@ -4119,5 +4171,10 @@"Move to More": "收进「更多」","Move out of More": "移出「更多」","Reset sidebar order": "恢复默认排列",- "Reset chat order": "恢复默认顺序"+ "Reset chat order": "恢复默认顺序",+ "Delete provider": "删除供应商",+ "Delete this provider?": "删除这个供应商?",+ "This is your active {{service}} provider — deleting it switches to {{next}}.": "这是当前使用中的 {{service}} 供应商,删除后会切换到 {{next}}。",+ "This removes {{count}} model(s) and its saved credentials. This can't be undone.": "这会删除 {{count}} 个模型及已保存的密钥,且不可撤销。",+ "nothing configured": "未配置"}diff --git a/web/tests/app-update.test.ts b/web/tests/app-update.test.tsnew file mode 100644index 000000000..cfc87e5cf--- /dev/null+++ b/web/tests/app-update.test.ts@@ -0,0 +1,113 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ checkAppUpdate,+ fetchAppUpdateJob,+ fetchAppUpdateStatus,+ requestAppUpdate,+ setAppUpdateChecks,+ updateJobIsActive,+} from '../lib/app-update'++const statusPayload = {+ current_version: '1.6.1',+ check_enabled: true,+ checked_at: '2026-08-30T00:00:00Z',+ cached: false,+ check_error: '',+ update_available: true,+ release: {+ version: '1.7.0',+ name: 'DeepTutor 1.7',+ published_at: '2026-08-30T00:00:00Z',+ url: 'https://github.com/HKUDS/DeepTutor/releases/tag/v1.7.0',+ excerpt: 'A stable release.',+ migration_warning: false,+ },+ installation: {+ mode: 'pypi',+ automatic_update: true,+ command: 'pip install -U deeptutor',+ reason: '',+ },+ launcher_managed: true,+ is_admin: true,+ job: null,+} as const++const jobPayload = {+ id: 'job-1',+ status: 'pending',+ current_version: '1.6.1',+ target_version: '1.7.0',+ created_at: '2026-08-30T00:00:00Z',+ started_at: null,+ finished_at: null,+ error: null,+ restart_count: 0,+} as const++test('app update client uses the canonical system routes', async () => {+ const requests: Array<{ path: string; method: string; body?: string }> = []+ const originalFetch = globalThis.fetch+ globalThis.fetch = async (input, init) => {+ requests.push({+ path: String(input),+ method: init?.method ?? 'GET',+ body: typeof init?.body === 'string' ? init.body : undefined,+ })+ const updateRequest = String(input) === '/api/v1/system/update' && init?.method === 'POST'+ const body = String(input).endsWith('/job') || updateRequest ? jobPayload : statusPayload+ return new Response(JSON.stringify(body), {+ status: updateRequest ? 202 : 200,+ headers: { 'content-type': 'application/json' },+ })+ }++ try {+ assert.equal((await fetchAppUpdateStatus()).current_version, '1.6.1')+ assert.equal((await checkAppUpdate()).release?.version, '1.7.0')+ assert.equal((await setAppUpdateChecks(false)).check_enabled, true)+ assert.equal((await requestAppUpdate()).id, 'job-1')+ assert.equal((await fetchAppUpdateJob())?.id, 'job-1')+ } finally {+ globalThis.fetch = originalFetch+ }++ assert.deepEqual(+ requests.map(({ path, method }) => ({ path, method })),+ [+ { path: '/api/v1/system/update', method: 'GET' },+ { path: '/api/v1/system/update/check', method: 'POST' },+ { path: '/api/v1/system/update/settings', method: 'PUT' },+ { path: '/api/v1/system/update', method: 'POST' },+ { path: '/api/v1/system/update/job', method: 'GET' },+ ]+ )+ assert.equal(requests[2]?.body, JSON.stringify({ enabled: false }))+ assert.equal(requests[3]?.body, JSON.stringify({ confirmation: 'update-and-restart' }))+})++test('app update client preserves FastAPI error details', async () => {+ const originalFetch = globalThis.fetch+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ detail: 'Finish the active conversation.' }), {+ status: 409,+ headers: { 'content-type': 'application/json' },+ })++ try {+ await assert.rejects(requestAppUpdate(), /Finish the active conversation/)+ } finally {+ globalThis.fetch = originalFetch+ }+})++test('only non-terminal jobs remain active', () => {+ for (const status of ['pending', 'handoff', 'running', 'restarting'] as const) {+ assert.equal(updateJobIsActive(status), true)+ }+ assert.equal(updateJobIsActive('succeeded'), false)+ assert.equal(updateJobIsActive('failed'), false)+})diff --git a/web/tests/mastery-session.test.ts b/web/tests/mastery-session.test.tsnew file mode 100644index 000000000..15a3607e8--- /dev/null+++ b/web/tests/mastery-session.test.ts@@ -0,0 +1,84 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ masteryPathIdOf,+ readingWorkspaceIdOf,+} from "../lib/mastery-session";+import type { SessionSummary } from "../lib/session-api";+import { workspaceActionNeedsConfiguration } from "../lib/workspace-mode";++function session(preferences: SessionSummary["preferences"]): SessionSummary {+ return {+ id: "session-1",+ session_id: "session-1",+ title: "Learning session",+ created_at: 1,+ updated_at: 1,+ message_count: 1,+ last_message: "hello",+ preferences,+ };+}++test("mastery ownership survives switching the per-turn action", () => {+ const item = session({+ workspace_mode: "mastery_path",+ mastery_path_id: "path-42",+ capability: "deep_research",+ });++ assert.equal(masteryPathIdOf(item), "path-42");+});++test("reading ownership survives switching the per-turn action", () => {+ const item = session({+ workspace_mode: "immersive_reading",+ reading_workspace_id: "reading-42",+ capability: "visualize",+ });++ assert.equal(readingWorkspaceIdOf(item), "reading-42");+});++test("legacy learning sessions remain routable", () => {+ assert.equal(+ masteryPathIdOf(+ session({ capability: "mastery_path", mastery_path_id: "legacy-path" }),+ ),+ "legacy-path",+ );+ assert.equal(+ readingWorkspaceIdOf(+ session({+ capability: "immersive_reading",+ session_kind: "immersive_reading",+ reading_workspace_id: "legacy-reading",+ }),+ ),+ "legacy-reading",+ );+});++test("unrelated sessions do not inherit stale learning ids", () => {+ assert.equal(+ masteryPathIdOf(+ session({ capability: "chat", mastery_path_id: "stale-path" }),+ ),+ "",+ );+ assert.equal(+ readingWorkspaceIdOf(+ session({ capability: "chat", reading_workspace_id: "stale-reading" }),+ ),+ "",+ );+});++test("configured workspace actions do not bypass their settings", () => {+ assert.equal(workspaceActionNeedsConfiguration("deep_question"), true);+ assert.equal(workspaceActionNeedsConfiguration("visualize"), true);+ assert.equal(workspaceActionNeedsConfiguration("deep_research"), true);+ assert.equal(workspaceActionNeedsConfiguration("deep_solve"), false);+ assert.equal(workspaceActionNeedsConfiguration(""), false);+});diff --git a/web/tests/reading-turn-state.test.ts b/web/tests/reading-turn-state.test.tsindex 5c9d34f2b..606c87bc7 100644--- a/web/tests/reading-turn-state.test.ts+++ b/web/tests/reading-turn-state.test.ts@@ -1,7 +1,7 @@import test from "node:test";import assert from "node:assert/strict";import {- READING_CAPABILITY,+ READING_WORKSPACE_MODE,getReadingTurnState,readingTurnFields,resetReadingTurnState,@@ -12,11 +12,11 @@ import {test.beforeEach(() => resetReadingTurnState());-test("carries the document and viewport on a reading turn", () => {+test("carries the document and viewport for every action inside reading", () => {setReadingMaterial("d138eacaad029843");setReadingViewport({ locator: 3, selection: "attention" });- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {reading_material_id: "d138eacaad029843",reading_viewport: { locator: 3, selection: "attention" },});@@ -27,43 +27,39 @@ test("carries the document and viewport on a reading turn", () => {// document open" attached the reader to every later turn — a brand-new chat// session would open with "I see you're reading …" and cite pages from a// document the user had moved on from.-test("carries nothing once the user switches to another mode", () => {+test("changing the per-turn action does not detach the reading workspace", () => {setReadingMaterial("d138eacaad029843");setReadingViewport({ locator: 3 });- for (const capability of [- "",- "deep_solve",- "deep_research",- "mastery_path",- "visualize",- ]) {- assert.deepEqual(readingTurnFields(capability), {}, capability);+ for (const capability of ["", "deep_solve", "deep_research", "visualize"]) {+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {+ reading_material_id: "d138eacaad029843",+ reading_viewport: { locator: 3 },+ }, capability);}});-test("carries nothing when the capability is absent", () => {+test("carries nothing when the workspace mode is absent", () => {setReadingMaterial("d138eacaad029843");assert.deepEqual(readingTurnFields(null), {});assert.deepEqual(readingTurnFields(undefined), {});});-test("the document itself is kept, so returning to the mode resumes it", () => {+test("leaving the reading workspace stops carrying its document", () => {setReadingMaterial("d138eacaad029843");setReadingViewport({ locator: 7 });- // Away…- assert.deepEqual(readingTurnFields("deep_solve"), {});- // …and back, with the reader still where it was.+ assert.deepEqual(readingTurnFields(null), {});+ // The reader cell remains intact so returning to the workspace resumes it.assert.equal(getReadingTurnState().materialId, "d138eacaad029843");assert.equal(- readingTurnFields(READING_CAPABILITY).reading_viewport?.locator,+ readingTurnFields(READING_WORKSPACE_MODE).reading_viewport?.locator,7,);});test("carries nothing in reading mode with no document open", () => {- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {});+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {});});test("closing the document clears its viewport too", () => {@@ -71,7 +67,7 @@ test("closing the document clears its viewport too", () => {setReadingViewport({ locator: 9, selection: "x" });setReadingMaterial(null);- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {});+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {});assert.deepEqual(getReadingTurnState(), {workspaceId: null,materialId: null,@@ -85,13 +81,13 @@ test("carries the private workspace and clears it independently", () => {setReadingWorkspace("workspace_123");setReadingMaterial("d138eacaad029843");- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {reading_workspace_id: "workspace_123",reading_material_id: "d138eacaad029843",});setReadingWorkspace(null);- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {});+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {});assert.deepEqual(getReadingTurnState(), {workspaceId: null,materialId: null,@@ -103,7 +99,7 @@ test("carries the private workspace and clears it independently", () => {test("a viewport with no locator or selection is omitted, not sent empty", () => {setReadingMaterial("d138eacaad029843");- assert.deepEqual(readingTurnFields(READING_CAPABILITY), {+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE), {reading_material_id: "d138eacaad029843",});});@@ -112,12 +108,12 @@ test("nonsense viewport values are ignored", () => {setReadingMaterial("d138eacaad029843");setReadingViewport({ locator: -3 });assert.equal(- readingTurnFields(READING_CAPABILITY).reading_viewport,+ readingTurnFields(READING_WORKSPACE_MODE).reading_viewport,undefined,);setReadingViewport({ locator: 2.7 });assert.equal(- readingTurnFields(READING_CAPABILITY).reading_viewport?.locator,+ readingTurnFields(READING_WORKSPACE_MODE).reading_viewport?.locator,2,);});@@ -125,14 +121,14 @@ test("nonsense viewport values are ignored", () => {test("carries precise media time, including the beginning", () => {setReadingMaterial("d138eacaad029843");setReadingViewport({ locator: 2, timeSeconds: 62.5 });- assert.deepEqual(readingTurnFields(READING_CAPABILITY).reading_viewport, {+ assert.deepEqual(readingTurnFields(READING_WORKSPACE_MODE).reading_viewport, {locator: 2,time_seconds: 62.5,});setReadingViewport({ timeSeconds: 0 });assert.equal(- readingTurnFields(READING_CAPABILITY).reading_viewport?.time_seconds,+ readingTurnFields(READING_WORKSPACE_MODE).reading_viewport?.time_seconds,0,);});diff --git a/web/tests/reading-v2-surface.test.ts b/web/tests/reading-v2-surface.test.tsindex 8571afe1e..2fddbe894 100644--- a/web/tests/reading-v2-surface.test.ts+++ b/web/tests/reading-v2-surface.test.ts@@ -89,6 +89,14 @@ test("reading is reachable only through its own workspace", () => {assert.doesNotMatch(css, /dt-reader-shell|--reader-width/);});+test("reading owns an isolated chat runtime instead of inheriting Home's stream", () => {+ const layout = source("app/(workspace)/reading/layout.tsx");++ assert.match(layout, /UnifiedChatProvider/);+ assert.match(layout, /QuizFollowupProvider/);+ assert.match(layout, /GeogebraTabProvider/);+});+test("Reading V2 inherits product theme tokens instead of a fixed cream palette", () => {const library = librarySurface();const workspace = workspaceSurface();