DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge origin/main into multi-user
Bingxi Zhao (Frank)e53985d7f0c9
diff --cc .env.exampleindex 886096cc4,8b1b6a664..240d79aa1--- a/.env.example+++ b/.env.example@@@ -69,59 -74,15 +75,72 @@@ NEXT_PUBLIC_API_BASE# Keep this false in production.DISABLE_SSL_VERIFY=false+# --------------------------------------------+# PocketBase (Optional — auth + storage sidecar)+# --------------------------------------------+# Leave POCKETBASE_URL blank to use the built-in SQLite/JSON backend (default).+# Set it to enable PocketBase for auth, sessions, and KB storage.+#+# When running via Docker Compose, PocketBase is always started but only used+# if POCKETBASE_URL is set here.+#+# Local Docker: POCKETBASE_URL=http://pocketbase:8090+# Local bare: POCKETBASE_URL=http://localhost:8090+POCKETBASE_URL=++# Admin credentials used by the Python backend to manage collections.+# Set these after running the PocketBase container for the first time.+POCKETBASE_ADMIN_EMAIL=+POCKETBASE_ADMIN_PASSWORD=++# Public PocketBase URL for OAuth redirects (remote server deployments only).+# Leave blank when browsing from the same machine running Docker.+POCKETBASE_EXTERNAL_URL=++# --------------------------------------------+# Authentication (Optional)+# --------------------------------------------+# Set AUTH_ENABLED=true to require login when hosting publicly.+# Leave as false for local/localhost usage — no login needed.+AUTH_ENABLED=false++# Secret key used to sign JWT tokens. Set to a long random string.+# Generate with: python -c "import secrets; print(secrets.token_hex(32))"+AUTH_SECRET=++# How long login sessions last in hours (default: 24)+AUTH_TOKEN_EXPIRE_HOURS=24++# Must match AUTH_ENABLED above so the frontend knows to show the login page.+NEXT_PUBLIC_AUTH_ENABLED=false++# --- Multi-user setup (recommended) ---+# With AUTH_ENABLED=true and no AUTH_USERNAME/AUTH_PASSWORD_HASH set, navigate+# to /register in the browser. The first user to register is automatically+# granted admin privileges and can manage other users from /admin/users.+# Users are stored in data/user/auth_users.json.++# --- Single-user env-var setup (legacy / simple) ---+# Alternatively, set AUTH_USERNAME and AUTH_PASSWORD_HASH directly.+# This user is always treated as admin. When auth_users.json exists, it takes+# priority and these env vars are ignored.++# Username for the single admin account (single-user mode only).+AUTH_USERNAME=++# Bcrypt hash of the password. Generate with:+# python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"+AUTH_PASSWORD_HASH=+++ # --------------------------------------------+ # Chat Attachments (Optional)+ # --------------------------------------------+ # Where the chat turn runtime persists user-uploaded files (PDF, DOCX,+ # images, …) so the preview drawer can re-fetch the originals after the+ # in-memory base64 is dropped.+ #+ # Defaults to <project>/data/user/workspace/chat/attachments, which is+ # already mounted as a volume in docker-compose.yml — leave unset for the+ # default Docker / Linux deployment. Override only when running multiple+ # backend instances against shared storage (e.g. NFS).+ CHAT_ATTACHMENT_DIR=diff --cc README.mdindex c237a7cc6,b52b95ab6..fd14764b8--- a/README.md+++ b/README.md@@@ -74,14 -94,13 +94,14 @@@## ✨ Key Features- - **Unified Chat Workspace** — Five modes, one thread. Chat, Deep Solve, Quiz Generation, Deep Research, and Math Animator share the same context — start a conversation, escalate to multi-agent problem solving, generate quizzes, then deep-dive into research, all without losing a single message.- - **Personal TutorBots** — Not chatbots — autonomous tutors. Each TutorBot lives in its own workspace with its own memory, personality, and skill set. They set reminders, learn new abilities, and evolve as you grow. Powered by [nanobot](https://github.com/HKUDS/nanobot).- - **AI Co-Writer** — A Markdown editor where AI is a first-class collaborator. Select text, rewrite, expand, or summarize — drawing from your knowledge base and the web. Every piece feeds back into your learning ecosystem.- - **Guided Learning** — Turn your materials into structured, visual learning journeys. DeepTutor designs multi-step plans, generates interactive pages for each knowledge point, and lets you discuss alongside each step.- - **Knowledge Hub** — Upload PDFs, Markdown, and text files to build RAG-ready knowledge bases. Organize insights across sessions in color-coded notebooks. Your documents don't just sit there — they actively power every conversation.+ - **Unified Chat Workspace** — Six modes, one thread. Chat, Deep Solve, Quiz Generation, Deep Research, Math Animator, and Visualize share the same context — start a conversation, escalate to multi-agent problem solving, generate quizzes, visualize concepts, then deep-dive into research, all without losing a single message.+ - **AI Co-Writer** — A multi-document Markdown workspace where AI is a first-class collaborator. Select text, rewrite, expand, or summarize — drawing from your knowledge base and the web. Every piece feeds back into your learning ecosystem.+ - **Book Engine** — Turn your materials into structured, interactive "living books". A multi-agent pipeline designs outlines, retrieves relevant sources, and compiles rich pages with 14 block types — quizzes, flash cards, timelines, concept graphs, interactive demos, and more.+ - **Knowledge Hub** — Upload PDFs, Markdown, and text files to build RAG-ready knowledge bases. Organize insights in color-coded notebooks, revisit quiz questions in the Question Bank, and create custom Skills that shape how DeepTutor teaches you. Your documents don't just sit there — they actively power every conversation.- **Persistent Memory** — DeepTutor builds a living profile of you: what you've studied, how you learn, and where you're heading. Shared across all features and TutorBots, it gets sharper with every interaction.+ - **Personal TutorBots** — Not chatbots — autonomous tutors. Each TutorBot lives in its own workspace with its own memory, personality, and skill set. They set reminders, learn new abilities, and evolve as you grow. Powered by [nanobot](https://github.com/HKUDS/nanobot).- **Agent-Native CLI** — Every capability, knowledge base, session, and TutorBot is one command away. Rich terminal output for humans, structured JSON for AI agents and pipelines. Hand DeepTutor a [`SKILL.md`](SKILL.md) and your agents can operate it autonomously.+- **Optional Authentication** — Disabled by default for local use. Flip two env vars to require login when hosting publicly. Multi-user support with bcrypt-hashed passwords, JWT sessions, a self-service registration page, and a built-in admin dashboard for managing accounts and roles. Optionally back auth and storage with **PocketBase** for OAuth-ready authentication and improved multi-user concurrency — drops in as an optional sidecar with no code changes required.---diff --cc deeptutor/api/main.pyindex ec74e0554,a47fc201f..ca001d1c3--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@@ -221,7 -199,8 +222,9 @@@ app.mount# Some router modules load YAML settings at import time.from deeptutor.api.routers import (agent_config,+ attachments,+ auth,+ book,chat,co_writer,dashboard,@@@ -240,56 -220,30 +244,69 @@@vision_solver,)-# Include routers-app.include_router(solve.router, prefix="/api/v1", tags=["solve"])-app.include_router(chat.router, prefix="/api/v1", tags=["chat"])-app.include_router(question.router, prefix="/api/v1/question", tags=["question"])-app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])-app.include_router(dashboard.router, prefix="/api/v1/dashboard", tags=["dashboard"])-app.include_router(co_writer.router, prefix="/api/v1/co_writer", tags=["co_writer"])-app.include_router(notebook.router, prefix="/api/v1/notebook", tags=["notebook"])-app.include_router(book.router, prefix="/api/v1/book", tags=["book"])-app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"])-app.include_router(sessions.router, prefix="/api/v1/sessions", tags=["sessions"])+# Auth router is public — login/logout/register/status require no token+app.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])++# All other routers require a valid session when AUTH_ENABLED=true.+# require_auth is a no-op when AUTH_ENABLED=false, so this is safe for local use.+from deeptutor.api.routers.auth import require_auth # noqa: E402++_auth = [Depends(require_auth)]++app.include_router(solve.router, prefix="/api/v1", tags=["solve"], dependencies=_auth)+app.include_router(chat.router, prefix="/api/v1", tags=["chat"], dependencies=_auth)app.include_router(- question_notebook.router, prefix="/api/v1/question-notebook", tags=["question-notebook"]+ question.router, prefix="/api/v1/question", tags=["question"], dependencies=_auth)-app.include_router(settings.router, prefix="/api/v1/settings", tags=["settings"])-app.include_router(skills.router, prefix="/api/v1/skills", tags=["skills"])-app.include_router(system.router, prefix="/api/v1/system", tags=["system"])-app.include_router(plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"])-app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])-app.include_router(vision_solver.router, prefix="/api/v1", tags=["vision-solver"])-app.include_router(tutorbot.router, prefix="/api/v1/tutorbot", tags=["tutorbot"])-app.include_router(attachments.router, prefix="/api/attachments", tags=["attachments"])--# Unified WebSocket endpoint+app.include_router(+ knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"], dependencies=_auth+)+app.include_router(+ dashboard.router, prefix="/api/v1/dashboard", tags=["dashboard"], dependencies=_auth+)+app.include_router(+ co_writer.router, prefix="/api/v1/co_writer", tags=["co_writer"], dependencies=_auth+)+app.include_router(+ notebook.router, prefix="/api/v1/notebook", tags=["notebook"], dependencies=_auth+)- app.include_router(guide.router, prefix="/api/v1/guide", tags=["guide"], dependencies=_auth)++app.include_router(book.router, prefix="/api/v1/book", tags=["book"], dependencies=_auth)+app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"], dependencies=_auth)+app.include_router(+ sessions.router, prefix="/api/v1/sessions", tags=["sessions"], dependencies=_auth+)++app.include_router(++ question_notebook.router,++ prefix="/api/v1/question-notebook",++ tags=["question-notebook"],++ dependencies=_auth,++)+app.include_router(+ settings.router, prefix="/api/v1/settings", tags=["settings"], dependencies=_auth+)++app.include_router(skills.router, prefix="/api/v1/skills", tags=["skills"], dependencies=_auth)+app.include_router(system.router, prefix="/api/v1/system", tags=["system"], dependencies=_auth)+app.include_router(+ plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"], dependencies=_auth+)+app.include_router(+ agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"], dependencies=_auth+)+app.include_router(+ vision_solver.router, prefix="/api/v1", tags=["vision-solver"], dependencies=_auth+)+app.include_router(+ tutorbot.router, prefix="/api/v1/tutorbot", tags=["tutorbot"], dependencies=_auth+)++app.include_router(++ attachments.router,++ prefix="/api/attachments",++ tags=["attachments"],++ dependencies=_auth,++)++# Unified WebSocket endpoint — auth is checked inside the handler (WebSockets+# cannot use FastAPI dependencies in the standard way)app.include_router(unified_ws.router, prefix="/api/v1", tags=["unified-ws"])diff --cc deeptutor/api/routers/knowledge.pyindex cc6475860,533187536..8f646c74e--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@@ -108,100 -119,128 +119,174 @@@ def _save_uploaded_filesfiles: list[UploadFile],target_dir: Path,allowed_extensions: set[str] | None = None,+ kb_name: str | None = None,) -> tuple[list[str], list[str]]:+ """+ Save uploaded files to the local raw/ directory.++ When PocketBase is enabled and ``kb_name`` is supplied, each file is also+ uploaded to the PocketBase knowledge_bases record as a file attachment+ (best-effort — local write is always the primary path).+ """uploaded_files: list[str] = []uploaded_file_paths: list[str] = []+ written_file_paths: list[Path] = []+ from deeptutor.services.pocketbase_client import is_pocketbase_enabled++ _pb_sync = is_pocketbase_enabled() and bool(kb_name)++ try:+ for file in files:+ file_path = None+ original_filename = file.filename or "upload"+ try:+ sanitized_filename = DocumentValidator.validate_upload_safety(+ original_filename,+ _get_upload_file_size(file),+ allowed_extensions=allowed_extensions,+ )+ file.filename = sanitized_filename++ file_path = target_dir / sanitized_filename+ max_size = DocumentValidator.MAX_FILE_SIZE+ written_bytes = 0++ file.file.seek(0)+ with open(file_path, "wb") as buffer:+ for chunk in iter(lambda: file.file.read(8192), b""):+ written_bytes += len(chunk)+ if written_bytes > max_size:+ size_str = format_bytes_human_readable(max_size)+ raise HTTPException(+ status_code=400,+ detail=(+ f"File '{sanitized_filename}' exceeds maximum size "+ f"limit of {size_str}"+ ),+ )+ buffer.write(chunk)++ DocumentValidator.validate_upload_safety(+ sanitized_filename, written_bytes, allowed_extensions=allowed_extensions+ )+ written_file_paths.append(file_path)+ uploaded_files.append(sanitized_filename)+ uploaded_file_paths.append(str(file_path))++++ # Mirror file to PocketBase when enabled (best-effort, non-blocking).++ if _pb_sync and kb_name:++ try:++ _upload_file_to_pb(kb_name, sanitized_filename, file_path)++ except Exception as pb_exc:++ logger.debug(++ "PocketBase file upload failed for '%s': %s",++ sanitized_filename,++ pb_exc,++ )+ except Exception as e:+ if file_path and file_path.exists():+ try:+ os.unlink(file_path)+ except OSError:+ pass++ error_message = (+ f"Validation failed for file '{original_filename}': {format_exception_message(e)}"+ )+ logger.error(error_message, exc_info=True)+ raise HTTPException(status_code=400, detail=error_message) from e+ except Exception:+ for written_path in written_file_paths:+ if written_path.exists():+ try:+ os.unlink(written_path)+ except OSError:+ pass+ raise++ return uploaded_files, uploaded_file_paths+++ def _get_upload_file_size(file: UploadFile) -> int | None:+ """Best-effort byte size detection without consuming the uploaded stream."""+ try:+ current_position = file.file.tell()+ file.file.seek(0, os.SEEK_END)+ size = file.file.tell()+ file.file.seek(current_position)+ return size+ except Exception:+ return None+++ def _validate_upload_batch(+ files: list[UploadFile],+ allowed_extensions: set[str] | None = None,+ ) -> list[dict[str, int | str | None]]:+ """Validate upload metadata before mutating KB state or writing any files."""+ validated: list[dict[str, int | str | None]] = []+ seen_names: set[str] = set()+for file in files:- file_path = Noneoriginal_filename = file.filename or "upload"+ size_bytes = _get_upload_file_size(file)try:sanitized_filename = DocumentValidator.validate_upload_safety(- original_filename, None, allowed_extensions=allowed_extensions- )- file.filename = sanitized_filename-- file_path = target_dir / sanitized_filename- max_size = DocumentValidator.MAX_FILE_SIZE- written_bytes = 0-- with open(file_path, "wb") as buffer:- for chunk in iter(lambda: file.file.read(8192), b""):- written_bytes += len(chunk)- if written_bytes > max_size:- size_str = format_bytes_human_readable(max_size)- raise HTTPException(- status_code=400,- detail=f"File '{sanitized_filename}' exceeds maximum size limit of {size_str}",- )- buffer.write(chunk)-- DocumentValidator.validate_upload_safety(- sanitized_filename, written_bytes, allowed_extensions=allowed_extensions+ original_filename,+ size_bytes,+ allowed_extensions=allowed_extensions,)- uploaded_files.append(sanitized_filename)- uploaded_file_paths.append(str(file_path))-- # Mirror file to PocketBase when enabled (best-effort, non-blocking)- if _pb_sync and file_path:- try:- _upload_file_to_pb(kb_name, sanitized_filename, file_path)- except Exception as pb_exc:- logger.debug(- "PocketBase file upload failed for '%s': %s", sanitized_filename, pb_exc- )-except Exception as e:- if file_path and file_path.exists():- try:- os.unlink(file_path)- except OSError:- pass-error_message = (f"Validation failed for file '{original_filename}': {format_exception_message(e)}")- logger.error(error_message, exc_info=True)raise HTTPException(status_code=400, detail=error_message) from e- return uploaded_files, uploaded_file_paths+ if sanitized_filename in seen_names:+ raise HTTPException(+ status_code=400,+ detail=(+ f"Duplicate filename after sanitization: '{sanitized_filename}'. "+ "Rename one of the files and try again."+ ),+ )++ seen_names.add(sanitized_filename)+ validated.append(+ {+ "original_filename": original_filename,+ "sanitized_filename": sanitized_filename,+ "size_bytes": size_bytes,+ }+ )++ return validated+def _upload_file_to_pb(kb_name: str, filename: str, file_path: Path) -> None:+ """Upload a single file to the PocketBase knowledge_bases record."""+ try:+ from deeptutor.services.pocketbase_client import get_pb_client++ pb = get_pb_client()+ records = pb.collection("knowledge_bases").get_full_list(+ query_params={"filter": f'kb_name="{kb_name}"'}+ )+ if not records:+ logger.debug(f"PocketBase KB record not found for '{kb_name}', skipping file upload")+ return+ with open(file_path, "rb") as fh:+ pb.collection("knowledge_bases").update(+ records[0].id,+ body={"kb_name": kb_name},+ files={"raw_files": (filename, fh)},+ )+ logger.debug(f"Uploaded '{filename}' to PocketBase KB '{kb_name}'")+ except Exception as exc:+ logger.debug(f"_upload_file_to_pb failed: {exc}")++def _task_log(task_id: str, message: str, level: str = "info") -> None:manager = get_task_stream_manager()manager.ensure_task(task_id)diff --cc deeptutor/app/facade.pyindex 180063f57,e8e54f43b..55a81de1c--- a/deeptutor/app/facade.py+++ b/deeptutor/app/facade.py@@@ -9,10 -8,8 +8,8 @@@ import jsofrom typing import Any, AsyncIteratorfrom deeptutor.runtime.registry.capability_registry import get_capability_registry- from deeptutor.services.notebook import RecordType, get_notebook_manager+ from deeptutor.services.notebook import get_notebook_manager-from deeptutor.services.session import get_sqlite_session_store, get_turn_runtime_manager+from deeptutor.services.session import get_session_store, get_turn_runtime_manager@dataclass(slots=True)diff --cc deeptutor/knowledge/manager.pyindex 949866e3d,8a5c55c6b..104f47d2c--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@@ -12,15 -12,13 +12,13 @@@ import jsoimport osfrom pathlib import Pathimport shutil+ import statimport sys+ from typing import Anyfrom deeptutor.logging import get_logger- from deeptutor.services.rag.components.routing import FileTypeRouter- from deeptutor.services.rag.factory import (- DEFAULT_PROVIDER,- LEGACY_PROVIDER_ALIASES,- normalize_provider_name,- )-from deeptutor.services.rag.factory import DEFAULT_PROVIDER++from deeptutor.services.rag.factory import DEFAULT_PROVIDER, normalize_provider_name+ from deeptutor.services.rag.file_routing import FileTypeRouterlogger = get_logger("KnowledgeBaseManager")@@@ -392,9 -348,9 +388,9 @@@ class KnowledgeBaseManagerkb_entry["description"] = metadata["description"]if metadata.get("rag_provider"):raw_provider = str(metadata["rag_provider"]).strip().lower()- kb_entry["rag_provider"] = DEFAULT_PROVIDER+ kb_entry["rag_provider"] = normalize_provider_name(raw_provider)- if str(raw_provider).strip().lower() in LEGACY_PROVIDER_ALIASES:- kb_entry["needs_reindex"] = True # type: ignore[assignment]+ if raw_provider not in {"", DEFAULT_PROVIDER}:+ kb_entry["needs_reindex"] = Trueif metadata.get("created_at"):kb_entry["created_at"] = metadata["created_at"]if metadata.get("last_updated"):diff --cc deeptutor/services/session/context_builder.pyindex 1c457e717,9d3c4c444..cf5346ece--- a/deeptutor/services/session/context_builder.py+++ b/deeptutor/services/session/context_builder.py@@@ -11,8 -11,9 +11,9 @@@ from deeptutor.agents.base_agent imporfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_idfrom deeptutor.services.llm.config import LLMConfig+ from deeptutor.services.llm.context_window import resolve_effective_context_window-from .sqlite_store import SQLiteSessionStore+from .protocol import SessionStoreProtocoldef count_tokens(text: str) -> int:diff --cc deeptutor/services/session/turn_runtime.pyindex 3214a3b73,1e3980d89..e28c4d99e--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@@ -36,6 -36,74 +36,78 @@@ def _clip_text(value: str, limit: intreturn text[:limit].rstrip() + "\n...[truncated]"+ def _format_question_bank_entry(entry: dict[str, Any]) -> str:+ """Render a single Question Bank entry as a structured Markdown block."""+ lines: list[str] = []+ title = str(entry.get("session_title", "") or "Untitled session")+ difficulty = str(entry.get("difficulty", "") or "").strip()+ qtype = str(entry.get("question_type", "") or "").strip()+ is_correct = bool(entry.get("is_correct"))++ badges: list[str] = []+ if qtype:+ badges.append(qtype)+ if difficulty:+ badges.append(difficulty)+ badges.append("correct" if is_correct else "incorrect")+ badge_text = " · ".join(badges)++ lines.append(f"### Question (from {title}) [{badge_text}]")+ lines.append(_clip_text(str(entry.get("question", "") or ""), limit=2000))++ options = entry.get("options") or {}+ if isinstance(options, dict) and options:+ lines.append("")+ lines.append("**Options:**")+ for key in sorted(options.keys()):+ lines.append(f"- {key}. {options[key]}")++ user_answer = str(entry.get("user_answer", "") or "").strip()+ correct_answer = str(entry.get("correct_answer", "") or "").strip()+ if user_answer:+ lines.append("")+ lines.append(f"**User's Answer:** {_clip_text(user_answer, limit=1000)}")+ if correct_answer:+ lines.append(f"**Reference Answer:** {_clip_text(correct_answer, limit=1500)}")++ explanation = str(entry.get("explanation", "") or "").strip()+ if explanation:+ lines.append("")+ lines.append("**Explanation:**")+ lines.append(_clip_text(explanation, limit=2000))++ return "\n".join(lines)+++ async def _build_question_bank_context(- store: SQLiteSessionStore,++ store: SessionStoreProtocol,+ entry_ids: list[Any],+ ) -> str:+ """Fetch the requested Question Bank entries and render them as context."""++ get_entry = getattr(store, "get_notebook_entry", None)++ if not callable(get_entry):++ return ""+++ seen: set[int] = set()+ blocks: list[str] = []+ for raw in entry_ids:+ try:+ entry_id = int(raw)+ except (TypeError, ValueError):+ continue+ if entry_id in seen:+ continue+ seen.add(entry_id)+ try:- entry = await store.get_notebook_entry(entry_id)++ entry = await get_entry(entry_id)+ except Exception:+ entry = None+ if not entry:+ continue+ blocks.append(_format_question_bank_entry(entry))+ return "\n\n---\n\n".join(blocks)++def _extract_followup_question_context(config: dict[str, Any] | None,) -> dict[str, Any] | None:diff --cc web/.env.localindex 4b72a507e,2b04f3785..243c69999--- a/web/.env.local+++ b/web/.env.local@@@ -1,2 -1,2 +1,3 @@@+ # Auto-generated by start_web.py — do not edit manuallyNEXT_PUBLIC_API_BASE=http://localhost:8001+NEXT_PUBLIC_AUTH_ENABLED=falsediff --cc web/app/(auth)/login/page.tsxindex 5f58b996e,000000000..2a1244383mode 100644,000000..100644--- a/web/app/(auth)/login/page.tsx+++ b/web/app/(auth)/login/page.tsx@@@ -1,156 -1,0 +1,170 @@@+"use client";+- import { useState, useEffect } from "react";++import { Suspense, useState, useEffect } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import Link from "next/link";+import { login, fetchAuthStatus, checkIsFirstUser } from "@/lib/auth";+- export default function LoginPage() {++function LoginPageContent() {+ const router = useRouter();+ const searchParams = useSearchParams();+ const next = searchParams.get("next") ?? "/";++ const registered = searchParams.get("registered") === "1";++ const [username, setUsername] = useState("");+ const [password, setPassword] = useState("");+ const [error, setError] = useState("");+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ // If already authenticated, skip login+ fetchAuthStatus().then((status) => {+ if (status?.authenticated) {+ router.replace(next);+ return;+ }+ // No users registered yet — send straight to the registration page+ checkIsFirstUser().then((first) => {+ if (first) router.replace("/register");+ });+ });+ }, [router, next]);++ async function handleSubmit(e: React.FormEvent) {+ e.preventDefault();+ setError("");+ setLoading(true);++ const result = await login(username, password);++ if (result.ok) {+ router.replace(next);+ } else {+ setError(result.error ?? "Login failed");+ setLoading(false);+ }+ }++ return (+ <div className="w-full max-w-sm">+ {/* Logo / Title */}+ <div className="text-center mb-8">+ <h1 className="text-2xl font-semibold text-[var(--foreground)] tracking-tight">+ DeepTutor+ </h1>+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ Sign in to your account+ </p>+ </div>++ {/* Registered success notice */}+ {registered && (+ <div className="mb-4 rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-600 dark:text-green-400">+ Account created! Sign in to continue.+ </div>+ )}++ {/* Card */}+ <div className="bg-[var(--card)] border border-[var(--border)] rounded-2xl shadow-sm px-8 py-8">+ <form onSubmit={handleSubmit} className="space-y-5">+ {/* Email */}+ <div>+ <label+ htmlFor="username"+ className="block text-sm font-medium text-[var(--foreground)] mb-1.5"+ >+ </label>+ <input+ id="username"+ type="email"+ autoComplete="email"+ required+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ className="w-full px-3.5 py-2.5 rounded-lg border border-[var(--border)]+ bg-[var(--background)] text-[var(--foreground)]+ placeholder:text-[var(--muted-foreground)]+ focus:outline-none focus:ring-2 focus:ring-[var(--primary)] focus:border-transparent+ transition-shadow text-sm"+ placeholder="[email protected]"+ />+ </div>++ {/* Password */}+ <div>+ <label+ htmlFor="password"+ className="block text-sm font-medium text-[var(--foreground)] mb-1.5"+ >+ Password+ </label>+ <input+ id="password"+ type="password"+ autoComplete="current-password"+ required+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ className="w-full px-3.5 py-2.5 rounded-lg border border-[var(--border)]+ bg-[var(--background)] text-[var(--foreground)]+ placeholder:text-[var(--muted-foreground)]+ focus:outline-none focus:ring-2 focus:ring-[var(--primary)] focus:border-transparent+ transition-shadow text-sm"+ placeholder="••••••••"+ />+ </div>++ {/* Error message */}+ {error && (+ <p className="text-sm text-red-500 bg-red-500/10 rounded-lg px-3 py-2">+ {error}+ </p>+ )}++ {/* Submit */}+ <button+ type="submit"+ disabled={loading}+ className="w-full py-2.5 px-4 rounded-lg font-medium text-sm+ bg-[var(--primary)] text-[var(--primary-foreground)]+ hover:opacity-90 active:opacity-80+ disabled:opacity-50 disabled:cursor-not-allowed+ transition-opacity"+ >+ {loading ? "Signing in…" : "Sign in"}+ </button>+ </form>+ </div>++ <p className="mt-6 text-center text-sm text-[var(--muted-foreground)]">+ Don't have an account?{" "}+ <Link+ href="/register"+ className="text-[var(--primary)] hover:underline font-medium"+ >+ Create one+ </Link>+ </p>++ <p className="mt-3 text-center text-xs text-[var(--muted-foreground)]">+ DeepTutor · Agent-Native Learning+ </p>+ </div>+ );+}++++export default function LoginPage() {++ return (++ <Suspense++ fallback={++ <div className="w-full max-w-sm text-center text-sm text-[var(--muted-foreground)]">++ Loading sign in...++ </div>++ }++ >++ <LoginPageContent />++ </Suspense>++ );++}diff --cc web/app/(utility)/settings/page.tsxindex c5a54a4aa,0eeaea4c4..8703a5aec--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@@ -18,11 -18,12 +18,12 @@@ importTerminal,Trash2,Wand2,- X,} from "lucide-react";- import { writeStoredLanguage } from "@/context/AppShellContext";- import { apiUrl, apiFetch } from "@/lib/api";+ import { useTranslation } from "react-i18next";++ import { writeStoredLanguage } from "@/context/app-shell-storage";-import { apiUrl } from "@/lib/api";++import { apiFetch, apiUrl } from "@/lib/api";import { setTheme as applyThemePreference } from "@/lib/theme";type ServiceName = "llm" | "embedding" | "search";@@@ -438,33 -360,18 +360,32 @@@ function SettingsPageContent()useEffect(() => {const load = async () => {- const settingsResponse = await fetch(apiUrl("/api/v1/settings"));- const settingsPayload =- (await settingsResponse.json()) as SettingsPayload;- setCatalog(settingsPayload.catalog);- setDraft(cloneCatalog(settingsPayload.catalog));- setTheme(settingsPayload.ui.theme);- setLanguage(settingsPayload.ui.language);- if (settingsPayload.providers) setProviders(settingsPayload.providers);-- const statusResponse = await fetch(apiUrl("/api/v1/system/status"));- const statusPayload = (await statusResponse.json()) as SystemStatus;- setStatus(statusPayload);+ try {+ const settingsResponse = await apiFetch(apiUrl("/api/v1/settings"));- if (!settingsResponse.ok)++ if (!settingsResponse.ok) {+ throw new Error(`Settings fetch failed: ${settingsResponse.status}`);++ }+ const settingsPayload =+ (await settingsResponse.json()) as SettingsPayload;- if (settingsPayload?.catalog) {- setCatalog(settingsPayload.catalog);- setDraft(cloneCatalog(settingsPayload.catalog));- }- if (settingsPayload?.ui) {- setTheme(settingsPayload.ui.theme);- setLanguage(settingsPayload.ui.language);- }++ setCatalog(settingsPayload.catalog);++ setDraft(cloneCatalog(settingsPayload.catalog));++ setTheme(settingsPayload.ui.theme);++ setLanguage(settingsPayload.ui.language);++ if (settingsPayload.providers) setProviders(settingsPayload.providers);+ } catch (err) {+ console.error("Failed to load settings:", err);+ }++ try {+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));- if (!statusResponse.ok)++ if (!statusResponse.ok) {+ throw new Error(`Status fetch failed: ${statusResponse.status}`);++ }+ const statusPayload = (await statusResponse.json()) as SystemStatus;+ setStatus(statusPayload);+ } catch (err) {+ console.error("Failed to load system status:", err);+ }};load();return () => {@@@ -532,10 -422,10 +436,10 @@@// -- UI preference helpers ----------------------------------------------const persistUi = async (- nextTheme: "light" | "dark",+ nextTheme: "light" | "dark" | "glass" | "snow",nextLanguage: "en" | "zh",) => {- await fetch(apiUrl("/api/v1/settings/ui"), {+ await apiFetch(apiUrl("/api/v1/settings/ui"), {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ theme: nextTheme, language: nextLanguage }),@@@ -691,8 -627,8 +641,8 @@@const payload = await response.json();setCatalog(payload.catalog);setDraft(cloneCatalog(payload.catalog));- setToast("Applied to .env");+ setToast(t("Applied to .env"));- const statusResponse = await fetch(apiUrl("/api/v1/system/status"));+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));setStatus((await statusResponse.json()) as SystemStatus);} finally {setApplying(false);@@@ -709,7 -645,7 +659,7 @@@setLogs(`Preparing ${activeService} diagnostics...\n`);setTestRunning(activeService);try {-- const response = await fetch(++ const response = await apiFetch(apiUrl(`/api/v1/settings/tests/${activeService}/start`),{method: "POST",diff --cc web/app/(workspace)/agents/page.tsxindex 1b7c2b280,c188f584a..8da93ff6b--- a/web/app/(workspace)/agents/page.tsx+++ b/web/app/(workspace)/agents/page.tsx@@@ -16,8 -19,9 +19,9 @@@ importX,} from "lucide-react";import { useRouter } from "next/navigation";+ import { useTranslation } from "react-i18next";import dynamic from "next/dynamic";--import { apiUrl } from "@/lib/api";++import { apiFetch, apiUrl } from "@/lib/api";const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"),@@@ -75,9 -88,8 +88,9 @@@ export default function AgentsPage()const loadBots = useCallback(async () => {setLoading(true);try {-- const res = await fetch(apiUrl("/api/v1/tutorbot"));- setBots(await res.json());++ const res = await apiFetch(apiUrl("/api/v1/tutorbot"));+ const data = await res.json();+ setBots(Array.isArray(data) ? data : (data.bots ?? []));} finally {setLoading(false);}@@@ -85,7 -97,7 +98,7 @@@const loadSouls = useCallback(async () => {try {-- const res = await fetch(apiUrl("/api/v1/tutorbot/souls"));++ const res = await apiFetch(apiUrl("/api/v1/tutorbot/souls"));if (res.ok) setSouls(await res.json());} catch {/* ignore */@@@ -161,6 -187,632 +188,632 @@@);}+ /* ── Channels tab (schema-driven, all channels) ─────────── */++ /**+ * JSON-Schema fragment subset we actually consume. Pydantic emits richer+ * shapes (allOf / examples / formats) that we ignore — the form gracefully+ * falls back to a text input for anything it doesn't recognise.+ */+ type JsonSchema = {+ type?: string | string[];+ title?: string;+ description?: string;+ default?: unknown;+ enum?: unknown[];+ properties?: Record<string, JsonSchema>;+ items?: JsonSchema;+ anyOf?: JsonSchema[];+ };++ interface ChannelSchemaEntry {+ name: string;+ display_name: string;+ default_config: Record<string, unknown>;+ secret_fields: string[];+ json_schema: JsonSchema;+ }++ interface ChannelsSchemaResponse {+ channels: Record<string, ChannelSchemaEntry>;+ global: { json_schema: JsonSchema; secret_fields: string[] };+ }++ /** Pick the first non-null variant of an `anyOf` and merge its meta. */+ function resolveSchemaVariant(s: JsonSchema): JsonSchema {+ if (!s.anyOf) return s;+ const first = s.anyOf.find((v) => v.type !== "null") ?? s.anyOf[0];+ return {+ ...first,+ title: s.title ?? first.title,+ description: s.description ?? first.description,+ };+ }++ /** True iff this schema's value can be `null` (e.g. `Optional[str]`). */+ function isNullable(s: JsonSchema): boolean {+ if (Array.isArray(s.type) && s.type.includes("null")) return true;+ if (s.anyOf?.some((v) => v.type === "null")) return true;+ return false;+ }++ /** Default value for a property when the live config doesn't set it. */+ function defaultFor(s: JsonSchema): unknown {+ if (s.default !== undefined) return s.default;+ const v = resolveSchemaVariant(s);+ switch (v.type) {+ case "boolean":+ return false;+ case "integer":+ case "number":+ return 0;+ case "array":+ return [];+ case "object":+ return {};+ case "string":+ default:+ return "";+ }+ }++ /** Title-case a snake_case key when no `title` is provided. */+ function humaniseKey(k: string): string {+ return k.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());+ }++ /** Generic field renderer — recursive for nested objects. */+ function SchemaField({+ fieldKey,+ schema,+ value,+ onChange,+ secretFields,+ path,+ showSecretFor,+ toggleSecret,+ }: {+ fieldKey: string;+ schema: JsonSchema;+ value: unknown;+ onChange: (next: unknown) => void;+ secretFields: Set<string>;+ path: string;+ showSecretFor: Set<string>;+ toggleSecret: (path: string) => void;+ }) {+ const v = resolveSchemaVariant(schema);+ const label = schema.title || v.title || humaniseKey(fieldKey);+ const description = schema.description || v.description;+ const isSecret = secretFields.has(path);+ const enumValues = (v.enum ?? schema.enum) as unknown[] | undefined;++ // Boolean → checkbox row (label inline).+ if (v.type === "boolean") {+ return (+ <label className="flex items-start gap-2 text-[13px]">+ <input+ type="checkbox"+ checked={!!value}+ onChange={(e) => onChange(e.target.checked)}+ className="mt-0.5"+ />+ <span>+ {label}+ {description && (+ <span className="ml-1 text-[11px] text-[var(--muted-foreground)]">+ — {description}+ </span>+ )}+ </span>+ </label>+ );+ }++ // Enum / Literal → select.+ if (Array.isArray(enumValues) && enumValues.length > 0) {+ return (+ <div>+ <FieldLabel label={label} description={description} />+ <select+ value={String(value ?? "")}+ onChange={(e) => onChange(e.target.value)}+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"+ >+ {enumValues.map((opt) => (+ <option key={String(opt)} value={String(opt)}>+ {String(opt)}+ </option>+ ))}+ </select>+ </div>+ );+ }++ // Array of strings → textarea (one per line). For non-string arrays we+ // fall through to JSON editing below.+ if (v.type === "array" && (v.items?.type === "string" || !v.items)) {+ const lines = Array.isArray(value) ? (value as unknown[]).map(String) : [];+ return (+ <div>+ <FieldLabel+ label={label}+ description={description ?? "One value per line"}+ />+ <textarea+ value={lines.join("\n")}+ onChange={(e) =>+ onChange(+ e.target.value+ .split("\n")+ .map((s) => s.trim())+ .filter(Boolean),+ )+ }+ rows={Math.max(3, Math.min(8, lines.length + 1))}+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] outline-none focus:border-[var(--ring)]"+ />+ </div>+ );+ }++ // Nested object → recursive fieldset.+ if (v.type === "object" && v.properties) {+ const obj = (value && typeof value === "object" ? value : {}) as Record<+ string,+ unknown+ >;+ return (+ <fieldset className="rounded-lg border border-[var(--border)]/60 px-3 py-2.5 space-y-2.5">+ <legend className="px-1 text-[12px] font-medium text-[var(--muted-foreground)]">+ {label}+ </legend>+ {description && (+ <p className="text-[11px] text-[var(--muted-foreground)]">+ {description}+ </p>+ )}+ {Object.entries(v.properties).map(([k, child]) => (+ <SchemaField+ key={k}+ fieldKey={k}+ schema={child}+ value={obj[k] ?? defaultFor(child)}+ onChange={(next) => onChange({ ...obj, [k]: next })}+ secretFields={secretFields}+ path={path ? `${path}.${k}` : k}+ showSecretFor={showSecretFor}+ toggleSecret={toggleSecret}+ />+ ))}+ </fieldset>+ );+ }++ // Integer/number → number input.+ if (v.type === "integer" || v.type === "number") {+ return (+ <div>+ <FieldLabel label={label} description={description} />+ <input+ type="number"+ value={typeof value === "number" ? value : ""}+ onChange={(e) => {+ const raw = e.target.value;+ if (raw === "") onChange(isNullable(schema) ? null : 0);+ else+ onChange(+ v.type === "integer" ? parseInt(raw, 10) : parseFloat(raw),+ );+ }}+ className="w-40 rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"+ />+ </div>+ );+ }++ // Default: string input (with secret reveal handling).+ const reveal = showSecretFor.has(path);+ const strVal = value == null ? "" : String(value);+ return (+ <div>+ <FieldLabel label={label} description={description} />+ <div className="relative">+ <input+ type={isSecret && !reveal ? "password" : "text"}+ autoComplete={isSecret ? "new-password" : "off"}+ spellCheck={!isSecret}+ value={strVal}+ onChange={(e) => {+ const next = e.target.value;+ // Empty optional strings persist as null (matches Pydantic's+ // `Optional[str]` default and avoids "" sneaking past validators).+ onChange(next === "" && isNullable(schema) ? null : next);+ }}+ className={`w-full rounded-lg border border-[var(--border)] bg-transparent py-2 pl-3 ${isSecret ? "pr-10 font-mono" : "pr-3"} text-[13px] outline-none focus:border-[var(--ring)]`}+ />+ {isSecret && (+ <button+ type="button"+ onClick={() => toggleSecret(path)}+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ aria-label={reveal ? "Hide secret" : "Show secret"}+ title={reveal ? "Hide secret" : "Show secret"}+ >+ {reveal ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </button>+ )}+ </div>+ </div>+ );+ }++ function FieldLabel({+ label,+ description,+ }: {+ label: string;+ description?: string;+ }) {+ return (+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">+ {label}+ {description && (+ <span className="ml-1 font-normal opacity-70">— {description}</span>+ )}+ </label>+ );+ }++ function ChannelsTab({+ bots,+ loading,+ onToast,+ onReload,+ }: {+ bots: BotInfo[];+ loading: boolean;+ onToast: (msg: string) => void;+ onReload: () => Promise<void>;+ }) {+ const { t } = useTranslation();+ const [selectedBot, setSelectedBot] = useState("");+ const [schemaCatalog, setSchemaCatalog] =+ useState<ChannelsSchemaResponse | null>(null);+ const [channels, setChannels] = useState<Record<string, unknown>>({});+ const [activeChannel, setActiveChannel] = useState<string | null>(null);+ const [reloadError, setReloadError] = useState<string | null>(null);+ const [loadingDetail, setLoadingDetail] = useState(false);+ const [saving, setSaving] = useState(false);+ /** dot-paths of secrets the user has explicitly toggled to plaintext. */+ const [revealed, setRevealed] = useState<Set<string>>(new Set());++ // One-time fetch of the channel schema catalog. Cheap and never changes+ // at runtime (channels are discovered at process start).+ useEffect(() => {+ void (async () => {+ try {- const res = await fetch(apiUrl("/api/v1/tutorbot/channels/schema"));++ const res = await apiFetch(apiUrl("/api/v1/tutorbot/channels/schema"));+ if (res.ok) setSchemaCatalog(await res.json());+ } catch {+ /* leave catalog null → renders fallback message */+ }+ })();+ }, []);++ useEffect(() => {+ if (bots.length > 0 && !selectedBot) setSelectedBot(bots[0].bot_id);+ }, [bots, selectedBot]);++ useEffect(() => {+ setRevealed(new Set());+ setReloadError(null);+ }, [selectedBot]);++ const loadDetail = useCallback(async (bid: string) => {+ if (!bid) return;+ setLoadingDetail(true);+ try {+ // Edit form needs raw secrets to populate fields. Default GET masks them.- const res = await fetch(++ const res = await apiFetch(+ apiUrl(`/api/v1/tutorbot/${bid}?include_secrets=true`),+ );+ if (!res.ok) return;+ const data = await res.json();+ const raw = (data.channels ?? {}) as Record<string, unknown>;+ // Surface globals as-is; per-channel dicts are passed straight to the+ // SchemaForm which handles per-field defaults from the JSON schema.+ setChannels({+ send_progress: raw.send_progress !== false,+ send_tool_hints: !!raw.send_tool_hints,+ ...Object.fromEntries(+ Object.entries(raw).filter(+ ([k]) => k !== "send_progress" && k !== "send_tool_hints",+ ),+ ),+ });+ setReloadError(+ typeof data.last_reload_error === "string"+ ? data.last_reload_error+ : null,+ );+ } finally {+ setLoadingDetail(false);+ }+ }, []);++ useEffect(() => {+ if (selectedBot) void loadDetail(selectedBot);+ }, [selectedBot, loadDetail]);++ // Pick a sensible default active channel: prefer one already enabled,+ // otherwise the first channel in the catalog.+ useEffect(() => {+ if (activeChannel || !schemaCatalog) return;+ const names = Object.keys(schemaCatalog.channels);+ const enabled = names.find((n) => {+ const cfg = channels[n];+ return (+ cfg &&+ typeof cfg === "object" &&+ (cfg as Record<string, unknown>).enabled === true+ );+ });+ setActiveChannel(enabled ?? names[0] ?? null);+ }, [schemaCatalog, channels, activeChannel]);++ const toggleSecret = useCallback((path: string) => {+ setRevealed((prev) => {+ const next = new Set(prev);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ return next;+ });+ }, []);++ const setActiveChannelConfig = (next: unknown) => {+ if (!activeChannel) return;+ setChannels((prev) => ({ ...prev, [activeChannel]: next }));+ };++ const save = async () => {+ if (!selectedBot) return;+ setSaving(true);+ try {- const res = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ channels }),+ });+ if (res.ok) {+ onToast(t("Channels saved"));+ await Promise.all([onReload(), loadDetail(selectedBot)]);+ } else if (res.status === 422) {+ const err = (await res.json().catch(() => ({}))) as {+ detail?: { message?: string; errors?: unknown } | string;+ };+ const detail = err.detail;+ const msg =+ typeof detail === "string"+ ? detail+ : (detail?.message ?? t("Invalid channel configuration"));+ onToast(msg);+ } else {+ const err = (await res.json().catch(() => ({}))) as { detail?: string };+ onToast(err.detail ?? t("Save failed"));+ }+ } finally {+ setSaving(false);+ }+ };++ if (loading) {+ return (+ <div className="flex min-h-[320px] items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ );+ }++ if (bots.length === 0) {+ return (+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">+ <p className="text-[14px] font-medium text-[var(--foreground)]">+ {t("No bots to configure")}+ </p>+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">+ {t("Create a bot first in the Bots tab.")}+ </p>+ </div>+ );+ }++ const channelEntries = schemaCatalog+ ? Object.entries(schemaCatalog.channels).sort(([, a], [, b]) =>+ a.display_name.localeCompare(b.display_name),+ )+ : [];+ const activeEntry = activeChannel+ ? schemaCatalog?.channels[activeChannel]+ : undefined;+ const activeValue =+ activeChannel &&+ channels[activeChannel] &&+ typeof channels[activeChannel] === "object"+ ? (channels[activeChannel] as Record<string, unknown>)+ : (activeEntry?.default_config ?? {});+ const activeSecretSet = new Set(activeEntry?.secret_fields ?? []);++ return (+ <div className="space-y-5">+ <div className="flex flex-wrap items-center gap-3">+ <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">+ {t("Bot")}+ </label>+ <select+ value={selectedBot}+ onChange={(e) => setSelectedBot(e.target.value)}+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ >+ {bots.map((b) => (+ <option key={b.bot_id} value={b.bot_id}>+ {b.name} ({b.bot_id})+ </option>+ ))}+ </select>+ <button+ type="button"+ onClick={() => void save()}+ disabled={saving || loadingDetail}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"+ >+ {saving ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Save className="h-3.5 w-3.5" />+ )}+ {t("Save")}+ </button>+ </div>++ {reloadError && (+ <div className="rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-300">+ <strong className="font-medium">+ {t("Channel listeners failed to restart:")}+ </strong>{" "}+ <span className="font-mono">{reloadError}</span>{" "}+ <span className="opacity-80">+ {t("Config is saved on disk; stop and start the bot to apply.")}+ </span>+ </div>+ )}++ {loadingDetail || !schemaCatalog ? (+ <div className="flex justify-center py-8">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : (+ <>+ {/* Globals (Delivery) */}+ <div className="rounded-xl border border-[var(--border)] p-4 space-y-3">+ <h3 className="text-[13px] font-medium text-[var(--foreground)]">+ {t("Delivery")}+ </h3>+ <label className="flex items-center gap-2 text-[13px]">+ <input+ type="checkbox"+ checked={!!channels.send_progress}+ onChange={(e) =>+ setChannels((c) => ({+ ...c,+ send_progress: e.target.checked,+ }))+ }+ />+ {t("Stream progress text to channels")}+ </label>+ <label className="flex items-center gap-2 text-[13px]">+ <input+ type="checkbox"+ checked={!!channels.send_tool_hints}+ onChange={(e) =>+ setChannels((c) => ({+ ...c,+ send_tool_hints: e.target.checked,+ }))+ }+ />+ {t("Stream tool hints to channels")}+ </label>+ </div>++ {/* Channel master-detail */}+ <div className="grid grid-cols-1 gap-4 md:grid-cols-[180px_1fr]">+ <aside className="rounded-xl border border-[var(--border)] p-2 h-fit">+ <ul className="space-y-0.5">+ {channelEntries.map(([name, entry]) => {+ const cfg = channels[name] as+ | Record<string, unknown>+ | undefined;+ const enabled = cfg?.enabled === true;+ const isActive = activeChannel === name;+ return (+ <li key={name}>+ <button+ type="button"+ onClick={() => setActiveChannel(name)}+ className={`group flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-left text-[13px] transition-colors ${+ isActive+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <span className="truncate">{entry.display_name}</span>+ {enabled && (+ <span+ aria-label={t("Enabled")}+ title={t("Enabled")}+ className="ml-2 h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"+ />+ )}+ </button>+ </li>+ );+ })}+ </ul>+ </aside>++ <section className="rounded-xl border border-[var(--border)] p-4 space-y-3">+ {!activeEntry ? (+ <p className="text-[13px] text-[var(--muted-foreground)]">+ {t("Select a channel.")}+ </p>+ ) : (+ <>+ <div className="flex items-baseline justify-between">+ <h3 className="text-[14px] font-medium text-[var(--foreground)]">+ {activeEntry.display_name}+ </h3>+ <code className="text-[11px] text-[var(--muted-foreground)]">+ {activeEntry.name}+ </code>+ </div>+ {activeEntry.json_schema.description && (+ <p className="text-[11px] text-[var(--muted-foreground)]">+ {activeEntry.json_schema.description}+ </p>+ )}+ {Object.entries(activeEntry.json_schema.properties ?? {}).map(+ ([k, child]) => (+ <SchemaField+ key={k}+ fieldKey={k}+ schema={child}+ value={activeValue[k] ?? defaultFor(child)}+ onChange={(next) =>+ setActiveChannelConfig({ ...activeValue, [k]: next })+ }+ secretFields={activeSecretSet}+ path={k}+ showSecretFor={revealed}+ toggleSecret={toggleSecret}+ />+ ),+ )}+ </>+ )}+ </section>+ </div>+ </>+ )}+ </div>+ );+ }+/* ── Bots Tab ───────────────────────────────────────────── */function BotsTab({@@@ -216,7 -879,7 +880,7 @@@if (!botId) return;setCreating(true);try {-- const res = await fetch(apiUrl("/api/v1/tutorbot"), {++ const res = await apiFetch(apiUrl("/api/v1/tutorbot"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@@ -240,7 -914,7 +915,7 @@@const startBot = useCallback(async (bid: string) => {-- const res = await fetch(apiUrl("/api/v1/tutorbot"), {++ const res = await apiFetch(apiUrl("/api/v1/tutorbot"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ bot_id: bid }),@@@ -255,7 -929,7 +930,7 @@@const stopBot = useCallback(async (bid: string) => {-- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}`), {method: "DELETE",});if (res.ok) {@@@ -274,7 -951,7 +952,7 @@@))return;-- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), {method: "DELETE",});if (res.ok) {@@@ -540,7 -1256,7 +1257,7 @@@ function ProfilesTab(if (!bid) return;setLoadingFiles(true);try {-- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));const data: Record<string, string> = await res.json();setFiles(data);setEditor(data[activeFile] ?? "");@@@ -557,14 -1276,123 +1277,123 @@@useEffect(() => {setEditor(files[activeFile] ?? "");+ if (activeFile === "SOUL.md") {+ const matched = matchSoulId(files["SOUL.md"] ?? "");+ setSelectedSoulId(matched);+ setSourceSoulId(matched === "_custom" ? null : matched);+ }setActiveView("edit");- }, [activeFile, files]);+ }, [activeFile, files, matchSoulId]);- const saveFile = useCallback(async () => {- if (!selectedBot) return;+ const applySoulSelection = useCallback(+ (nextId: string) => {+ if (nextId === "_custom") {+ setSelectedSoulId("_custom");+ setSourceSoulId(null);+ return;+ }+ const soul = souls.find((s) => s.id === nextId);+ if (!soul) return;+ setSelectedSoulId(nextId);+ setSourceSoulId(nextId);+ setEditor(soul.content);+ },+ [souls],+ );++ const handleSoulSelect = useCallback(+ (nextId: string) => {+ if (hasChanges) {+ setPendingSoulId(nextId);+ setReplaceModalOpen(true);+ return;+ }+ applySoulSelection(nextId);+ },+ [applySoulSelection, hasChanges],+ );++ const saveFile = useCallback(async (+ mode: "file_only" | "update_template" | "new_template",+ createTemplateName?: string,+ ) => {+ if (!selectedBot) return false;setSaving(true);try {- const res = await fetch(+ if (activeFile === "SOUL.md") {+ const content = editor.trim();+ if (!content) {+ onToast(t("SOUL.md is empty"));+ return false;+ }+ if (mode === "update_template") {+ if (!sourceSoulTemplate) {+ onToast(t("No template selected to update"));+ return false;+ }- const tplRes = await fetch(++ const tplRes = await apiFetch(+ apiUrl(`/api/v1/tutorbot/souls/${sourceSoulTemplate.id}`),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: sourceSoulTemplate.name,+ content: editor,+ }),+ },+ );+ if (!tplRes.ok) {+ onToast(t("Failed to update soul template"));+ return false;+ }+ await onReloadSouls();+ setSelectedSoulId(sourceSoulTemplate.id);+ setSourceSoulId(sourceSoulTemplate.id);+ } else if (mode === "new_template") {+ const rawName = (createTemplateName ?? "").trim();+ if (!rawName) {+ onToast(t("Template name is required"));+ return false;+ }+ const baseId = rawName+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");+ if (!baseId) {+ onToast(t("Please choose a name with letters or numbers"));+ return false;+ }+ const existing = new Set(souls.map((s) => s.id));+ let soulId = baseId;+ let n = 2;+ while (existing.has(soulId)) {+ soulId = `${baseId}-${n}`;+ n += 1;+ }- const tplRes = await fetch(apiUrl("/api/v1/tutorbot/souls"), {++ const tplRes = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id: soulId,+ name: rawName,+ content: editor,+ }),+ });+ if (tplRes.status === 409) {+ onToast(t("A soul with this id already exists, try another name"));+ return false;+ }+ if (!tplRes.ok) {+ onToast(t("Failed to save soul template"));+ return false;+ }+ await onReloadSouls();+ setSelectedSoulId(soulId);+ setSourceSoulId(soulId);+ }+ }+- const res = await fetch(++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`),{method: "PUT",@@@ -574,8 -1402,21 +1403,21 @@@);if (res.ok) {setFiles((prev) => ({ ...prev, [activeFile]: editor }));+ if (activeFile === "SOUL.md") {- const personaRes = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {++ const personaRes = await apiFetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ persona: editor }),+ });+ if (!personaRes.ok) {+ onToast(t("SOUL.md saved, but persona sync failed"));+ return false;+ }+ }onToast(`${activeFile} saved`);+ return true;}+ return false;} finally {setSaving(false);}@@@ -769,7 -1796,7 +1797,7 @@@ function SoulsTab(if (!editing) return;setSaving(true);try {-- const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${editing}`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/souls/${editing}`), {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: editName.trim(), content: editContent }),@@@ -794,7 -1821,7 +1822,7 @@@if (!id) return;setSaving(true);try {-- const res = await fetch(apiUrl("/api/v1/tutorbot/souls"), {++ const res = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ id, name, content: newContent }),@@@ -815,8 -1842,9 +1843,9 @@@const deleteSoul = useCallback(async (soul: SoulTemplate) => {- if (!window.confirm(`Delete soul "${soul.name}"?`)) return;- const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), {+ if (!window.confirm(t('Delete soul "{{name}}"?', { name: soul.name })))+ return;- const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), {method: "DELETE",});if (res.ok) {