Skip to content

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

feat: add optional PocketBase integration for auth and session storage

xor_xe6ca2ecd64f61
diff --git a/.env.example b/.env.example
index 7e0b6403e..886096cc4 100644
--- a/.env.example
+++ b/.env.example
@@ -10,6 +10,7 @@
# --------------------------------------------
BACKEND_PORT=8001
FRONTEND_PORT=3782
+POCKETBASE_PORT=8090
# --------------------------------------------
# LLM (Required)
@@ -68,6 +69,28 @@ 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)
# --------------------------------------------
diff --git a/.gitignore b/.gitignore
index f1f9bdd3c..ebeb880ee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -54,6 +54,7 @@ MANIFEST
# Virtual Environments
.env
*.env
+*.env.local
!.env.example
env/
venv/
diff --git a/README.md b/README.md
index 876552da4..c237a7cc6 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,7 @@
- **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.
- **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.
- **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.
+- **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.
---
@@ -336,6 +336,47 @@ priority over `AUTH_USERNAME` / `AUTH_PASSWORD_HASH`.
</details>
+<details>
+<summary><b>PocketBase sidecar (optional auth + storage)</b></summary>
+
+PocketBase is an optional lightweight backend that replaces the built-in SQLite/JSON auth and session storage. It adds OAuth-ready authentication, real-time subscriptions, and a visual admin panel — with zero changes required to switch back if you don't set `POCKETBASE_URL`.
+
+**When to use it:** public deployments where you want OAuth later, or multi-user setups that need better concurrency than the default SQLite lock.
+
+**Quick start (Docker Compose):**
+
+```bash
+# PocketBase starts automatically alongside DeepTutor when using docker compose
+docker compose up -d
+
+# 1. Open the admin panel and create your admin account
+open http://localhost:8090/_/
+
+# 2. Bootstrap collections (run once)
+pip install pocketbase
+python scripts/pb_setup.py
+
+# 3. Enable PocketBase in .env and restart
+```
+
+**Required `.env` additions:**
+
+```dotenv
+POCKETBASE_URL=http://localhost:8090 # or http://pocketbase:8090 inside Docker
+POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```
+
+**devenv users:**
+
+```bash
+devenv up # starts PocketBase on :8090 alongside backend and frontend
+```
+
+Leave `POCKETBASE_URL` unset (or remove it) to fall back to the built-in SQLite backend at any time — no data migration needed for new sessions.
+
+</details>
+
<details>
<summary><b>Development mode (hot-reload)</b></summary>
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index 349ac0b6b..ec74e0554 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -1,5 +1,6 @@
from contextlib import asynccontextmanager
import logging
+import os
from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
@@ -110,6 +111,14 @@ async def lifespan(app: FastAPI):
except Exception as e:
logger.warning(f"Failed to auto-start TutorBots: {e}")
+ # Ping PocketBase if configured — logs a warning (not an error) if unreachable
+ try:
+ from deeptutor.services.pocketbase_client import ping_pocketbase
+
+ await ping_pocketbase()
+ except Exception as e:
+ logger.warning(f"PocketBase startup check failed: {e}")
+
yield
# Execute on shutdown
@@ -164,10 +173,24 @@ async def selective_access_log(request, call_next):
return response
-# Configure CORS
+# Configure CORS.
+# allow_origins=["*"] is incompatible with allow_credentials=True (browsers reject it).
+# We build an explicit list that covers both localhost and 127.0.0.1 variants so the
+# frontend works regardless of which loopback alias the browser resolves to.
+_frontend_port = os.getenv("FRONTEND_PORT", "3782")
+_extra_origin = os.getenv("CORS_ORIGIN", "") # optional extra origin for deployments
+_cors_origins = [
+ f"http://localhost:{_frontend_port}",
+ f"http://127.0.0.1:{_frontend_port}",
+ "http://localhost:3000", # common Next.js default
+ "http://127.0.0.1:3000",
+]
+if _extra_origin:
+ _cors_origins.append(_extra_origin)
+
app.add_middleware(
CORSMiddleware,
- allow_origins=["*"], # In production, replace with specific frontend origin
+ allow_origins=_cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index cff04475a..4b91a02dc 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -1,21 +1,33 @@
"""Auth router — login, logout, status, registration, and user-management endpoints."""
+import os
+
from fastapi import APIRouter, Cookie, Depends, HTTPException, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, field_validator
+# SameSite=None lets the cookie work when the browser accesses the frontend via
+# 127.0.0.1 and the backend via localhost (different origins on the same machine).
+# Browsers require Secure=True for SameSite=None, but that needs HTTPS — so in
+# local dev we fall back to SameSite=Lax and tell users to use localhost:// URLs.
+_SECURE = os.getenv("AUTH_COOKIE_SECURE", "false").lower() == "true"
+_SAMESITE = "none" if _SECURE else "lax"
+
from deeptutor.logging import get_logger
from deeptutor.services.auth import (
AUTH_ENABLED,
+ POCKETBASE_ENABLED,
TOKEN_EXPIRE_HOURS,
TokenPayload,
add_user,
authenticate,
+ authenticate_pb,
create_token,
decode_token,
delete_user,
is_first_user,
list_users,
+ register_pb,
set_role,
)
@@ -49,16 +61,17 @@ class RegisterRequest(BaseModel):
@field_validator("username")
@classmethod
def username_valid(cls, v: str) -> str:
+ import re
+
v = v.strip()
if not v:
- raise ValueError("Username cannot be empty")
- if len(v) < 3:
- raise ValueError("Username must be at least 3 characters")
- if len(v) > 32:
- raise ValueError("Username must be at most 32 characters")
- allowed = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.")
- if not all(c in allowed for c in v):
- raise ValueError("Username may only contain letters, digits, -, _, and .")
+ raise ValueError("Email cannot be empty")
+ # Accept standard email addresses (used by PocketBase mode) or plain
+ # usernames (used by the built-in SQLite/JSON auth mode).
+ email_re = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+ plain_re = re.compile(r"^[A-Za-z0-9_\-.]{3,64}$")
+ if not email_re.match(v) and not plain_re.match(v):
+ raise ValueError("Enter a valid email address")
return v
@field_validator("password")
@@ -207,6 +220,28 @@ async def login(body: LoginRequest, response: Response) -> dict:
if not AUTH_ENABLED:
return {"ok": True, "message": "Auth is disabled — no login required."}
+ if POCKETBASE_ENABLED:
+ # PocketBase mode: email = username field for backwards-compat with the
+ # existing LoginRequest schema; users can pass their email as "username".
+ pb_result = authenticate_pb(body.username, body.password)
+ if not pb_result:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Incorrect email or password",
+ )
+ payload, pb_token = pb_result
+ response.set_cookie(
+ key=_COOKIE_NAME,
+ value=pb_token,
+ httponly=True,
+ samesite=_SAMESITE,
+ max_age=_COOKIE_MAX_AGE,
+ secure=_SECURE,
+ )
+ logger.info(f"User '{payload.username}' logged in via PocketBase (role={payload.role!r})")
+ return {"ok": True, "username": payload.username, "role": payload.role}
+
+ # Standard JWT + bcrypt mode
result = authenticate(body.username, body.password)
if not result:
raise HTTPException(
@@ -219,9 +254,9 @@ async def login(body: LoginRequest, response: Response) -> dict:
key=_COOKIE_NAME,
value=token,
httponly=True,
- samesite="lax",
+ samesite=_SAMESITE,
max_age=_COOKIE_MAX_AGE,
- secure=False, # Set to True when served over HTTPS
+ secure=_SECURE,
)
logger.info(f"User '{result.username}' logged in (role={result.role!r})")
@@ -231,7 +266,7 @@ async def login(body: LoginRequest, response: Response) -> dict:
@router.post("/logout")
async def logout(response: Response) -> dict:
"""Clear the JWT cookie."""
- response.delete_cookie(key=_COOKIE_NAME, samesite="lax")
+ response.delete_cookie(key=_COOKIE_NAME, samesite=_SAMESITE)
return {"ok": True}
@@ -240,8 +275,8 @@ async def register(body: RegisterRequest) -> dict:
"""
Create a new user account.
- The very first user to register is automatically granted admin privileges.
- Subsequent registrations create regular users.
+ In PocketBase mode, the username is also used as the email address.
+ In standard mode, the first user to register is automatically granted admin.
Only available when AUTH_ENABLED=true.
"""
@@ -251,10 +286,18 @@ async def register(body: RegisterRequest) -> dict:
detail="Auth is disabled — registration is not available.",
)
- # Check whether this will be the first (admin) user before writing
+ if POCKETBASE_ENABLED:
+ result = register_pb(username=body.username, email=body.username, password=body.password)
+ if not result:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="Registration failed — username or email may already be taken.",
+ )
+ logger.info(f"New user registered via PocketBase: '{body.username}'")
+ return {"ok": True, "username": body.username, "role": "user", "is_first_user": False}
+
+ # Standard mode
first = is_first_user()
-
- # Prevent duplicate usernames
existing = {u["username"] for u in list_users()}
if body.username in existing:
raise HTTPException(
diff --git a/deeptutor/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.py
index 3cdeab582..ee32e4f68 100644
--- a/deeptutor/api/routers/dashboard.py
+++ b/deeptutor/api/routers/dashboard.py
@@ -4,14 +4,14 @@ from typing import Any
from fastapi import APIRouter, HTTPException
-from deeptutor.services.session import get_sqlite_session_store
+from deeptutor.services.session import get_session_store
router = APIRouter()
@router.get("/recent")
async def get_recent_activities(limit: int = 50, type: str | None = None):
- store = get_sqlite_session_store()
+ store = get_session_store()
sessions = await store.list_sessions(limit=limit, offset=0)
activities: list[dict[str, Any]] = []
@@ -40,7 +40,7 @@ async def get_recent_activities(limit: int = 50, type: str | None = None):
@router.get("/{entry_id}")
async def get_activity_entry(entry_id: str):
- store = get_sqlite_session_store()
+ store = get_session_store()
session = await store.get_session_with_messages(entry_id)
if session is None:
raise HTTPException(status_code=404, detail="Entry not found")
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index d5818726d..cc6475860 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -32,14 +32,13 @@ from deeptutor.knowledge.add_documents import DocumentAdder
from deeptutor.knowledge.initializer import KnowledgeBaseInitializer
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+from deeptutor.logging import get_logger
+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.rag.components.routing import FileTypeRouter
from deeptutor.services.rag.factory import DEFAULT_PROVIDER, has_pipeline, normalize_provider_name
from deeptutor.utils.document_validator import DocumentValidator
from deeptutor.utils.error_utils import format_exception_message
-from deeptutor.logging import get_logger
-from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
-
# Initialize logger with config
config = load_config_with_main("main.yaml", PROJECT_ROOT)
log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
@@ -109,10 +108,22 @@ def _save_uploaded_files(
files: 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] = []
+ from deeptutor.services.pocketbase_client import is_pocketbase_enabled
+
+ _pb_sync = is_pocketbase_enabled() and bool(kb_name)
+
for file in files:
file_path = None
original_filename = file.filename or "upload"
@@ -142,6 +153,16 @@ def _save_uploaded_files(
)
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:
@@ -158,6 +179,29 @@ def _save_uploaded_files(
return uploaded_files, uploaded_file_paths
+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)
@@ -232,7 +276,10 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
_task_log(task_id, "Finalizing initialization")
initializer.progress_tracker.update(
- ProgressStage.COMPLETED, "Knowledge base initialization complete!", current=1, total=1
+ ProgressStage.COMPLETED,
+ "Knowledge base initialization complete!",
+ current=1,
+ total=1,
)
manager = get_kb_manager()
@@ -250,7 +297,9 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
},
)
- _task_log(task_id, f"Knowledge base '{initializer.kb_name}' initialized", level="success")
+ _task_log(
+ task_id, f"Knowledge base '{initializer.kb_name}' initialized", level="success"
+ )
task_manager.update_task_status(task_id, "completed")
task_stream_manager.emit_complete(
task_id, f"Knowledge base '{initializer.kb_name}' initialization complete"
@@ -363,7 +412,9 @@ async def run_upload_processing_task(
)
_task_log(task_id, f"Updated folder sync state: {folder_id}")
except Exception as sync_err:
- _task_log(task_id, f"Folder sync state update failed: {sync_err}", level="warning")
+ _task_log(
+ task_id, f"Folder sync state update failed: {sync_err}", level="warning"
+ )
num_processed = len(processed_files) if processed_files else 0
progress_tracker.update(
@@ -373,7 +424,9 @@ async def run_upload_processing_task(
total=num_processed,
)
- _task_log(task_id, f"Processed {num_processed} file(s) for '{kb_name}'", level="success")
+ _task_log(
+ task_id, f"Processed {num_processed} file(s) for '{kb_name}'", level="success"
+ )
task_manager.update_task_status(task_id, "completed")
task_stream_manager.emit_complete(
task_id, f"Successfully processed {num_processed} files for '{kb_name}'"
@@ -647,7 +700,9 @@ async def upload_files(
kb_entry = _load_kb_entry_or_404(manager, kb_name)
_assert_kb_writable_or_409(kb_name, kb_entry)
- kb_provider = _validate_registered_provider(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)
+ kb_provider = _validate_registered_provider(
+ kb_entry.get("rag_provider") or DEFAULT_PROVIDER
+ )
if requested_provider and requested_provider != kb_provider:
raise HTTPException(
status_code=400,
@@ -837,24 +892,29 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):
if not has_active_task and not expected_task_id:
if kb_is_ready:
- await websocket.send_json({
- "type": "progress",
- "data": {
- "stage": "completed",
- "message": "Knowledge base is ready.",
- "percent": 100,
- "current": 1,
- "total": 1,
- },
- })
+ await websocket.send_json(
+ {
+ "type": "progress",
+ "data": {
+ "stage": "completed",
+ "message": "Knowledge base is ready.",
+ "percent": 100,
+ "current": 1,
+ "total": 1,
+ },
+ }
+ )
else:
- await websocket.send_json({
- "type": "progress",
- "data": initial_progress or {
- "stage": "error",
- "message": "Knowledge base needs reindex or initialization.",
- },
- })
+ await websocket.send_json(
+ {
+ "type": "progress",
+ "data": initial_progress
+ or {
+ "stage": "error",
+ "message": "Knowledge base needs reindex or initialization.",
+ },
+ }
+ )
return
if initial_progress:
@@ -891,7 +951,11 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):
current_progress = progress_tracker.get_progress()
if current_progress:
progress_task_id = current_progress.get("task_id")
- if expected_task_id and progress_task_id and progress_task_id != expected_task_id:
+ if (
+ expected_task_id
+ and progress_task_id
+ and progress_task_id != expected_task_id
+ ):
continue
current_timestamp = current_progress.get("timestamp")
if current_timestamp != last_timestamp:
@@ -993,7 +1057,9 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background
manager = get_kb_manager()
kb_entry = _load_kb_entry_or_404(manager, kb_name)
_assert_kb_writable_or_409(kb_name, kb_entry)
- kb_provider = _validate_registered_provider(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)
+ kb_provider = _validate_registered_provider(
+ kb_entry.get("rag_provider") or DEFAULT_PROVIDER
+ )
# Get linked folders and find the one with matching ID
folders = manager.get_linked_folders(kb_name)
diff --git a/deeptutor/api/routers/memory.py b/deeptutor/api/routers/memory.py
index 9d645801f..fcd33e7c4 100644
--- a/deeptutor/api/routers/memory.py
+++ b/deeptutor/api/routers/memory.py
@@ -8,7 +8,7 @@ from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from deeptutor.services.memory import MemoryFile, get_memory_service
-from deeptutor.services.session import get_sqlite_session_store
+from deeptutor.services.session import get_session_store
router = APIRouter()
@@ -53,7 +53,7 @@ async def update_memory(payload: FileUpdateRequest):
@router.post("/refresh")
async def refresh_memory(payload: MemoryRefreshRequest):
- store = get_sqlite_session_store()
+ store = get_session_store()
session_id = str(payload.session_id or "").strip()
if session_id:
session = await store.get_session(session_id)
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index 3497bd5bd..bfd2d0699 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -6,10 +6,10 @@ from __future__ import annotations
import logging
-from pydantic import BaseModel, Field, field_validator
from fastapi import APIRouter, HTTPException, Query
+from pydantic import BaseModel, Field, field_validator
-from deeptutor.services.session import get_sqlite_session_store
+from deeptutor.services.session import get_session_store
logger = logging.getLogger(__name__)
@@ -69,14 +69,14 @@ async def list_sessions(
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
):
- store = get_sqlite_session_store()
+ store = get_session_store()
sessions = await store.list_sessions(limit=limit, offset=offset)
return {"sessions": sessions}
@router.get("/{session_id}")
async def get_session(session_id: str):
- store = get_sqlite_session_store()
+ store = get_session_store()
session = await store.get_session_with_messages(session_id)
if session is None:
raise HTTPException(status_code=404, detail="Session not found")
@@ -85,7 +85,7 @@ async def get_session(session_id: str):
@router.patch("/{session_id}")
async def rename_session(session_id: str, payload: SessionRenameRequest):
- store = get_sqlite_session_store()
+ store = get_session_store()
updated = await store.update_session_title(session_id, payload.title)
if not updated:
raise HTTPException(status_code=404, detail="Session not found")
@@ -95,7 +95,7 @@ async def rename_session(session_id: str, payload: SessionRenameRequest):
@router.delete("/{session_id}")
async def delete_session(session_id: str):
- store = get_sqlite_session_store()
+ store = get_session_store()
deleted = await store.delete_session(session_id)
if not deleted:
raise HTTPException(status_code=404, detail="Session not found")
@@ -106,7 +106,7 @@ async def delete_session(session_id: str):
async def record_quiz_results(session_id: str, payload: QuizResultsRequest):
if not payload.answers:
raise HTTPException(status_code=400, detail="Quiz results are required")
- store = get_sqlite_session_store()
+ store = get_session_store()
session = await store.get_session(session_id)
if session is None:
raise HTTPException(status_code=404, detail="Session not found")
@@ -124,7 +124,9 @@ async def record_quiz_results(session_id: str, payload: QuizResultsRequest):
[item.model_dump() for item in payload.answers],
)
except Exception:
- logger.warning("Failed to upsert notebook entries for session %s", session_id, exc_info=True)
+ logger.warning(
+ "Failed to upsert notebook entries for session %s", session_id, exc_info=True
+ )
return {
"recorded": True,
"session_id": session_id,
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index e514a26af..08dcf07ec 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -20,6 +20,18 @@ logger = logging.getLogger(__name__)
@router.websocket("/ws")
async def unified_websocket(ws: WebSocket) -> None:
+ # Auth check — mirrors the require_auth HTTP dependency.
+ # Token is read from the ?token= query param (WebSocket headers can't
+ # carry cookies cross-origin in all browsers).
+ # Uses the same local jwt.decode() path — no network call.
+ from deeptutor.services.auth import AUTH_ENABLED, decode_token
+
+ if AUTH_ENABLED:
+ token = ws.query_params.get("token") or ws.cookies.get("dt_token")
+ if not token or not decode_token(token):
+ await ws.close(code=4001)
+ return
+
await ws.accept()
closed = False
subscription_tasks: dict[str, asyncio.Task[None]] = {}
diff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.py
index 984e38bd3..180063f57 100644
--- a/deeptutor/app/facade.py
+++ b/deeptutor/app/facade.py
@@ -12,7 +12,7 @@ from typing import Any, AsyncIterator
from deeptutor.runtime.registry.capability_registry import get_capability_registry
from deeptutor.services.notebook import RecordType, 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)
@@ -59,7 +59,7 @@ class DeepTutorApp:
def __init__(self) -> None:
self.runtime = get_turn_runtime_manager()
- self.store = get_sqlite_session_store()
+ self.store = get_session_store()
self.notebooks = get_notebook_manager()
self.capabilities = get_capability_registry()
@@ -112,7 +112,9 @@ class DeepTutorApp:
)
return CapabilityAvailability(name=resolved, available=True)
- async def start_turn(self, request: TurnRequest | dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
+ async def start_turn(
+ self, request: TurnRequest | dict[str, Any]
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
if isinstance(request, dict):
request = TurnRequest(**request)
resolved_capability = self.resolve_capability(request.capability)
@@ -178,13 +180,17 @@ class DeepTutorApp:
def add_record(self, **kwargs: Any) -> dict[str, Any]:
return self.notebooks.add_record(**kwargs)
- def update_record(self, notebook_id: str, record_id: str, **kwargs: Any) -> dict[str, Any] | None:
+ def update_record(
+ self, notebook_id: str, record_id: str, **kwargs: Any
+ ) -> dict[str, Any] | None:
return self.notebooks.update_record(notebook_id, record_id, **kwargs)
def remove_record(self, notebook_id: str, record_id: str) -> bool:
return self.notebooks.remove_record(notebook_id, record_id)
- def get_records_by_references(self, notebook_references: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ def get_records_by_references(
+ self, notebook_references: list[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
return self.notebooks.get_records_by_references(notebook_references)
def import_markdown_into_notebook(self, notebook_id: str, path: str | Path) -> dict[str, Any]:
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index ae4773653..949866e3d 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -16,8 +16,11 @@ import sys
from 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,
+ LEGACY_PROVIDER_ALIASES,
+ normalize_provider_name,
+)
logger = get_logger("KnowledgeBaseManager")
@@ -126,6 +129,13 @@ class KnowledgeBaseManager:
self.config_file = self.base_dir / "kb_config.json"
self.config = self._load_config()
+ # PocketBase sync — enabled when POCKETBASE_URL is set.
+ # The local JSON file stays the source of truth; PocketBase gets a
+ # mirrored copy for admin-panel visibility and future multi-user access.
+ from deeptutor.services.pocketbase_client import is_pocketbase_enabled
+
+ self._pb_enabled = is_pocketbase_enabled()
+
def _load_config(self) -> dict:
"""Load knowledge base configuration from the canonical kb_config.json file."""
if self.config_file.exists():
@@ -173,8 +183,10 @@ class KnowledgeBaseManager:
kb_dir = self.base_dir / kb_name
legacy_storage = kb_dir / "rag_storage"
llamaindex_storage = kb_dir / "llamaindex_storage"
- if legacy_storage.exists() and legacy_storage.is_dir() and not (
- llamaindex_storage.exists() and llamaindex_storage.is_dir()
+ if (
+ legacy_storage.exists()
+ and legacy_storage.is_dir()
+ and not (llamaindex_storage.exists() and llamaindex_storage.is_dir())
):
if not kb_entry.get("needs_reindex", False):
kb_entry["needs_reindex"] = True
@@ -208,6 +220,35 @@ class KnowledgeBaseManager:
f.flush()
os.fsync(f.fileno()) # Ensure data is written to disk
+ def _sync_kb_to_pb(self, name: str, kb_entry: dict) -> None:
+ """
+ Mirror a KB metadata entry to PocketBase (best-effort, non-blocking).
+ Called after every local config save when PocketBase is enabled.
+ """
+ if not self._pb_enabled:
+ return
+ 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="{name}"'}
+ )
+ payload = {
+ "kb_name": name,
+ "description": kb_entry.get("description", f"Knowledge base: {name}"),
+ "rag_provider": kb_entry.get("rag_provider", "llamaindex"),
+ "needs_reindex": bool(kb_entry.get("needs_reindex", False)),
+ "status": kb_entry.get("status", "unknown"),
+ "kb_created_at": kb_entry.get("created_at", ""),
+ }
+ if records:
+ pb.collection("knowledge_bases").update(records[0].id, payload)
+ else:
+ pb.collection("knowledge_bases").create(payload)
+ except Exception as exc:
+ logger.debug(f"PocketBase KB sync failed for '{name}': {exc}")
+
def update_kb_status(
self,
name: str,
@@ -217,6 +258,9 @@ class KnowledgeBaseManager:
"""
Update knowledge base status and progress in kb_config.json.
+ When PocketBase is enabled, the updated entry is also mirrored to the
+ PocketBase knowledge_bases collection (best-effort).
+
Args:
name: Knowledge base name
status: Status string ("initializing", "processing", "ready", "error")
@@ -262,6 +306,7 @@ class KnowledgeBaseManager:
kb_config["embedding_model"], kb_config["embedding_dim"] = fp
self._save_config()
+ self._sync_kb_to_pb(name, kb_config)
def get_kb_status(self, name: str) -> dict | None:
"""Get status and progress for a knowledge base."""
@@ -277,7 +322,7 @@ class KnowledgeBaseManager:
def list_knowledge_bases(self) -> list[str]:
"""List all available knowledge bases.
-
+
This method:
1. Loads registered KBs from kb_config.json
2. Scans the directory for existing KBs not yet registered
@@ -297,38 +342,37 @@ class KnowledgeBaseManager:
for item in self.base_dir.iterdir():
if not item.is_dir() or item.name.startswith(("__", ".")):
continue
-
+
# Skip if already in config
if item.name in kb_list:
continue
-
+
# Check if this is a valid KB directory (legacy rag_storage or llamaindex_storage)
rag_storage = item / "rag_storage"
llamaindex_storage = item / "llamaindex_storage"
- is_valid_kb = (
- (rag_storage.exists() and rag_storage.is_dir()) or
- (llamaindex_storage.exists() and llamaindex_storage.is_dir())
+ is_valid_kb = (rag_storage.exists() and rag_storage.is_dir()) or (
+ llamaindex_storage.exists() and llamaindex_storage.is_dir()
)
-
+
if is_valid_kb:
# Auto-register this KB to kb_config.json
kb_list.add(item.name)
self._auto_register_kb(item.name)
config_changed = True
-
+
# Save config if we registered new KBs
if config_changed:
self._save_config()
return sorted(kb_list)
-
+
def _auto_register_kb(self, name: str):
"""Auto-register an existing KB to kb_config.json.
-
+
Reads info from metadata.json (if exists) for backward compatibility.
"""
kb_dir = self.base_dir / name
-
+
# Default values
kb_entry = {
"path": name,
@@ -336,7 +380,7 @@ class KnowledgeBaseManager:
"status": "ready", # Existing KB with storage is considered ready
"updated_at": datetime.now().isoformat(),
}
-
+
# Try to read metadata.json for existing info (backward compatibility)
metadata_file = kb_dir / "metadata.json"
if metadata_file.exists():
@@ -350,14 +394,14 @@ class KnowledgeBaseManager:
raw_provider = str(metadata["rag_provider"]).strip().lower()
kb_entry["rag_provider"] = normalize_provider_name(raw_provider)
if str(raw_provider).strip().lower() in LEGACY_PROVIDER_ALIASES:
- kb_entry["needs_reindex"] = True
+ kb_entry["needs_reindex"] = True # type: ignore[assignment]
if metadata.get("created_at"):
kb_entry["created_at"] = metadata["created_at"]
if metadata.get("last_updated"):
kb_entry["updated_at"] = metadata["last_updated"]
except Exception as e:
logger.warning(f"Failed to read metadata.json for '{name}': {e}")
-
+
# Detect rag_provider from storage type if not set
if "rag_provider" not in kb_entry:
rag_storage = kb_dir / "rag_storage"
@@ -366,13 +410,13 @@ class KnowledgeBaseManager:
kb_entry["rag_provider"] = DEFAULT_PROVIDER
elif rag_storage.exists():
kb_entry["rag_provider"] = DEFAULT_PROVIDER
- kb_entry["needs_reindex"] = True
-
+ kb_entry["needs_reindex"] = True # type: ignore[assignment]
+
# Add to config
if "knowledge_bases" not in self.config:
self.config["knowledge_bases"] = {}
self.config["knowledge_bases"][name] = kb_entry
-
+
logger.info(f"Auto-registered KB '{name}' to kb_config.json")
def register_knowledge_base(self, name: str, description: str = "", set_default: bool = False):
@@ -485,7 +529,7 @@ class KnowledgeBaseManager:
def get_metadata(self, name: str | None = None) -> dict:
"""Get knowledge base metadata.
-
+
Source:
1. kb_config.json (authoritative source)
"""
@@ -494,11 +538,11 @@ class KnowledgeBaseManager:
kb_name = self.get_default()
if kb_name is None:
return {}
-
+
# First, try kb_config.json (authoritative source)
self.config = self._load_config()
kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
-
+
if kb_config:
# Build metadata from config
metadata = {
@@ -513,7 +557,7 @@ class KnowledgeBaseManager:
# Remove None values
metadata = {k: v for k, v in metadata.items() if v is not None}
return metadata
-
+
return {}
def get_info(self, name: str | None = None) -> dict:
@@ -627,7 +671,10 @@ class KnowledgeBaseManager:
# Check rag_initialized (llamaindex storage only)
rag_initialized = (
- (dir_exists and llamaindex_storage_dir and llamaindex_storage_dir.exists() and llamaindex_storage_dir.is_dir())
+ dir_exists
+ and llamaindex_storage_dir
+ and llamaindex_storage_dir.exists()
+ and llamaindex_storage_dir.is_dir()
)
info["statistics"] = {
diff --git a/deeptutor/services/auth.py b/deeptutor/services/auth.py
index 007032db5..89930532b 100644
--- a/deeptutor/services/auth.py
+++ b/deeptutor/services/auth.py
@@ -45,10 +45,16 @@ AUTH_PASSWORD_HASH: str = os.getenv("AUTH_PASSWORD_HASH", "")
AUTH_SECRET: str = os.getenv("AUTH_SECRET", "")
TOKEN_EXPIRE_HOURS: int = int(os.getenv("AUTH_TOKEN_EXPIRE_HOURS", "24"))
+# PocketBase auth mode — active when POCKETBASE_URL is set AND AUTH_ENABLED=true.
+# When enabled, login/register proxy to PocketBase and token validation uses
+# PocketBase's auth-refresh endpoint (cached in memory — no static secret needed).
+POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")
+POCKETBASE_ENABLED: bool = bool(POCKETBASE_URL) and AUTH_ENABLED
+
_ALGORITHM = "HS256"
_USERS_FILE = Path("data/user/auth_users.json")
-if AUTH_ENABLED and not AUTH_SECRET:
+if AUTH_ENABLED and not POCKETBASE_ENABLED and not AUTH_SECRET:
logger.warning(
"AUTH_ENABLED=true but AUTH_SECRET is not set. "
"A temporary secret will be generated — tokens will be invalidated on restart. "
@@ -263,9 +269,35 @@ def create_token(username: str, role: str = "user") -> str:
def decode_token(token: str) -> TokenPayload | None:
- """Decode and validate a JWT. Returns a TokenPayload or None if invalid."""
+ """
+ Validate a token and return a TokenPayload, or None if invalid.
+
+ - PocketBase mode: calls PocketBase's auth-refresh endpoint (cached in
+ memory for 60 s, so only the first request per token per minute makes
+ a network call). No static JWT secret required.
+ - Standard mode: local in-memory jwt.decode() using AUTH_SECRET — zero
+ network calls, same as before.
+ """
+ if not token:
+ return None
+
+ if POCKETBASE_ENABLED:
+ from deeptutor.services.pocketbase_client import validate_pb_token
+
+ payload = validate_pb_token(token)
+ if payload is None:
+ return None
+ return TokenPayload(
+ username=payload["username"],
+ role=payload.get("role", "user"),
+ )
+
+ # Standard JWT + bcrypt mode
from jose import JWTError, jwt
+ if not AUTH_SECRET:
+ return None
+
try:
payload = jwt.decode(token, AUTH_SECRET, algorithms=[_ALGORITHM])
username = payload.get("sub")
@@ -276,6 +308,67 @@ def decode_token(token: str) -> TokenPayload | None:
return None
+# ---------------------------------------------------------------------------
+# PocketBase auth helpers
+# ---------------------------------------------------------------------------
+
+
+def authenticate_pb(username: str, password: str) -> tuple[TokenPayload, str] | None:
+ """
+ Authenticate against PocketBase and return (TokenPayload, raw_pb_token).
+
+ Only called when POCKETBASE_ENABLED=True.
+ Returns None on failure.
+ The raw token is the PocketBase JWT string to be stored in the cookie.
+
+ PocketBase requires an email address; plain usernames are mapped to
+ <username>@deeptutor.local to match the email used at registration.
+ """
+ try:
+ from deeptutor.services.pocketbase_client import get_pb_client
+
+ pb = get_pb_client()
+ result = pb.collection("users").auth_with_password(username, password)
+ token: str = result.token
+ record = result.record
+ username = (
+ getattr(record, "email", None)
+ or getattr(record, "name", None)
+ or getattr(record, "id", "unknown")
+ )
+ # PocketBase has no built-in "role" field by default; treat all as "user".
+ # Admins authenticated via PocketBase admin panel use a separate endpoint.
+ role = getattr(record, "role", "user") or "user"
+ return TokenPayload(username=str(username), role=str(role)), token
+ except Exception as exc:
+ logger.warning(f"PocketBase authentication failed: {exc}")
+ return None
+
+
+def register_pb(username: str, email: str, password: str) -> dict | None:
+ """
+ Create a new user in PocketBase.
+
+ Returns the created user record dict or None on failure.
+ """
+ try:
+ from deeptutor.services.pocketbase_client import get_pb_client
+
+ pb = get_pb_client()
+ record = pb.collection("users").create(
+ {
+ "username": username,
+ "email": email,
+ "password": password,
+ "passwordConfirm": password,
+ }
+ )
+ return {"id": record.id, "username": username, "email": email}
+ except Exception as exc:
+ logger.warning(f"PocketBase registration failed: {exc}")
+ return None
+
+
# ---------------------------------------------------------------------------
# Main auth entry point
# ---------------------------------------------------------------------------
diff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.py
index db133c999..8d6e2e956 100644
--- a/deeptutor/services/memory/service.py
+++ b/deeptutor/services/memory/service.py
@@ -10,15 +10,15 @@ workspace directory, not in the shared memory dir.
from __future__ import annotations
-import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
+import re
from typing import Literal
from deeptutor.services.llm import stream as llm_stream
from deeptutor.services.path_service import PathService, get_path_service
-from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store
+from deeptutor.services.session.protocol import SessionStoreProtocol
MemoryFile = Literal["summary", "profile"]
MEMORY_FILES: list[MemoryFile] = ["summary", "profile"]
@@ -52,10 +52,12 @@ class MemoryService:
def __init__(
self,
path_service: PathService | None = None,
- store: SQLiteSessionStore | None = None,
+ store: SessionStoreProtocol | None = None,
) -> None:
+ from deeptutor.services.session import get_session_store
+
self._path_service = path_service or get_path_service()
- self._store = store or get_sqlite_session_store()
+ self._store = store or get_session_store()
self._migrate_legacy()
@property
@@ -82,11 +84,13 @@ class MemoryService:
self._memory_dir.mkdir(parents=True, exist_ok=True)
if preferences:
self._path("profile").write_text(
- f"## Preferences\n{preferences}", encoding="utf-8",
+ f"## Preferences\n{preferences}",
+ encoding="utf-8",
)
if context:
self._path("summary").write_text(
- f"## Learning Journey\n{context}", encoding="utf-8",
+ f"## Learning Journey\n{context}",
+ encoding="utf-8",
)
legacy.rename(legacy.with_suffix(".md.bak"))
@@ -232,7 +236,8 @@ class MemoryService:
messages = await self._store.get_messages_for_context(target)
relevant = [
- m for m in messages
+ m
+ for m in messages
if str(m.get("role", "")) in {"user", "assistant"}
and str(m.get("content", "") or "").strip()
][-max_messages:]
@@ -252,9 +257,7 @@ class MemoryService:
cap = str(sess.get("capability", "") or "")
source = (
- f"[Session] {target}\n"
- f"[Capability] {cap or 'chat'}\n\n"
- f"[Recent Transcript]\n{transcript}"
+ f"[Session] {target}\n[Capability] {cap or 'chat'}\n\n[Recent Transcript]\n{transcript}"
)
p_changed = await self._rewrite_one("profile", source, language)
@@ -308,7 +311,7 @@ class MemoryService:
"## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
"规则:保持简短,删除过时内容,不要记录临时对话。\n\n"
f"[当前画像]\n{current or '(empty)'}\n\n"
- f"[新增材料]\n{source}"
+ f"[新增材料]\n{source}",
)
return (
"You maintain a user profile document. Only keep stable identity, "
@@ -318,7 +321,7 @@ class MemoryService:
"## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
"Rules: keep it short, remove stale items, no transient chatter.\n\n"
f"[Current profile]\n{current or '(empty)'}\n\n"
- f"[New material]\n{source}"
+ f"[New material]\n{source}",
)
@staticmethod
@@ -331,7 +334,7 @@ class MemoryService:
"## Current Focus\n## Accomplishments\n## Open Questions\n\n"
"规则:保持简短,删除已完成或过时的条目。\n\n"
f"[当前摘要]\n{current or '(empty)'}\n\n"
- f"[新增材料]\n{source}"
+ f"[新增材料]\n{source}",
)
return (
"You maintain a learning journey summary. Track what the user is studying, "
@@ -341,7 +344,7 @@ class MemoryService:
"## Current Focus\n## Accomplishments\n## Open Questions\n\n"
"Rules: keep it short, remove completed/stale items.\n\n"
f"[Current summary]\n{current or '(empty)'}\n\n"
- f"[New material]\n{source}"
+ f"[New material]\n{source}",
)
# ── Helpers ───────────────────────────────────────────────────────
@@ -353,11 +356,13 @@ class MemoryService:
context = ""
pref_match = re.search(
r"##\s*Preferences\s*(.*?)(?=\n##\s*Context\b|\Z)",
- text, flags=re.IGNORECASE | re.DOTALL,
+ text,
+ flags=re.IGNORECASE | re.DOTALL,
)
ctx_match = re.search(
r"##\s*Context\s*(.*)$",
- text, flags=re.IGNORECASE | re.DOTALL,
+ text,
+ flags=re.IGNORECASE | re.DOTALL,
)
if pref_match:
preferences = pref_match.group(1).strip()
diff --git a/deeptutor/services/pocketbase_client.py b/deeptutor/services/pocketbase_client.py
new file mode 100644
index 000000000..76bc26d48
--- /dev/null
+++ b/deeptutor/services/pocketbase_client.py
@@ -0,0 +1,177 @@
+"""
+PocketBase client singleton.
+
+Only initialised when POCKETBASE_URL is present in the environment.
+All other code checks ``is_pocketbase_enabled()`` before calling
+``get_pb_client()`` to avoid import-time failures when PocketBase is
+not configured.
+
+Token validation uses PocketBase's auth-refresh endpoint rather than
+local JWT decoding (PocketBase does not expose a static JWT secret).
+Results are cached in memory for 60 seconds so only the first request
+per token per minute incurs a network call (~5–10 ms); all subsequent
+requests within the TTL are resolved in < 1 ms from the local cache.
+
+Usage:
+ from deeptutor.services.pocketbase_client import get_pb_client, is_pocketbase_enabled
+
+ if is_pocketbase_enabled():
+ pb = get_pb_client()
+ result = pb.collection("sessions").get_list(1, 50)
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from typing import Any
+
+from deeptutor.logging import get_logger
+
+logger = get_logger("PocketBase")
+
+_POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")
+_ADMIN_EMAIL: str = os.getenv("POCKETBASE_ADMIN_EMAIL", "")
+_ADMIN_PASSWORD: str = os.getenv("POCKETBASE_ADMIN_PASSWORD", "")
+
+_client = None
+_client_initialised = False
+
+# Token validation cache: token -> (payload_dict, expires_at)
+_TOKEN_CACHE: dict[str, tuple[dict[str, Any], float]] = {}
+_TOKEN_CACHE_TTL: float = 60.0 # seconds
+
+
+def is_pocketbase_enabled() -> bool:
+ """Return True when POCKETBASE_URL is configured."""
+ return bool(_POCKETBASE_URL)
+
+
+def get_pb_client():
+ """
+ Return an admin-authenticated PocketBase SDK client (cached singleton).
+
+ Raises RuntimeError if POCKETBASE_URL is not set.
+ Raises on authentication failure.
+ """
+ global _client, _client_initialised
+
+ if not is_pocketbase_enabled():
+ raise RuntimeError("PocketBase is not configured. Set POCKETBASE_URL in .env to enable it.")
+
+ if _client_initialised:
+ return _client
+
+ try:
+ from pocketbase import PocketBase # type: ignore[import]
+ except ImportError as exc:
+ raise RuntimeError(
+ "The 'pocketbase' package is not installed. Run: pip install pocketbase"
+ ) from exc
+
+ pb = PocketBase(_POCKETBASE_URL)
+
+ if _ADMIN_EMAIL and _ADMIN_PASSWORD:
+ try:
+ pb.admins.auth_with_password(_ADMIN_EMAIL, _ADMIN_PASSWORD)
+ logger.info(f"PocketBase admin authenticated at {_POCKETBASE_URL}")
+ except Exception as exc:
+ logger.error(
+ f"PocketBase admin authentication failed: {exc}. "
+ "Check POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD."
+ )
+ raise
+ else:
+ logger.warning(
+ "POCKETBASE_ADMIN_EMAIL / POCKETBASE_ADMIN_PASSWORD not set. "
+ "The backend will connect to PocketBase without admin privileges. "
+ "Collection management (scripts/pb_setup.py) will not work."
+ )
+
+ _client = pb
+ _client_initialised = True
+ return _client
+
+
+def validate_pb_token(token: str) -> dict[str, Any] | None:
+ """
+ Validate a PocketBase user token and return the user payload dict.
+
+ Uses PocketBase's /api/collections/users/auth-refresh endpoint.
+ Results are cached for ``_TOKEN_CACHE_TTL`` seconds so only the
+ first call per token per minute makes a network round-trip.
+
+ Returns a dict with at least ``username`` and ``role`` keys, or
+ None if the token is invalid / expired.
+ """
+ if not is_pocketbase_enabled():
+ return None
+
+ now = time.monotonic()
+
+ # Cache hit
+ cached = _TOKEN_CACHE.get(token)
+ if cached is not None:
+ payload, expires_at = cached
+ if now < expires_at:
+ return payload
+ del _TOKEN_CACHE[token]
+
+ # Cache miss — call PocketBase
+ try:
+ from pocketbase import PocketBase # type: ignore[import]
+
+ pb = PocketBase(_POCKETBASE_URL)
+ # Inject the user token so auth_refresh validates it
+ pb.auth_store.save(token, None)
+ result = pb.collection("users").auth_refresh()
+
+ record = result.record
+ username = (
+ getattr(record, "email", None)
+ or getattr(record, "name", None)
+ or getattr(record, "username", None)
+ or getattr(record, "id", "unknown")
+ )
+ role = str(getattr(record, "role", "user") or "user")
+
+ payload = {"username": str(username), "role": role}
+ _TOKEN_CACHE[token] = (payload, now + _TOKEN_CACHE_TTL)
+ return payload
+
+ except Exception as exc:
+ logger.debug(f"PocketBase token validation failed: {exc}")
+ return None
+
+
+async def ping_pocketbase() -> bool:
+ """
+ Async health check called during FastAPI lifespan startup.
+
+ Returns True if PocketBase is reachable, False otherwise.
+ Logs a clear warning (not an exception) so the server still starts
+ when PocketBase is configured but temporarily unavailable.
+ """
+ if not is_pocketbase_enabled():
+ return False
+
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=5.0) as client:
+ resp = await client.get(f"{_POCKETBASE_URL}/api/health")
+ if resp.status_code == 200:
+ logger.info(f"PocketBase health check passed at {_POCKETBASE_URL}")
+ return True
+ logger.warning(
+ f"PocketBase health check returned HTTP {resp.status_code} at {_POCKETBASE_URL}. "
+ "Sessions will fail until PocketBase is healthy."
+ )
+ return False
+ except Exception as exc:
+ logger.warning(
+ f"PocketBase is unreachable at {_POCKETBASE_URL} ({exc}). "
+ "Sessions and auth will fall back to SQLite until PocketBase is available. "
+ "Check that the pocketbase container is running and POCKETBASE_URL is correct."
+ )
+ return False
diff --git a/deeptutor/services/session/__init__.py b/deeptutor/services/session/__init__.py
index 8f589fad4..42cf668aa 100644
--- a/deeptutor/services/session/__init__.py
+++ b/deeptutor/services/session/__init__.py
@@ -6,28 +6,49 @@ Provides unified session management for all agent modules.
Usage:
from deeptutor.services.session import BaseSessionManager
-
+
class MySessionManager(BaseSessionManager):
def __init__(self):
super().__init__("my_module")
-
+
def _get_session_id_prefix(self) -> str:
return "my_"
-
+
def _get_default_title(self) -> str:
return "New My Session"
-
+
# ... implement other abstract methods
"""
from .base_session_manager import BaseSessionManager
+from .protocol import SessionStoreProtocol
from .sqlite_store import SQLiteSessionStore, get_sqlite_session_store
from .turn_runtime import TurnRuntimeManager, get_turn_runtime_manager
+
+def get_session_store() -> SessionStoreProtocol:
+ """
+ Return the active session store backend.
+
+ When POCKETBASE_URL is set in the environment, returns a
+ PocketBaseSessionStore. Otherwise falls back to the local
+ SQLiteSessionStore (default, zero-config behaviour).
+ """
+ import os
+
+ if os.getenv("POCKETBASE_URL"):
+ from .pocketbase_store import PocketBaseSessionStore
+
+ return PocketBaseSessionStore()
+ return get_sqlite_session_store()
+
+
__all__ = [
"BaseSessionManager",
+ "SessionStoreProtocol",
"SQLiteSessionStore",
"TurnRuntimeManager",
+ "get_session_store",
"get_sqlite_session_store",
"get_turn_runtime_manager",
]
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index aedd69243..1c457e717 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -12,7 +12,7 @@ from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
from deeptutor.services.llm.config import LLMConfig
-from .sqlite_store import SQLiteSessionStore
+from .protocol import SessionStoreProtocol
def count_tokens(text: str) -> int:
@@ -89,7 +89,7 @@ class ContextBuilder:
def __init__(
self,
- store: SQLiteSessionStore,
+ store: SessionStoreProtocol,
history_budget_ratio: float = 0.35,
summary_target_ratio: float = 0.40,
) -> None:
@@ -314,7 +314,9 @@ class ContextBuilder:
stored_summary = str(session.get("compressed_summary", "") or "").strip()
summary_up_to_msg_id = int(session.get("summary_up_to_msg_id", 0) or 0)
- unsummarized = [item for item in messages if int(item.get("id", 0) or 0) > summary_up_to_msg_id]
+ unsummarized = [
+ item for item in messages if int(item.get("id", 0) or 0) > summary_up_to_msg_id
+ ]
current_history = self._build_history(stored_summary, unsummarized)
current_tokens = count_tokens(build_history_text(current_history))
@@ -328,7 +330,9 @@ class ContextBuilder:
budget=budget,
)
- older_unsummarized, recent_messages = self._select_recent_messages(unsummarized, recent_budget)
+ older_unsummarized, recent_messages = self._select_recent_messages(
+ unsummarized, recent_budget
+ )
merge_parts: list[str] = []
if stored_summary:
merge_parts.append(f"Existing summary:\n{stored_summary}")
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
new file mode 100644
index 000000000..896213768
--- /dev/null
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -0,0 +1,616 @@
+"""
+PocketBase-backed session store.
+
+Implements SessionStoreProtocol using PocketBase collections for all durable
+storage. The key performance design:
+
+- All methods except ``append_turn_event`` make direct PocketBase HTTP calls.
+ These are called at most a handful of times per turn (create, get, update
+ status, add message) and the ~5–10 ms overhead is acceptable.
+
+- ``append_turn_event`` returns immediately without writing to PocketBase.
+ The existing ``_mirror_event_to_workspace`` in turn_runtime.py already
+ appends every event to a local ``events.jsonl`` file. When
+ ``update_turn_status`` finalises a turn it reads that file and batch-posts
+ all events to PocketBase ``turn_events`` in a single request, trading
+ real-time durability for ~40× lower per-event latency during streaming.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+import time
+from typing import Any
+import uuid
+
+from deeptutor.logging import get_logger
+from deeptutor.services.path_service import get_path_service
+
+logger = get_logger("PocketBaseStore")
+
+
+def _json_loads(value: Any, default: Any) -> Any:
+ if not value:
+ return default
+ if isinstance(value, (dict, list)):
+ return value
+ try:
+ return json.loads(value)
+ except Exception:
+ return default
+
+
+def _pb():
+ """Return the shared PocketBase client."""
+ from deeptutor.services.pocketbase_client import get_pb_client
+
+ return get_pb_client()
+
+
+def _to_float(value: Any, default: float = 0.0) -> float:
+ try:
+ return float(value) if value is not None else default
+ except (TypeError, ValueError):
+ return default
+
+
+class PocketBaseSessionStore:
+ """PocketBase-backed implementation of SessionStoreProtocol."""
+
+ # ------------------------------------------------------------------
+ # Sessions
+ # ------------------------------------------------------------------
+
+ async def create_session(
+ self,
+ title: str | None = None,
+ session_id: str | None = None,
+ ) -> dict[str, Any]:
+ now = time.time()
+ resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"
+ resolved_title = (title or "New conversation").strip() or "New conversation"
+
+ def _create():
+ return (
+ _pb()
+ .collection("sessions")
+ .create(
+ {
+ "session_id": resolved_id,
+ "title": resolved_title[:100],
+ "compressed_summary": "",
+ "summary_up_to_msg_id": 0,
+ "preferences_json": {},
+ "capability": "",
+ "status": "idle",
+ }
+ )
+ )
+
+ record = await asyncio.to_thread(_create)
+ return self._session_record_to_dict(record, resolved_id, resolved_title, now)
+
+ async def get_session(self, session_id: str) -> dict[str, Any] | None:
+ def _get():
+ try:
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ return records[0] if records else None
+ except Exception:
+ return None
+
+ record = await asyncio.to_thread(_get)
+ if record is None:
+ return None
+ return self._session_record_to_dict(record)
+
+ async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]:
+ if session_id:
+ session = await self.get_session(session_id)
+ if session is not None:
+ return session
+ return await self.create_session()
+
+ def _session_record_to_dict(
+ self,
+ record: Any,
+ session_id: str | None = None,
+ title: str | None = None,
+ now: float | None = None,
+ ) -> dict[str, Any]:
+ sid = session_id or getattr(record, "session_id", getattr(record, "id", ""))
+ t = title or getattr(record, "title", "New conversation") or "New conversation"
+ created = _to_float(getattr(record, "created", None)) or now or time.time()
+ updated = _to_float(getattr(record, "updated", None)) or now or time.time()
+ preferences_raw = getattr(record, "preferences_json", None)
+ return {
+ "id": sid,
+ "session_id": sid,
+ "title": t,
+ "created_at": created,
+ "updated_at": updated,
+ "compressed_summary": getattr(record, "compressed_summary", "") or "",
+ "summary_up_to_msg_id": int(getattr(record, "summary_up_to_msg_id", 0) or 0),
+ "preferences": _json_loads(preferences_raw, {}),
+ "capability": getattr(record, "capability", "") or "",
+ "status": getattr(record, "status", "idle") or "idle",
+ "active_turn_id": "",
+ }
+
+ async def update_session_title(self, session_id: str, title: str) -> bool:
+ def _update():
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if not records:
+ return False
+ _pb().collection("sessions").update(
+ records[0].id, {"title": (title.strip() or "New conversation")[:100]}
+ )
+ return True
+
+ try:
+ return await asyncio.to_thread(_update)
+ except Exception as exc:
+ logger.warning(f"update_session_title failed: {exc}")
+ return False
+
+ async def delete_session(self, session_id: str) -> bool:
+ def _delete():
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if not records:
+ return False
+ _pb().collection("sessions").delete(records[0].id)
+ return True
+
+ try:
+ return await asyncio.to_thread(_delete)
+ except Exception as exc:
+ logger.warning(f"delete_session failed: {exc}")
+ return False
+
+ async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
+ page = (offset // limit) + 1
+
+ def _list():
+ return (
+ _pb()
+ .collection("sessions")
+ .get_list(
+ page,
+ limit,
+ query_params={"sort": "-updated"},
+ )
+ )
+
+ try:
+ result = await asyncio.to_thread(_list)
+ return [self._session_record_to_dict(r) for r in result.items]
+ except Exception as exc:
+ logger.warning(f"list_sessions failed: {exc}")
+ return []
+
+ async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:
+ def _update():
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if not records:
+ return False
+ _pb().collection("sessions").update(
+ records[0].id,
+ {
+ "compressed_summary": summary,
+ "summary_up_to_msg_id": max(0, int(up_to_msg_id)),
+ },
+ )
+ return True
+
+ try:
+ return await asyncio.to_thread(_update)
+ except Exception as exc:
+ logger.warning(f"update_summary failed: {exc}")
+ return False
+
+ async def update_session_preferences(
+ self, session_id: str, preferences: dict[str, Any]
+ ) -> bool:
+ async def _merge():
+ session = await self.get_session(session_id)
+ if session is None:
+ return False
+ merged = {**session.get("preferences", {}), **(preferences or {})}
+
+ def _update():
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if not records:
+ return False
+ _pb().collection("sessions").update(records[0].id, {"preferences_json": merged})
+ return True
+
+ return await asyncio.to_thread(_update)
+
+ try:
+ return await _merge()
+ except Exception as exc:
+ logger.warning(f"update_session_preferences failed: {exc}")
+ return False
+
+ async def get_session_with_messages(self, session_id: str) -> dict[str, Any] | None:
+ session = await self.get_session(session_id)
+ if session is None:
+ return None
+ session["messages"] = await self.get_messages(session_id)
+ session["active_turns"] = await self.list_active_turns(session_id)
+ return session
+
+ # ------------------------------------------------------------------
+ # Messages
+ # ------------------------------------------------------------------
+
+ async def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str,
+ capability: str = "",
+ events: list[dict[str, Any]] | None = None,
+ attachments: list[dict[str, Any]] | None = None,
+ ) -> int:
+ now = time.time()
+
+ def _add():
+ record = (
+ _pb()
+ .collection("messages")
+ .create(
+ {
+ "session_id": session_id,
+ "role": role,
+ "content": content or "",
+ "capability": capability or "",
+ "events_json": events or [],
+ "attachments_json": attachments or [],
+ "msg_created_at": now,
+ }
+ )
+ )
+ # Update session title if still default
+ sessions = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if sessions and sessions[0].title == "New conversation" and role == "user":
+ trimmed = (content or "").strip()
+ if trimmed:
+ new_title = trimmed[:50] + ("..." if len(trimmed) > 50 else "")
+ _pb().collection("sessions").update(sessions[0].id, {"title": new_title})
+ return record
+
+ try:
+ record = await asyncio.to_thread(_add)
+ # Return a synthetic integer id using epoch ms
+ return int(now * 1000)
+ except Exception as exc:
+ logger.warning(f"add_message failed: {exc}")
+ return 0
+
+ async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
+ def _get():
+ return (
+ _pb()
+ .collection("messages")
+ .get_full_list(
+ query_params={
+ "filter": f'session_id="{session_id}"',
+ "sort": "msg_created_at",
+ }
+ )
+ )
+
+ try:
+ records = await asyncio.to_thread(_get)
+ return [self._message_record_to_dict(r) for r in records]
+ except Exception as exc:
+ logger.warning(f"get_messages failed: {exc}")
+ return []
+
+ async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:
+ messages = await self.get_messages(session_id)
+ return [
+ {"id": m["id"], "role": m["role"], "content": m["content"] or ""}
+ for m in messages
+ if m["role"] in ("user", "assistant", "system")
+ ]
+
+ def _message_record_to_dict(self, record: Any) -> dict[str, Any]:
+ return {
+ "id": getattr(record, "id", ""),
+ "session_id": getattr(record, "session_id", ""),
+ "role": getattr(record, "role", ""),
+ "content": getattr(record, "content", "") or "",
+ "capability": getattr(record, "capability", "") or "",
+ "events": _json_loads(getattr(record, "events_json", None), []),
+ "attachments": _json_loads(getattr(record, "attachments_json", None), []),
+ "created_at": _to_float(getattr(record, "msg_created_at", None)),
+ }
+
+ # ------------------------------------------------------------------
+ # Turns
+ # ------------------------------------------------------------------
+
+ async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]:
+ now = time.time()
+ turn_id = f"turn_{int(now * 1000)}_{uuid.uuid4().hex[:10]}"
+
+ def _create():
+ # Guard: ensure session exists
+ sessions = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})
+ )
+ if not sessions:
+ raise ValueError(f"Session not found: {session_id}")
+ # Guard: no duplicate active turns
+ active = (
+ _pb()
+ .collection("turns")
+ .get_full_list(
+ query_params={"filter": f'session_id="{session_id}" && status="running"'}
+ )
+ )
+ if active:
+ raise RuntimeError(f"Session already has an active turn: {active[0].turn_id}")
+ return (
+ _pb()
+ .collection("turns")
+ .create(
+ {
+ "turn_id": turn_id,
+ "session_id": session_id,
+ "capability": capability or "",
+ "status": "running",
+ "error": "",
+ "turn_created_at": now,
+ "turn_updated_at": now,
+ "finished_at": None,
+ }
+ )
+ )
+
+ await asyncio.to_thread(_create)
+ return {
+ "id": turn_id,
+ "turn_id": turn_id,
+ "session_id": session_id,
+ "capability": capability or "",
+ "status": "running",
+ "error": "",
+ "created_at": now,
+ "updated_at": now,
+ "finished_at": None,
+ "last_seq": 0,
+ }
+
+ async def get_turn(self, turn_id: str) -> dict[str, Any] | None:
+ def _get():
+ records = (
+ _pb()
+ .collection("turns")
+ .get_full_list(query_params={"filter": f'turn_id="{turn_id}"'})
+ )
+ return records[0] if records else None
+
+ record = await asyncio.to_thread(_get)
+ return self._turn_record_to_dict(record) if record else None
+
+ async def get_active_turn(self, session_id: str) -> dict[str, Any] | None:
+ def _get():
+ records = (
+ _pb()
+ .collection("turns")
+ .get_full_list(
+ query_params={
+ "filter": f'session_id="{session_id}" && status="running"',
+ "sort": "-turn_updated_at",
+ }
+ )
+ )
+ return records[0] if records else None
+
+ record = await asyncio.to_thread(_get)
+ return self._turn_record_to_dict(record) if record else None
+
+ async def list_active_turns(self, session_id: str) -> list[dict[str, Any]]:
+ def _list():
+ return (
+ _pb()
+ .collection("turns")
+ .get_full_list(
+ query_params={
+ "filter": f'session_id="{session_id}" && status="running"',
+ "sort": "-turn_updated_at",
+ }
+ )
+ )
+
+ try:
+ records = await asyncio.to_thread(_list)
+ return [self._turn_record_to_dict(r) for r in records]
+ except Exception:
+ return []
+
+ async def update_turn_status(self, turn_id: str, status: str, error: str = "") -> bool:
+ now = time.time()
+ finished_at = now if status in {"completed", "failed", "cancelled"} else None
+
+ def _update():
+ records = (
+ _pb()
+ .collection("turns")
+ .get_full_list(query_params={"filter": f'turn_id="{turn_id}"'})
+ )
+ if not records:
+ return False
+ _pb().collection("turns").update(
+ records[0].id,
+ {
+ "status": status,
+ "error": error or "",
+ "turn_updated_at": now,
+ "finished_at": finished_at,
+ },
+ )
+ return True
+
+ try:
+ updated = await asyncio.to_thread(_update)
+ except Exception as exc:
+ logger.warning(f"update_turn_status failed: {exc}")
+ return False
+
+ # Batch-flush turn events from local JSONL buffer to PocketBase on finalisation
+ if updated and finished_at is not None:
+ await self._flush_turn_events(turn_id)
+
+ return updated
+
+ async def _flush_turn_events(self, turn_id: str) -> None:
+ """
+ Read the local events.jsonl write-ahead buffer and batch-POST all
+ events to PocketBase turn_events collection in a single background call.
+ """
+ try:
+ path_service = get_path_service()
+ # The JSONL file is written by _mirror_event_to_workspace; we look
+ # across all capability workspaces since we only have the turn_id.
+ workspace_root = path_service.get_user_root()
+ jsonl_files: list[Path] = list(workspace_root.rglob(f"{turn_id}/events.jsonl"))
+
+ if not jsonl_files:
+ return
+
+ events: list[dict[str, Any]] = []
+ for jsonl_path in jsonl_files:
+ try:
+ for line in jsonl_path.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if line:
+ events.append(json.loads(line))
+ except Exception as exc:
+ logger.debug(f"Could not read events.jsonl at {jsonl_path}: {exc}")
+
+ if not events:
+ return
+
+ def _batch_create():
+ pb = _pb()
+ for event in events:
+ try:
+ pb.collection("turn_events").create(
+ {
+ "turn_id": turn_id,
+ "session_id": event.get("session_id", ""),
+ "seq": int(event.get("seq", 0)),
+ "type": event.get("type", ""),
+ "source": event.get("source", ""),
+ "stage": event.get("stage", ""),
+ "content": str(event.get("content", ""))[:10000],
+ "metadata_json": event.get("metadata", {}),
+ "event_timestamp": float(event.get("timestamp", 0)),
+ }
+ )
+ except Exception as exc:
+ logger.debug(f"turn_events batch item failed: {exc}")
+
+ await asyncio.to_thread(_batch_create)
+ logger.debug(f"Flushed {len(events)} turn events for {turn_id} to PocketBase")
+
+ except Exception as exc:
+ logger.warning(f"_flush_turn_events failed for {turn_id}: {exc}")
+
+ def _turn_record_to_dict(self, record: Any) -> dict[str, Any]:
+ turn_id = getattr(record, "turn_id", getattr(record, "id", ""))
+ return {
+ "id": turn_id,
+ "turn_id": turn_id,
+ "session_id": getattr(record, "session_id", ""),
+ "capability": getattr(record, "capability", "") or "",
+ "status": getattr(record, "status", "running") or "running",
+ "error": getattr(record, "error", "") or "",
+ "created_at": _to_float(getattr(record, "turn_created_at", None)),
+ "updated_at": _to_float(getattr(record, "turn_updated_at", None)),
+ "finished_at": _to_float(getattr(record, "finished_at", None)) or None,
+ "last_seq": 0,
+ }
+
+ # ------------------------------------------------------------------
+ # Turn events — write-ahead only; batch flush handled in update_turn_status
+ # ------------------------------------------------------------------
+
+ async def append_turn_event(self, turn_id: str, event: dict[str, Any]) -> dict[str, Any]:
+ """
+ Assign a monotonic seq number and return the annotated payload.
+
+ Does NOT write to PocketBase immediately — the caller's
+ _mirror_event_to_workspace already appends to events.jsonl, which
+ is flushed to PocketBase in bulk when the turn is finalised.
+ """
+ payload = dict(event)
+ payload.setdefault("turn_id", turn_id)
+ # Assign seq if not provided; use timestamp-based counter as fallback.
+ if not payload.get("seq"):
+ payload["seq"] = int(time.time() * 1000) % 1_000_000
+ return payload
+
+ async def get_turn_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]:
+ """Retrieve persisted turn events from PocketBase (post-turn replay)."""
+
+ def _get():
+ filter_str = f'turn_id="{turn_id}"'
+ if after_seq > 0:
+ filter_str += f" && seq > {after_seq}"
+ return (
+ _pb()
+ .collection("turn_events")
+ .get_full_list(query_params={"filter": filter_str, "sort": "seq"})
+ )
+
+ try:
+ records = await asyncio.to_thread(_get)
+ return [
+ {
+ "type": getattr(r, "type", ""),
+ "source": getattr(r, "source", ""),
+ "stage": getattr(r, "stage", ""),
+ "content": getattr(r, "content", "") or "",
+ "metadata": _json_loads(getattr(r, "metadata_json", None), {}),
+ "session_id": getattr(r, "session_id", ""),
+ "turn_id": turn_id,
+ "seq": int(getattr(r, "seq", 0)),
+ "timestamp": _to_float(getattr(r, "event_timestamp", None)),
+ }
+ for r in records
+ ]
+ except Exception as exc:
+ logger.warning(f"get_turn_events failed: {exc}")
+ return []
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
new file mode 100644
index 000000000..e4765903b
--- /dev/null
+++ b/deeptutor/services/session/protocol.py
@@ -0,0 +1,65 @@
+"""
+Structural protocol for session stores.
+
+Both SQLiteSessionStore and PocketBaseSessionStore satisfy this protocol,
+allowing the rest of the codebase to be store-agnostic.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Protocol, runtime_checkable
+
+
+@runtime_checkable
+class SessionStoreProtocol(Protocol):
+ async def create_session(
+ self,
+ title: str | None = None,
+ session_id: str | None = None,
+ ) -> dict[str, Any]: ...
+
+ async def get_session(self, session_id: str) -> dict[str, Any] | None: ...
+
+ async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]: ...
+
+ async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]: ...
+
+ async def get_turn(self, turn_id: str) -> dict[str, Any] | None: ...
+
+ async def get_active_turn(self, session_id: str) -> dict[str, Any] | None: ...
+
+ async def list_active_turns(self, session_id: str) -> list[dict[str, Any]]: ...
+
+ async def update_turn_status(self, turn_id: str, status: str, error: str = "") -> bool: ...
+
+ async def append_turn_event(self, turn_id: str, event: dict[str, Any]) -> dict[str, Any]: ...
+
+ async def get_turn_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]: ...
+
+ async def update_session_title(self, session_id: str, title: str) -> bool: ...
+
+ async def delete_session(self, session_id: str) -> bool: ...
+
+ async def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str,
+ capability: str = "",
+ events: list[dict[str, Any]] | None = None,
+ attachments: list[dict[str, Any]] | None = None,
+ ) -> int: ...
+
+ async def get_messages(self, session_id: str) -> list[dict[str, Any]]: ...
+
+ async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]: ...
+
+ async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]: ...
+
+ async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool: ...
+
+ async def update_session_preferences(
+ self, session_id: str, preferences: dict[str, Any]
+ ) -> bool: ...
+
+ async def get_session_with_messages(self, session_id: str) -> dict[str, Any] | None: ...
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index f90cd5251..3214a3b73 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -5,16 +5,16 @@ Turn-level runtime manager for unified chat streaming.
from __future__ import annotations
import asyncio
+from collections.abc import AsyncIterator
import contextlib
+from dataclasses import dataclass, field
import json
import logging
-from collections.abc import AsyncIterator
-from dataclasses import dataclass, field
from typing import Any
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.services.path_service import get_path_service
-from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store
+from deeptutor.services.session.protocol import SessionStoreProtocol
logger = logging.getLogger(__name__)
@@ -95,11 +95,7 @@ def _format_followup_question_context(context: dict[str, Any], language: str = "
option_lines.append(f"{key}. {value}")
correctness = context.get("is_correct")
correctness_text = (
- "correct"
- if correctness is True
- else "incorrect"
- if correctness is False
- else "unknown"
+ "correct" if correctness is True else "incorrect" if correctness is False else "unknown"
)
if str(language or "en").lower().startswith("zh"):
@@ -198,8 +194,10 @@ class _TurnExecution:
class TurnRuntimeManager:
"""Run one turn in the background and multiplex persisted/live events."""
- def __init__(self, store: SQLiteSessionStore | None = None) -> None:
- self.store = store or get_sqlite_session_store()
+ def __init__(self, store: SessionStoreProtocol | None = None) -> None:
+ from deeptutor.services.session import get_session_store
+
+ self.store = store or get_session_store()
self._lock = asyncio.Lock()
self._executions: dict[str, _TurnExecution] = {}
@@ -208,9 +206,7 @@ class TurnRuntimeManager:
raw_config = dict(payload.get("config", {}) or {})
runtime_only_keys = ("_persist_user_message", "followup_question_context")
runtime_only_config = {
- key: raw_config.pop(key)
- for key in runtime_only_keys
- if key in raw_config
+ key: raw_config.pop(key) for key in runtime_only_keys if key in raw_config
}
try:
from deeptutor.capabilities.request_contracts import validate_capability_config
@@ -313,7 +309,9 @@ class TurnRuntimeManager:
async with self._lock:
execution = self._executions.get(turn_id)
if execution is not None:
- execution.subscribers = [sub for sub in execution.subscribers if sub is not subscriber]
+ execution.subscribers = [
+ sub for sub in execution.subscribers if sub is not subscriber
+ ]
async def subscribe_session(
self,
@@ -337,12 +335,12 @@ class TurnRuntimeManager:
assistant_content = ""
try:
+ from deeptutor.agents.notebook import NotebookAnalysisAgent
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.runtime.orchestrator import ChatOrchestrator
- from deeptutor.agents.notebook import NotebookAnalysisAgent
+ from deeptutor.services.llm.config import get_llm_config
from deeptutor.services.memory import get_memory_service
from deeptutor.services.notebook import notebook_manager
- from deeptutor.services.llm.config import get_llm_config
from deeptutor.services.session.context_builder import ContextBuilder
request_config = dict(payload.get("config", {}) or {})
@@ -384,7 +382,7 @@ class TurnRuntimeManager:
session_id=session_id,
llm_config=llm_config,
language=payload.get("language", "en"),
- on_event=lambda event: self._persist_and_publish(execution, event),
+ on_event=lambda event: self._persist_and_publish(execution, event), # type: ignore[arg-type, return-value]
)
memory_service = get_memory_service()
memory_context = memory_service.build_memory_context()
@@ -398,7 +396,7 @@ class TurnRuntimeManager:
notebook_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=referenced_records,
- emit=lambda event: self._persist_and_publish(execution, event),
+ emit=lambda event: self._persist_and_publish(execution, event), # type: ignore[arg-type, return-value]
)
if history_references:
@@ -421,7 +419,9 @@ class TurnRuntimeManager:
if not transcript_lines:
continue
- history_summary = str(history_session.get("compressed_summary", "") or "").strip()
+ history_summary = str(
+ history_session.get("compressed_summary", "") or ""
+ ).strip()
if not history_summary:
history_summary = _clip_text(
" ".join(
@@ -456,7 +456,7 @@ class TurnRuntimeManager:
history_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=history_records,
- emit=lambda event: self._persist_and_publish(execution, event),
+ emit=lambda event: self._persist_and_publish(execution, event), # type: ignore[arg-type, return-value]
)
if not history_context.strip():
MAX_FALLBACK_CHARS = 8000
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 118d8f07f..85e36626b 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -10,6 +10,10 @@
# ============================================
services:
+ pocketbase:
+ volumes:
+ - ./data/pocketbase:/pb/pb_data
+
deeptutor:
build:
target: development
diff --git a/docker-compose.yml b/docker-compose.yml
index 0d010f570..37e3bf077 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -18,6 +18,28 @@
# ============================================
services:
+ # ============================================
+ # PocketBase — optional auth + storage sidecar
+ # Set POCKETBASE_URL=http://pocketbase:8090 in .env to activate.
+ # Leave POCKETBASE_URL blank to run without PocketBase (SQLite fallback).
+ # ============================================
+ pocketbase:
+ image: ghcr.io/muchobien/pocketbase:latest
+ container_name: pocketbase
+ restart: unless-stopped
+ ports:
+ - "${POCKETBASE_PORT:-8090}:8090"
+ volumes:
+ - ./data/pocketbase:/pb/pb_data
+ networks:
+ - deeptutor-network
+ healthcheck:
+ test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:8090/api/health"]
+ interval: 10s
+ timeout: 5s
+ retries: 3
+ start_period: 10s
+
# ============================================
# All-in-One DeepTutor Service
# ============================================
@@ -96,6 +118,10 @@ services:
retries: 3
start_period: 60s
+ depends_on:
+ pocketbase:
+ condition: service_healthy
+
networks:
- deeptutor-network
diff --git a/requirements/server.txt b/requirements/server.txt
index e96272cf7..9be59c5a2 100644
--- a/requirements/server.txt
+++ b/requirements/server.txt
@@ -15,3 +15,7 @@ python-multipart>=0.0.6
# --- Authentication ---
bcrypt>=4.0.0
python-jose[cryptography]>=3.3.0
+
+# --- PocketBase (optional sidecar backend) ---
+# Only used when POCKETBASE_URL is set in the environment.
+pocketbase>=0.12.0
diff --git a/scripts/pb_setup.py b/scripts/pb_setup.py
new file mode 100644
index 000000000..58dc525a5
--- /dev/null
+++ b/scripts/pb_setup.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+"""
+PocketBase collection bootstrap script.
+
+Run this once after starting PocketBase for the first time:
+
+ python scripts/pb_setup.py
+
+Requires POCKETBASE_URL, POCKETBASE_ADMIN_EMAIL, and POCKETBASE_ADMIN_PASSWORD
+to be set in your .env file (or exported as environment variables).
+
+Safe to re-run — existing collections are left untouched.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import sys
+
+# Allow running from project root without installing the package.
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+# Load .env if present.
+try:
+ from dotenv import load_dotenv
+
+ load_dotenv(Path(__file__).resolve().parent.parent / ".env")
+except ImportError:
+ pass
+
+
+POCKETBASE_URL = os.getenv("POCKETBASE_URL", "").rstrip("/")
+ADMIN_EMAIL = os.getenv("POCKETBASE_ADMIN_EMAIL", "")
+ADMIN_PASSWORD = os.getenv("POCKETBASE_ADMIN_PASSWORD", "")
+
+
+def _require_env():
+ missing = []
+ if not POCKETBASE_URL:
+ missing.append("POCKETBASE_URL")
+ if not ADMIN_EMAIL:
+ missing.append("POCKETBASE_ADMIN_EMAIL")
+ if not ADMIN_PASSWORD:
+ missing.append("POCKETBASE_ADMIN_PASSWORD")
+ if missing:
+ print(f"ERROR: Missing required env vars: {', '.join(missing)}")
+ print("Set them in your .env file or export them before running this script.")
+ sys.exit(1)
+
+
+def _get_client():
+ try:
+ from pocketbase import PocketBase # type: ignore[import]
+ except ImportError:
+ print("ERROR: pocketbase package not installed.")
+ print("Run: pip install pocketbase")
+ sys.exit(1)
+
+ pb = PocketBase(POCKETBASE_URL)
+ pb.admins.auth_with_password(ADMIN_EMAIL, ADMIN_PASSWORD)
+ return pb
+
+
+def _existing_collections(pb) -> set[str]:
+ try:
+ collections = pb.collections.get_full_list()
+ return {c.name for c in collections}
+ except Exception:
+ return set()
+
+
+def _create_if_missing(pb, name: str, schema: dict, existing: set[str]):
+ if name in existing:
+ print(f" skip {name} (already exists)")
+ return
+ try:
+ pb.collections.create(schema)
+ print(f" create {name}")
+ except Exception as exc:
+ print(f" ERROR creating {name}: {exc}")
+
+
+def main():
+ _require_env()
+ print(f"Connecting to PocketBase at {POCKETBASE_URL} ...")
+ pb = _get_client()
+ print("Authenticated as admin.")
+
+ existing = _existing_collections(pb)
+ print(f"Found {len(existing)} existing collection(s): {sorted(existing) or '(none)'}\n")
+
+ collections = [
+ # ----------------------------------------------------------------
+ # sessions
+ # ----------------------------------------------------------------
+ {
+ "name": "sessions",
+ "type": "base",
+ "schema": [
+ {"name": "session_id", "type": "text", "required": True},
+ {"name": "user_id", "type": "text", "required": False},
+ {"name": "title", "type": "text", "required": False},
+ {"name": "compressed_summary", "type": "text", "required": False},
+ {"name": "summary_up_to_msg_id", "type": "number", "required": False},
+ {"name": "preferences_json", "type": "json", "required": False},
+ {"name": "capability", "type": "text", "required": False},
+ {"name": "status", "type": "text", "required": False},
+ ],
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ },
+ # ----------------------------------------------------------------
+ # messages
+ # ----------------------------------------------------------------
+ {
+ "name": "messages",
+ "type": "base",
+ "schema": [
+ {"name": "session_id", "type": "text", "required": True},
+ {"name": "role", "type": "text", "required": True},
+ {"name": "content", "type": "text", "required": False},
+ {"name": "capability", "type": "text", "required": False},
+ {"name": "events_json", "type": "json", "required": False},
+ {"name": "attachments_json", "type": "json", "required": False},
+ {"name": "msg_created_at", "type": "number", "required": False},
+ ],
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ },
+ # ----------------------------------------------------------------
+ # turns
+ # ----------------------------------------------------------------
+ {
+ "name": "turns",
+ "type": "base",
+ "schema": [
+ {"name": "turn_id", "type": "text", "required": True},
+ {"name": "session_id", "type": "text", "required": True},
+ {"name": "capability", "type": "text", "required": False},
+ {"name": "status", "type": "text", "required": False},
+ {"name": "error", "type": "text", "required": False},
+ {"name": "turn_created_at", "type": "number", "required": False},
+ {"name": "turn_updated_at", "type": "number", "required": False},
+ {"name": "finished_at", "type": "number", "required": False},
+ ],
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ },
+ # ----------------------------------------------------------------
+ # turn_events
+ # ----------------------------------------------------------------
+ {
+ "name": "turn_events",
+ "type": "base",
+ "schema": [
+ {"name": "turn_id", "type": "text", "required": True},
+ {"name": "session_id", "type": "text", "required": False},
+ {"name": "seq", "type": "number", "required": True},
+ {"name": "type", "type": "text", "required": False},
+ {"name": "source", "type": "text", "required": False},
+ {"name": "stage", "type": "text", "required": False},
+ {"name": "content", "type": "text", "required": False},
+ {"name": "metadata_json", "type": "json", "required": False},
+ {"name": "event_timestamp", "type": "number", "required": False},
+ ],
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ },
+ # ----------------------------------------------------------------
+ # knowledge_bases
+ # ----------------------------------------------------------------
+ {
+ "name": "knowledge_bases",
+ "type": "base",
+ "schema": [
+ {"name": "kb_name", "type": "text", "required": True},
+ {"name": "user_id", "type": "text", "required": False},
+ {"name": "description", "type": "text", "required": False},
+ {"name": "rag_provider", "type": "text", "required": False},
+ {"name": "needs_reindex", "type": "bool", "required": False},
+ {"name": "status", "type": "text", "required": False},
+ {"name": "kb_created_at", "type": "text", "required": False},
+ {
+ "name": "raw_files",
+ "type": "file",
+ "required": False,
+ "options": {"maxSelect": 99, "maxSize": 52428800},
+ },
+ ],
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ },
+ ]
+
+ print("Creating collections:")
+ for col in collections:
+ _create_if_missing(pb, col["name"], col, existing)
+
+ print("\nDone. PocketBase collections are ready.")
+ print(f"Open the admin panel at {POCKETBASE_URL}/_/ to view and configure collections.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/web/app/(auth)/login/page.tsx b/web/app/(auth)/login/page.tsx
index 98e18ecc1..5f58b996e 100644
--- a/web/app/(auth)/login/page.tsx
+++ b/web/app/(auth)/login/page.tsx
@@ -68,18 +68,18 @@ export default function LoginPage() {
{/* 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">
- {/* Username */}
+ {/* Email */}
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Username
+ Email
</label>
<input
id="username"
- type="text"
- autoComplete="username"
+ type="email"
+ autoComplete="email"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
@@ -88,7 +88,7 @@ export default function LoginPage() {
placeholder:text-[var(--muted-foreground)]
focus:outline-none focus:ring-2 focus:ring-[var(--primary)] focus:border-transparent
transition-shadow text-sm"
- placeholder="admin"
+ placeholder="[email protected]"
/>
</div>
diff --git a/web/app/(auth)/register/page.tsx b/web/app/(auth)/register/page.tsx
index b3e7e51a5..07253283d 100644
--- a/web/app/(auth)/register/page.tsx
+++ b/web/app/(auth)/register/page.tsx
@@ -72,18 +72,18 @@ export default function RegisterPage() {
{/* 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">
- {/* Username */}
+ {/* Email */}
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Username
+ Email
</label>
<input
id="username"
- type="text"
- autoComplete="username"
+ type="email"
+ autoComplete="email"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
@@ -92,7 +92,7 @@ export default function RegisterPage() {
placeholder:text-[var(--muted-foreground)]
focus:outline-none focus:ring-2 focus:ring-[var(--primary)] focus:border-transparent
transition-shadow text-sm"
- placeholder="your_username"
+ placeholder="[email protected]"
/>
</div>
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index b31024ddc..c5a54a4aa 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -21,10 +21,8 @@ import {
X,
} from "lucide-react";
-import { useTranslation } from "react-i18next";
-
import { writeStoredLanguage } from "@/context/AppShellContext";
-import { apiUrl } from "@/lib/api";
+import { apiUrl, apiFetch } from "@/lib/api";
import { setTheme as applyThemePreference } from "@/lib/theme";
type ServiceName = "llm" | "embedding" | "search";
@@ -66,16 +64,13 @@ type Catalog = {
};
type UiSettings = {
- theme: "light" | "dark" | "glass" | "snow";
+ theme: "light" | "dark";
language: "en" | "zh";
};
-type ProviderOption = { value: string; label: string; base_url?: string; default_dim?: string };
-
type SettingsPayload = {
ui: UiSettings;
catalog: Catalog;
- providers?: Record<ServiceName, ProviderOption[]>;
};
type SystemStatus = {
@@ -86,7 +81,11 @@ type SystemStatus = {
};
type TourTestResult = "pass" | "fail" | "skip" | "pending";
-type TourTestResults = { llm: TourTestResult; embedding: TourTestResult; search: TourTestResult };
+type TourTestResults = {
+ llm: TourTestResult;
+ embedding: TourTestResult;
+ search: TourTestResult;
+};
type TourCompleteResponse = {
status: string;
message: string;
@@ -100,16 +99,24 @@ function cloneCatalog(catalog: Catalog): Catalog {
return JSON.parse(JSON.stringify(catalog)) as Catalog;
}
-function getActiveProfile(catalog: Catalog, serviceName: ServiceName): CatalogProfile | null {
+function getActiveProfile(
+ catalog: Catalog,
+ serviceName: ServiceName,
+): CatalogProfile | null {
const service = catalog.services[serviceName];
return (
- service.profiles.find((profile) => profile.id === service.active_profile_id) ??
+ service.profiles.find(
+ (profile) => profile.id === service.active_profile_id,
+ ) ??
service.profiles[0] ??
null
);
}
-function getActiveModel(catalog: Catalog, serviceName: ServiceName): CatalogModel | null {
+function getActiveModel(
+ catalog: Catalog,
+ serviceName: ServiceName,
+): CatalogModel | null {
if (serviceName === "search") return null;
const service = catalog.services[serviceName];
const profile = getActiveProfile(catalog, serviceName);
@@ -138,7 +145,11 @@ function defaultCatalog(): Catalog {
version: 1,
services: {
llm: { active_profile_id: null, active_model_id: null, profiles: [] },
- embedding: { active_profile_id: null, active_model_id: null, profiles: [] },
+ embedding: {
+ active_profile_id: null,
+ active_model_id: null,
+ profiles: [],
+ },
search: { active_profile_id: null, profiles: [] },
},
};
@@ -147,9 +158,6 @@ function defaultCatalog(): Catalog {
const inputClass =
"w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40";
-const selectClass =
- "w-full appearance-none rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] cursor-pointer";
-
function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
if (!value) return "";
if (typeof value === "string") return value;
@@ -165,10 +173,26 @@ function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
// ---------------------------------------------------------------------------
const TOUR_GUIDE_STEPS = [
- { target: "tour-llm", title: "1 / 4 — LLM", desc: "Configure your language model endpoint. This powers all chat and reasoning." },
- { target: "tour-embedding", title: "2 / 4 — Embedding", desc: "Set the embedding model for knowledge retrieval." },
- { target: "tour-search", title: "3 / 4 — Search", desc: "Optional: add a web search provider for real-time information." },
- { target: "tour-complete", title: "4 / 4 — Complete", desc: "When you are ready, click here to test and launch DeepTutor." },
+ {
+ target: "tour-llm",
+ title: "1 / 4 — LLM",
+ desc: "Configure your language model endpoint. This powers all chat and reasoning.",
+ },
+ {
+ target: "tour-embedding",
+ title: "2 / 4 — Embedding",
+ desc: "Set the embedding model for knowledge retrieval.",
+ },
+ {
+ target: "tour-search",
+ title: "3 / 4 — Search",
+ desc: "Optional: add a web search provider for real-time information.",
+ },
+ {
+ target: "tour-complete",
+ title: "4 / 4 — Complete",
+ desc: "When you are ready, click here to test and launch DeepTutor.",
+ },
];
const supportedSearchProviders = [
@@ -179,7 +203,12 @@ const supportedSearchProviders = [
"duckduckgo",
"perplexity",
] as const;
-const deprecatedSearchProviders = new Set(["exa", "serper", "baidu", "openrouter"]);
+const deprecatedSearchProviders = new Set([
+ "exa",
+ "serper",
+ "baidu",
+ "openrouter",
+]);
// ---------------------------------------------------------------------------
// Spotlight overlay component
@@ -194,7 +223,6 @@ function SpotlightOverlay({
onNext: () => void;
onSkip: () => void;
}) {
- const { t } = useTranslation();
const [rect, setRect] = useState<DOMRect | null>(null);
const guideStep = TOUR_GUIDE_STEPS[stepIndex];
@@ -238,23 +266,23 @@ function SpotlightOverlay({
style={{ top: tooltipTop, left: tooltipLeft }}
>
<div className="mb-1 text-[13px] font-semibold text-[var(--foreground)]">
- {t(guideStep.title)}
+ {guideStep.title}
</div>
<p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t(guideStep.desc)}
+ {guideStep.desc}
</p>
<div className="flex items-center justify-between">
<button
onClick={onSkip}
className="text-[12px] text-[var(--muted-foreground)]/60 transition-colors hover:text-[var(--muted-foreground)]"
>
- {t("Skip tour")}
+ Skip tour
</button>
<button
onClick={onNext}
className="inline-flex items-center gap-1 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80"
>
- {stepIndex < TOUR_GUIDE_STEPS.length - 1 ? t("Next") : t("Got it")}
+ {stepIndex < TOUR_GUIDE_STEPS.length - 1 ? "Next" : "Got it"}
<ChevronRight className="h-3 w-3" />
</button>
</div>
@@ -278,9 +306,10 @@ function TestResultsModal({
onConfirm: () => void;
onCancel: () => void;
}) {
- const { t } = useTranslation();
- const hasCriticalFailure = results.llm === "fail" || results.embedding === "fail";
- const allDone = !testing && results.llm !== "pending" && results.embedding !== "pending";
+ const hasCriticalFailure =
+ results.llm === "fail" || results.embedding === "fail";
+ const allDone =
+ !testing && results.llm !== "pending" && results.embedding !== "pending";
const dot = (r: TourTestResult) => {
if (r === "pass") return "bg-emerald-500";
@@ -290,10 +319,10 @@ function TestResultsModal({
};
const label = (r: TourTestResult) => {
- if (r === "pass") return t("Passed");
- if (r === "fail") return t("Failed");
- if (r === "skip") return t("Skipped");
- return t("Testing...");
+ if (r === "pass") return "Passed";
+ if (r === "fail") return "Failed";
+ if (r === "skip") return "Skipped";
+ return "Testing...";
};
return (
@@ -301,10 +330,13 @@ function TestResultsModal({
<div className="w-[400px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl">
<div className="mb-5 flex items-center justify-between">
<h2 className="text-[16px] font-semibold text-[var(--foreground)]">
- {testing ? t("Running tests...") : t("Test Results")}
+ {testing ? "Running tests..." : "Test Results"}
</h2>
{!testing && (
- <button onClick={onCancel} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ <button
+ onClick={onCancel}
+ className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
<X className="h-4 w-4" />
</button>
)}
@@ -312,14 +344,23 @@ function TestResultsModal({
<div className="mb-6 space-y-3">
{(["llm", "embedding", "search"] as const).map((svc) => (
- <div key={svc} className="flex items-center justify-between rounded-lg border border-[var(--border)]/50 px-4 py-3">
+ <div
+ key={svc}
+ className="flex items-center justify-between rounded-lg border border-[var(--border)]/50 px-4 py-3"
+ >
<div className="flex items-center gap-2.5">
{serviceIcon(svc)}
- <span className="text-[13px] font-medium text-[var(--foreground)]">{svc.toUpperCase()}</span>
+ <span className="text-[13px] font-medium text-[var(--foreground)]">
+ {svc.toUpperCase()}
+ </span>
</div>
<div className="flex items-center gap-2">
- <span className={`inline-block h-2 w-2 rounded-full ${dot(results[svc])}`} />
- <span className="text-[12px] text-[var(--muted-foreground)]">{label(results[svc])}</span>
+ <span
+ className={`inline-block h-2 w-2 rounded-full ${dot(results[svc])}`}
+ />
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {label(results[svc])}
+ </span>
</div>
</div>
))}
@@ -331,7 +372,7 @@ function TestResultsModal({
onClick={onCancel}
className="flex-1 rounded-lg border border-[var(--border)] px-4 py-2 text-[13px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:text-[var(--foreground)]"
>
- {t("Back to editing")}
+ Back to editing
</button>
<button
onClick={onConfirm}
@@ -341,7 +382,7 @@ function TestResultsModal({
: "bg-[var(--foreground)] text-[var(--background)]"
}`}
>
- {hasCriticalFailure ? t("Launch anyway") : t("Confirm & Launch")}
+ {hasCriticalFailure ? "Launch anyway" : "Confirm & Launch"}
</button>
</div>
)}
@@ -349,7 +390,7 @@ function TestResultsModal({
{testing && (
<div className="flex items-center justify-center gap-2 py-2 text-[13px] text-[var(--muted-foreground)]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- {t("Please wait...")}
+ Please wait...
</div>
)}
</div>
@@ -362,12 +403,11 @@ function TestResultsModal({
// ═══════════════════════════════════════════════════════════════════════════
function SettingsPageContent() {
- const { t } = useTranslation();
const searchParams = useSearchParams();
const isTourMode = searchParams.get("tour") === "true";
const [status, setStatus] = useState<SystemStatus | null>(null);
- const [theme, setTheme] = useState<"light" | "dark" | "glass" | "snow">("light");
+ const [theme, setTheme] = useState<"light" | "dark">("light");
const [language, setLanguage] = useState<"en" | "zh">("en");
const [catalog, setCatalog] = useState<Catalog>(defaultCatalog());
const [draft, setDraft] = useState<Catalog>(defaultCatalog());
@@ -378,13 +418,18 @@ function SettingsPageContent() {
const [applying, setApplying] = useState(false);
const [toast, setToast] = useState<string>("");
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
- const [providers, setProviders] = useState<Record<ServiceName, ProviderOption[]>>({ llm: [], embedding: [], search: [] });
const eventSourceRef = useRef<EventSource | null>(null);
// Tour-specific state
const [tourGuideStep, setTourGuideStep] = useState(isTourMode ? 0 : -1);
- const [tourTestPhase, setTourTestPhase] = useState<"idle" | "testing" | "results">("idle");
- const [tourTestResults, setTourTestResults] = useState<TourTestResults>({ llm: "pending", embedding: "pending", search: "pending" });
+ const [tourTestPhase, setTourTestPhase] = useState<
+ "idle" | "testing" | "results"
+ >("idle");
+ const [tourTestResults, setTourTestResults] = useState<TourTestResults>({
+ llm: "pending",
+ embedding: "pending",
+ search: "pending",
+ });
const [tourCompleted, setTourCompleted] = useState(false);
const [tourRedirectAt, setTourRedirectAt] = useState<number | null>(null);
const [redirectCountdown, setRedirectCountdown] = useState(-1);
@@ -393,17 +438,33 @@ 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)
+ 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);
+ }
+ } catch (err) {
+ console.error("Failed to load settings:", err);
+ }
+
+ try {
+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
+ 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 () => {
@@ -422,7 +483,10 @@ function SettingsPageContent() {
useEffect(() => {
if (!tourCompleted || !tourRedirectAt) return;
const tick = () => {
- const secondsLeft = Math.max(0, Math.ceil(tourRedirectAt - Date.now() / 1000));
+ const secondsLeft = Math.max(
+ 0,
+ Math.ceil(tourRedirectAt - Date.now() / 1000),
+ );
setRedirectCountdown(secondsLeft);
};
tick();
@@ -449,10 +513,17 @@ function SettingsPageContent() {
const activeProfile = getActiveProfile(draft, activeService);
const activeModel = getActiveModel(draft, activeService);
const hasUnsavedChanges = JSON.stringify(catalog) !== JSON.stringify(draft);
- const searchProviderRaw = activeService === "search" ? (activeProfile?.provider || "").trim().toLowerCase() : "";
- const showSearchProviderWarning = activeService === "search" && Boolean(searchProviderRaw);
- const isDeprecatedSearchProvider = deprecatedSearchProviders.has(searchProviderRaw);
- const isSupportedSearchProvider = supportedSearchProviders.includes(searchProviderRaw as (typeof supportedSearchProviders)[number]);
+ const searchProviderRaw =
+ activeService === "search"
+ ? (activeProfile?.provider || "").trim().toLowerCase()
+ : "";
+ const showSearchProviderWarning =
+ activeService === "search" && Boolean(searchProviderRaw);
+ const isDeprecatedSearchProvider =
+ deprecatedSearchProviders.has(searchProviderRaw);
+ const isSupportedSearchProvider = supportedSearchProviders.includes(
+ searchProviderRaw as (typeof supportedSearchProviders)[number],
+ );
const isPerplexityMissingKey =
activeService === "search" &&
searchProviderRaw === "perplexity" &&
@@ -460,15 +531,18 @@ function SettingsPageContent() {
// -- UI preference helpers ----------------------------------------------
- const persistUi = async (nextTheme: "light" | "dark" | "glass" | "snow", nextLanguage: "en" | "zh") => {
- await fetch(apiUrl("/api/v1/settings/ui"), {
+ const persistUi = async (
+ nextTheme: "light" | "dark",
+ nextLanguage: "en" | "zh",
+ ) => {
+ await apiFetch(apiUrl("/api/v1/settings/ui"), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ theme: nextTheme, language: nextLanguage }),
});
};
- const updateTheme = async (nextTheme: "light" | "dark" | "glass" | "snow") => {
+ const updateTheme = async (nextTheme: "light" | "dark") => {
setTheme(nextTheme);
applyThemePreference(nextTheme);
await persistUi(nextTheme, language);
@@ -490,11 +564,6 @@ function SettingsPageContent() {
});
};
- const embeddingDefaultDim = (binding?: string) => {
- const match = (providers.embedding || []).find((p) => p.value === (binding || "openai"));
- return match?.default_dim || "3072";
- };
-
const addProfile = () => {
mutateCatalog((next) => {
const service = next.services[activeService];
@@ -517,7 +586,7 @@ function SettingsPageContent() {
id: modelId,
name: "New Model",
model: "",
- ...(activeService === "embedding" ? { dimension: embeddingDefaultDim() } : {}),
+ ...(activeService === "embedding" ? { dimension: "3072" } : {}),
});
service.active_model_id = modelId;
}
@@ -529,7 +598,9 @@ function SettingsPageContent() {
const removeActiveProfile = () => {
mutateCatalog((next) => {
const service = next.services[activeService];
- service.profiles = service.profiles.filter((profile) => profile.id !== service.active_profile_id);
+ service.profiles = service.profiles.filter(
+ (profile) => profile.id !== service.active_profile_id,
+ );
service.active_profile_id = service.profiles[0]?.id ?? null;
if (activeService !== "search") {
service.active_model_id = service.profiles[0]?.models?.[0]?.id ?? null;
@@ -541,14 +612,17 @@ function SettingsPageContent() {
if (activeService === "search") return;
mutateCatalog((next) => {
const service = next.services[activeService];
- const profile = service.profiles.find((item) => item.id === service.active_profile_id) ?? null;
+ const profile =
+ service.profiles.find(
+ (item) => item.id === service.active_profile_id,
+ ) ?? null;
if (!profile) return;
const modelId = `${activeService}-model-${Date.now()}`;
profile.models.push({
id: modelId,
name: "New Model",
model: "",
- ...(activeService === "embedding" ? { dimension: embeddingDefaultDim(profile.binding) } : {}),
+ ...(activeService === "embedding" ? { dimension: "3072" } : {}),
});
service.active_model_id = modelId;
});
@@ -558,9 +632,14 @@ function SettingsPageContent() {
if (activeService === "search") return;
mutateCatalog((next) => {
const service = next.services[activeService];
- const profile = service.profiles.find((item) => item.id === service.active_profile_id) ?? null;
+ const profile =
+ service.profiles.find(
+ (item) => item.id === service.active_profile_id,
+ ) ?? null;
if (!profile) return;
- profile.models = profile.models.filter((item) => item.id !== service.active_model_id);
+ profile.models = profile.models.filter(
+ (item) => item.id !== service.active_model_id,
+ );
service.active_model_id = profile.models[0]?.id ?? null;
});
};
@@ -587,7 +666,7 @@ function SettingsPageContent() {
const saveCatalog = async () => {
setSaving(true);
try {
- const response = await fetch(apiUrl("/api/v1/settings/catalog"), {
+ const response = await apiFetch(apiUrl("/api/v1/settings/catalog"), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ catalog: draft }),
@@ -595,7 +674,7 @@ function SettingsPageContent() {
const payload = await response.json();
setCatalog(payload.catalog);
setDraft(cloneCatalog(payload.catalog));
- setToast(t("Draft saved"));
+ setToast("Draft saved");
} finally {
setSaving(false);
}
@@ -604,7 +683,7 @@ function SettingsPageContent() {
const applyCatalog = async () => {
setApplying(true);
try {
- const response = await fetch(apiUrl("/api/v1/settings/apply"), {
+ const response = await apiFetch(apiUrl("/api/v1/settings/apply"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ catalog: draft }),
@@ -612,8 +691,8 @@ function SettingsPageContent() {
const payload = await response.json();
setCatalog(payload.catalog);
setDraft(cloneCatalog(payload.catalog));
- setToast(t("Applied to .env"));
- const statusResponse = await fetch(apiUrl("/api/v1/system/status"));
+ setToast("Applied to .env");
+ const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
setStatus((await statusResponse.json()) as SystemStatus);
} finally {
setApplying(false);
@@ -630,21 +709,32 @@ function SettingsPageContent() {
setLogs(`Preparing ${activeService} diagnostics...\n`);
setTestRunning(activeService);
try {
- const response = await fetch(apiUrl(`/api/v1/settings/tests/${activeService}/start`), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft }),
- });
- const payload = (await response.json()) as { run_id?: string; detail?: string };
+ const response = await fetch(
+ apiUrl(`/api/v1/settings/tests/${activeService}/start`),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ catalog: draft }),
+ },
+ );
+ const payload = (await response.json()) as {
+ run_id?: string;
+ detail?: string;
+ };
if (!response.ok || !payload.run_id) {
throw new Error(payload.detail || "Could not start diagnostics.");
}
const source = new EventSource(
- apiUrl(`/api/v1/settings/tests/${activeService}/${payload.run_id}/events`),
+ apiUrl(
+ `/api/v1/settings/tests/${activeService}/${payload.run_id}/events`,
+ ),
);
eventSourceRef.current = source;
source.onmessage = (event) => {
- const entry = JSON.parse(event.data) as { type: string; message: string };
+ const entry = JSON.parse(event.data) as {
+ type: string;
+ message: string;
+ };
setLogs((current) => `${current}[${entry.type}] ${entry.message}\n`);
if (entry.type === "completed" || entry.type === "failed") {
source.close();
@@ -657,11 +747,14 @@ function SettingsPageContent() {
source.close();
eventSourceRef.current = null;
setTestRunning(null);
- setLogs((current) => `${current}[failed] Diagnostics stream disconnected.\n`);
- setToast(t("Diagnostics stream disconnected"));
+ setLogs(
+ (current) => `${current}[failed] Diagnostics stream disconnected.\n`,
+ );
+ setToast("Diagnostics stream disconnected");
};
} catch (error) {
- const message = error instanceof Error ? error.message : "Could not start diagnostics.";
+ const message =
+ error instanceof Error ? error.message : "Could not start diagnostics.";
setLogs((current) => `${current}[failed] ${message}\n`);
setToast(message);
setTestRunning(null);
@@ -670,49 +763,69 @@ function SettingsPageContent() {
// -- Tour: run a single service test and return pass/fail ---------------
- const runSingleTest = useCallback(async (svc: ServiceName, catalogSnapshot: Catalog): Promise<"pass" | "fail"> => {
- try {
- const response = await fetch(apiUrl(`/api/v1/settings/tests/${svc}/start`), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: catalogSnapshot }),
- });
- const payload = (await response.json()) as { run_id?: string };
- if (!response.ok || !payload.run_id) return "fail";
-
- return new Promise((resolve) => {
- const source = new EventSource(
- apiUrl(`/api/v1/settings/tests/${svc}/${payload.run_id}/events`),
+ const runSingleTest = useCallback(
+ async (
+ svc: ServiceName,
+ catalogSnapshot: Catalog,
+ ): Promise<"pass" | "fail"> => {
+ try {
+ const response = await fetch(
+ apiUrl(`/api/v1/settings/tests/${svc}/start`),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ catalog: catalogSnapshot }),
+ },
);
- const timeout = setTimeout(() => { source.close(); resolve("fail"); }, 30000);
- source.onmessage = (event) => {
- const entry = JSON.parse(event.data) as { type: string };
- if (entry.type === "completed") {
- clearTimeout(timeout);
+ const payload = (await response.json()) as { run_id?: string };
+ if (!response.ok || !payload.run_id) return "fail";
+
+ return new Promise((resolve) => {
+ const source = new EventSource(
+ apiUrl(`/api/v1/settings/tests/${svc}/${payload.run_id}/events`),
+ );
+ const timeout = setTimeout(() => {
source.close();
- resolve("pass");
- } else if (entry.type === "failed") {
+ resolve("fail");
+ }, 30000);
+ source.onmessage = (event) => {
+ const entry = JSON.parse(event.data) as { type: string };
+ if (entry.type === "completed") {
+ clearTimeout(timeout);
+ source.close();
+ resolve("pass");
+ } else if (entry.type === "failed") {
+ clearTimeout(timeout);
+ source.close();
+ resolve("fail");
+ }
+ };
+ source.onerror = () => {
clearTimeout(timeout);
source.close();
resolve("fail");
- }
- };
- source.onerror = () => { clearTimeout(timeout); source.close(); resolve("fail"); };
- });
- } catch {
- return "fail";
- }
- }, []);
+ };
+ });
+ } catch {
+ return "fail";
+ }
+ },
+ [],
+ );
// -- Tour: Complete & Launch flow ---------------------------------------
const startTourComplete = async () => {
setTourTestPhase("testing");
- const results: TourTestResults = { llm: "pending", embedding: "pending", search: "pending" };
+ const results: TourTestResults = {
+ llm: "pending",
+ embedding: "pending",
+ search: "pending",
+ };
setTourTestResults({ ...results });
// Apply catalog first so backend picks up config
- await fetch(apiUrl("/api/v1/settings/apply"), {
+ await apiFetch(apiUrl("/api/v1/settings/apply"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ catalog: draft }),
@@ -730,7 +843,8 @@ function SettingsPageContent() {
// Test Search (skip if no provider configured)
const searchProfile = getActiveProfile(catalogSnapshot, "search");
- const hasSearchProvider = searchProfile?.provider && searchProfile.provider.trim() !== "";
+ const hasSearchProvider =
+ searchProfile?.provider && searchProfile.provider.trim() !== "";
if (hasSearchProvider) {
results.search = await runSingleTest("search", catalogSnapshot);
} else {
@@ -744,20 +858,28 @@ function SettingsPageContent() {
const confirmTourComplete = async () => {
setTourTestPhase("idle");
try {
- const response = await fetch(apiUrl("/api/v1/settings/tour/complete"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft, test_results: tourTestResults }),
- });
+ const response = await apiFetch(
+ apiUrl("/api/v1/settings/tour/complete"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ catalog: draft,
+ test_results: tourTestResults,
+ }),
+ },
+ );
if (response.ok) {
const payload = (await response.json()) as TourCompleteResponse;
setTourCompleted(true);
- setTourRedirectAt(payload.redirect_at ?? Math.floor(Date.now() / 1000) + 5);
+ setTourRedirectAt(
+ payload.redirect_at ?? Math.floor(Date.now() / 1000) + 5,
+ );
} else {
- setToast(t("Failed to complete tour"));
+ setToast("Failed to complete tour");
}
} catch {
- setToast(t("Failed to complete tour"));
+ setToast("Failed to complete tour");
}
};
@@ -768,9 +890,19 @@ function SettingsPageContent() {
// -- Reopen tour --------------------------------------------------------
const reopenTour = async () => {
- const response = await fetch(apiUrl("/api/v1/settings/tour/reopen"), { method: "POST" });
- const payload = (await response.json()) as { command?: string; message?: string };
- setToast(payload.command ? t("Run {{command}} in your terminal.", { command: payload.command }) : payload.message || t("Run python scripts/start_tour.py in your terminal."));
+ const response = await apiFetch(apiUrl("/api/v1/settings/tour/reopen"), {
+ method: "POST",
+ });
+ const payload = (await response.json()) as {
+ command?: string;
+ message?: string;
+ };
+ setToast(
+ payload.command
+ ? `Run ${payload.command} in your terminal.`
+ : payload.message ||
+ "Run python scripts/start_tour.py in your terminal.",
+ );
};
// ═══════════════════════════════════════════════════════════════════════
@@ -780,17 +912,17 @@ function SettingsPageContent() {
return (
<div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
<div className="mx-auto max-w-[960px] px-6 py-8">
-
{/* ── Tour Banner ── */}
{isTourMode && !tourCompleted && (
<div className="mb-6 flex items-center justify-between rounded-xl border border-[var(--primary)]/20 bg-[var(--primary)]/5 px-5 py-4">
<div>
<div className="flex items-center gap-2 text-[14px] font-semibold text-[var(--foreground)]">
<Rocket className="h-4 w-4 text-[var(--primary)]" />
- {t("Setup Tour")}
+ Setup Tour
</div>
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Configure your endpoints below, run tests, then launch DeepTutor.")}
+ Configure your endpoints below, run tests, then launch
+ DeepTutor.
</p>
</div>
<button
@@ -799,8 +931,12 @@ function SettingsPageContent() {
disabled={tourTestPhase === "testing"}
className="ml-4 inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-4 py-2 text-[13px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
>
- {tourTestPhase === "testing" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}
- {t("Complete & Launch")}
+ {tourTestPhase === "testing" ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <CheckCircle2 className="h-3.5 w-3.5" />
+ )}
+ Complete & Launch
</button>
</div>
)}
@@ -810,12 +946,12 @@ function SettingsPageContent() {
<div className="mb-6 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-4 text-center">
<div className="flex items-center justify-center gap-2 text-[14px] font-semibold text-emerald-600 dark:text-emerald-400">
<CheckCircle2 className="h-4 w-4" />
- {t("Configuration saved")}
+ Configuration saved
</div>
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
{redirectCountdown > 0
- ? t("Redirecting to DeepTutor in {{count}}s...", { count: redirectCountdown })
- : t("Redirecting...")}
+ ? `Redirecting to DeepTutor in ${redirectCountdown}s...`
+ : "Redirecting..."}
</p>
</div>
)}
@@ -824,7 +960,7 @@ function SettingsPageContent() {
<div className="mb-6 flex items-start justify-between">
<div>
<h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
- {t("Settings")}
+ Settings
</h1>
{toast ? (
<p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">
@@ -832,7 +968,9 @@ function SettingsPageContent() {
</p>
) : (
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {hasUnsavedChanges ? t("Draft has unsaved changes") : t("All changes saved")}
+ {hasUnsavedChanges
+ ? "Draft has unsaved changes"
+ : "All changes saved"}
</p>
)}
</div>
@@ -842,21 +980,29 @@ function SettingsPageContent() {
disabled={saving}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
>
- {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
- {t("Save Draft")}
+ {saving ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Save className="h-3 w-3" />
+ )}
+ Save Draft
</button>
<button
onClick={applyCatalog}
disabled={applying || isTourMode}
- title={isTourMode ? t("Complete the tour first") : undefined}
+ title={isTourMode ? "Complete the tour first" : undefined}
className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-opacity disabled:opacity-40 ${
isTourMode
? "cursor-not-allowed border border-[var(--border)]/30 bg-[var(--muted)] text-[var(--muted-foreground)]"
: "bg-[var(--foreground)] text-[var(--background)] hover:opacity-80"
}`}
>
- {applying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Wand2 className="h-3 w-3" />}
- {t("Apply")}
+ {applying ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Wand2 className="h-3 w-3" />
+ )}
+ Apply
</button>
</div>
</div>
@@ -864,9 +1010,11 @@ function SettingsPageContent() {
{/* ── Preferences & Runtime ── */}
<div className="mb-8 flex flex-wrap items-center gap-x-8 gap-y-3 border-b border-[var(--border)]/50 pb-6">
<div className="flex items-center gap-2">
- <span className="text-[12px] text-[var(--muted-foreground)]">{t("Theme")}</span>
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ Theme
+ </span>
<div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
- {(["snow", "light", "dark", "glass"] as const).map((v) => (
+ {(["light", "dark"] as const).map((v) => (
<button
key={v}
onClick={() => updateTheme(v)}
@@ -876,14 +1024,16 @@ function SettingsPageContent() {
: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
- {v === "snow" ? t("Snow") : v === "light" ? t("Light") : v === "dark" ? t("Dark") : t("Glass")}
+ {v === "light" ? "Light" : "Dark"}
</button>
))}
</div>
</div>
<div className="flex items-center gap-2">
- <span className="text-[12px] text-[var(--muted-foreground)]">{t("Language")}</span>
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ Language
+ </span>
<div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
{(["en", "zh"] as const).map((v) => (
<button
@@ -903,21 +1053,33 @@ function SettingsPageContent() {
<div className="ml-auto flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]">
<span className="flex items-center gap-1.5">
- <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(status?.backend.status === "online", false)}`} />
- {t("Backend")}
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(status?.backend.status === "online", false)}`}
+ />
+ Backend
</span>
<span className="flex items-center gap-1.5">
- <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.llm.model), Boolean(status?.llm.error))}`} />
- {t("LLM")}
- {status?.llm.model && <span className="text-[var(--muted-foreground)]/50">· {status.llm.model}</span>}
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.llm.model), Boolean(status?.llm.error))}`}
+ />
+ LLM
+ {status?.llm.model && (
+ <span className="text-[var(--muted-foreground)]/50">
+ · {status.llm.model}
+ </span>
+ )}
</span>
<span className="flex items-center gap-1.5">
- <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.embeddings.model), Boolean(status?.embeddings.error))}`} />
- {t("Emb")}
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.embeddings.model), Boolean(status?.embeddings.error))}`}
+ />
+ Emb
</span>
<span className="flex items-center gap-1.5">
- <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.search.provider), false)}`} />
- {t("Search")}
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.search.provider), false)}`}
+ />
+ Search
</span>
</div>
</div>
@@ -951,7 +1113,7 @@ function SettingsPageContent() {
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)]"
>
<Plus className="h-3 w-3" />
- {t("Profile")}
+ Profile
</button>
{activeService !== "search" && (
<button
@@ -959,7 +1121,7 @@ function SettingsPageContent() {
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)]"
>
<Plus className="h-3 w-3" />
- {t("Model")}
+ Model
</button>
)}
</div>
@@ -974,7 +1136,8 @@ function SettingsPageContent() {
key={profile.id}
onClick={() =>
mutateCatalog((next) => {
- next.services[activeService].active_profile_id = profile.id;
+ next.services[activeService].active_profile_id =
+ profile.id;
if (activeService !== "search") {
next.services[activeService].active_model_id =
profile.models[0]?.id ?? null;
@@ -982,14 +1145,17 @@ function SettingsPageContent() {
})
}
className={`w-full rounded-lg px-3 py-2.5 text-left transition-colors ${
- profile.id === draft.services[activeService].active_profile_id
+ profile.id ===
+ draft.services[activeService].active_profile_id
? "bg-[var(--muted)] text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
}`}
>
- <div className="text-[13px] font-medium">{profile.name}</div>
+ <div className="text-[13px] font-medium">
+ {profile.name}
+ </div>
<div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profile.base_url || t("No endpoint")}
+ {profile.base_url || "No endpoint"}
</div>
</button>
))}
@@ -999,7 +1165,7 @@ function SettingsPageContent() {
className="flex w-full items-center gap-1.5 rounded-lg px-3 py-2 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
>
<Trash2 className="h-3 w-3" />
- {t("Delete profile")}
+ Delete profile
</button>
</div>
@@ -1007,49 +1173,44 @@ function SettingsPageContent() {
<div className="space-y-5">
<div className="rounded-xl border border-[var(--border)] p-5">
<div className="mb-4 text-[13px] font-medium text-[var(--foreground)]">
- {t("Profile")}
+ Profile
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Name")}</div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Name
+ </div>
<input
className={inputClass}
value={activeProfile.name}
- onChange={(e) => updateProfileField("name", e.target.value)}
+ onChange={(e) =>
+ updateProfileField("name", e.target.value)
+ }
/>
</div>
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Provider")}
- </div>
- <div className="relative">
- <select
- className={selectClass}
- value={
- activeService === "search"
- ? activeProfile.provider || ""
- : activeProfile.binding || ""
- }
- onChange={(e) => {
- const val = e.target.value;
- const field = activeService === "search" ? "provider" : "binding";
- updateProfileField(field, val);
- const match = (providers[activeService] || []).find((p) => p.value === val);
- if (match?.base_url) {
- updateProfileField("base_url", match.base_url);
- }
- if (activeService === "embedding" && match?.default_dim) {
- updateModelField("dimension", match.default_dim);
- }
- }}
- >
- <option value="">{t("Select provider...")}</option>
- {(providers[activeService] || []).map((p) => (
- <option key={p.value} value={p.value}>{p.label}</option>
- ))}
- </select>
- <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />
+ {activeService === "search"
+ ? "Provider"
+ : "Provider Hint / Binding"}
</div>
+ <input
+ className={inputClass}
+ value={
+ activeService === "search"
+ ? activeProfile.provider || ""
+ : activeProfile.binding || ""
+ }
+ onChange={(e) =>
+ updateProfileField(
+ activeService === "search" ? "provider" : "binding",
+ e.target.value,
+ )
+ }
+ placeholder={
+ activeService === "search" ? "brave" : "openai"
+ }
+ />
{showSearchProviderWarning && (
<p
className={`mt-1.5 text-[11px] ${
@@ -1062,60 +1223,80 @@ function SettingsPageContent() {
>
{isSupportedSearchProvider
? isPerplexityMissingKey
- ? t("Perplexity requires API key. It will fail hard without credentials.")
- : t("Supported provider.")
+ ? "Perplexity requires API key. It will fail hard without credentials."
+ : "Supported provider."
: isDeprecatedSearchProvider
- ? t("Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.")
- : t("Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.")}
+ ? "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity."
+ : "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity."}
</p>
)}
</div>
<div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Base URL")}</div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Base URL
+ </div>
<input
className={inputClass}
value={activeProfile.base_url}
- onChange={(e) => updateProfileField("base_url", e.target.value)}
+ onChange={(e) =>
+ updateProfileField("base_url", e.target.value)
+ }
placeholder="https://api.openai.com/v1"
/>
</div>
<div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Key")}</div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ API Key
+ </div>
<input
className={inputClass}
value={activeProfile.api_key}
- onChange={(e) => updateProfileField("api_key", e.target.value)}
+ onChange={(e) =>
+ updateProfileField("api_key", e.target.value)
+ }
placeholder="sk-..."
/>
</div>
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Version")}</div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ API Version
+ </div>
<input
className={inputClass}
value={activeProfile.api_version}
- onChange={(e) => updateProfileField("api_version", e.target.value)}
- placeholder={t("Optional")}
+ onChange={(e) =>
+ updateProfileField("api_version", e.target.value)
+ }
+ placeholder="Optional"
/>
</div>
{activeService === "search" ? (
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Proxy")}</div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Proxy
+ </div>
<input
className={inputClass}
value={activeProfile.proxy || ""}
- onChange={(e) => updateProfileField("proxy", e.target.value)}
+ onChange={(e) =>
+ updateProfileField("proxy", e.target.value)
+ }
placeholder="http://127.0.0.1:7890 (optional)"
/>
</div>
) : (
<div className="sm:col-span-2">
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Extra Headers (JSON)")}
+ Extra Headers (JSON)
</div>
<textarea
className={`${inputClass} min-h-[84px] resize-y`}
- value={stringifyExtraHeaders(activeProfile.extra_headers)}
- onChange={(e) => updateProfileField("extra_headers", e.target.value)}
+ value={stringifyExtraHeaders(
+ activeProfile.extra_headers,
+ )}
+ onChange={(e) =>
+ updateProfileField("extra_headers", e.target.value)
+ }
placeholder='{"APP-Code":"your-app-code"}'
/>
</div>
@@ -1126,14 +1307,16 @@ function SettingsPageContent() {
{activeService !== "search" && (
<div className="rounded-xl border border-[var(--border)] p-5">
<div className="mb-4 flex items-center justify-between">
- <div className="text-[13px] font-medium text-[var(--foreground)]">{t("Models")}</div>
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ Models
+ </div>
<button
onClick={removeActiveModel}
disabled={!activeModel}
className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
>
<Trash2 className="h-3 w-3" />
- {t("Delete")}
+ Delete
</button>
</div>
{activeProfile.models.length > 0 && (
@@ -1143,11 +1326,13 @@ function SettingsPageContent() {
key={model.id}
onClick={() =>
mutateCatalog((next) => {
- next.services[activeService].active_model_id = model.id;
+ next.services[activeService].active_model_id =
+ model.id;
})
}
className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- model.id === draft.services[activeService].active_model_id
+ model.id ===
+ draft.services[activeService].active_model_id
? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
}`}
@@ -1160,17 +1345,42 @@ function SettingsPageContent() {
{activeModel && (
<div className="grid gap-4 sm:grid-cols-2">
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Label")}</div>
- <input className={inputClass} value={activeModel.name} onChange={(e) => updateModelField("name", e.target.value)} />
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Label
+ </div>
+ <input
+ className={inputClass}
+ value={activeModel.name}
+ onChange={(e) =>
+ updateModelField("name", e.target.value)
+ }
+ />
</div>
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Model ID")}</div>
- <input className={inputClass} value={activeModel.model} onChange={(e) => updateModelField("model", e.target.value)} placeholder="gpt-4o" />
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Model ID
+ </div>
+ <input
+ className={inputClass}
+ value={activeModel.model}
+ onChange={(e) =>
+ updateModelField("model", e.target.value)
+ }
+ placeholder="gpt-4o"
+ />
</div>
{activeService === "embedding" && (
<div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("Dimension")}</div>
- <input className={inputClass} value={activeModel.dimension || embeddingDefaultDim(activeProfile?.binding)} onChange={(e) => updateModelField("dimension", e.target.value)} />
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ Dimension
+ </div>
+ <input
+ className={inputClass}
+ value={activeModel.dimension || "3072"}
+ onChange={(e) =>
+ updateModelField("dimension", e.target.value)
+ }
+ />
</div>
)}
</div>
@@ -1181,7 +1391,7 @@ function SettingsPageContent() {
</div>
) : (
<div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">
- {t("No profiles configured. Add a profile to start.")}
+ No profiles configured. Add a profile to start.
</div>
)}
</div>
@@ -1196,34 +1406,52 @@ function SettingsPageContent() {
aria-expanded={diagnosticsOpen}
>
<Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- <span className="text-[13px] font-medium text-[var(--foreground)]">{t("Diagnostics")}</span>
- {testRunning && <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />}
+ <span className="text-[13px] font-medium text-[var(--foreground)]">
+ Diagnostics
+ </span>
+ {testRunning && (
+ <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />
+ )}
</button>
<div className="ml-3 flex items-center gap-3">
<button
type="button"
- onClick={() => { if (!diagnosticsOpen) setDiagnosticsOpen(true); runDetailedTest(); }}
+ onClick={() => {
+ if (!diagnosticsOpen) setDiagnosticsOpen(true);
+ runDetailedTest();
+ }}
disabled={testRunning !== null}
className="inline-flex items-center gap-1.5 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)] disabled:opacity-40"
>
{serviceIcon(activeService)}
- {t("Run test")}
+ Run test
</button>
<button
type="button"
onClick={() => setDiagnosticsOpen((v) => !v)}
className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- aria-label={diagnosticsOpen ? t("Collapse diagnostics") : t("Expand diagnostics")}
+ aria-label={
+ diagnosticsOpen
+ ? "Collapse diagnostics"
+ : "Expand diagnostics"
+ }
aria-expanded={diagnosticsOpen}
>
- <ChevronDown className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`} />
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`}
+ />
</button>
</div>
</div>
{diagnosticsOpen && (
<div className="border-t border-[var(--border)] px-5 py-4">
<p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t("Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.", { service: activeService })}
+ Streams config snapshot, request target, response summary, and
+ service-specific validation for the active{" "}
+ <span className="font-medium text-[var(--foreground)]">
+ {activeService}
+ </span>{" "}
+ profile.
</p>
<pre className="max-h-[360px] overflow-y-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] dark:bg-[#0a0a0a]">
{logs}
@@ -1240,7 +1468,7 @@ function SettingsPageContent() {
className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]/40 transition-colors hover:text-[var(--muted-foreground)]"
>
<RotateCcw className="h-3 w-3" />
- {t("Run Terminal Tour")}
+ Run Terminal Tour
</button>
)}
<span className="text-[11px] text-[var(--muted-foreground)]/30 ml-auto">
@@ -1250,19 +1478,22 @@ function SettingsPageContent() {
</div>
{/* ── Spotlight overlay (tour onboarding) ── */}
- {isTourMode && tourGuideStep >= 0 && tourGuideStep < TOUR_GUIDE_STEPS.length && !tourCompleted && (
- <SpotlightOverlay
- stepIndex={tourGuideStep}
- onNext={() => {
- if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {
- setTourGuideStep((s) => s + 1);
- } else {
- setTourGuideStep(-1);
- }
- }}
- onSkip={() => setTourGuideStep(-1)}
- />
- )}
+ {isTourMode &&
+ tourGuideStep >= 0 &&
+ tourGuideStep < TOUR_GUIDE_STEPS.length &&
+ !tourCompleted && (
+ <SpotlightOverlay
+ stepIndex={tourGuideStep}
+ onNext={() => {
+ if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {
+ setTourGuideStep((s) => s + 1);
+ } else {
+ setTourGuideStep(-1);
+ }
+ }}
+ onSkip={() => setTourGuideStep(-1)}
+ />
+ )}
{/* ── Test results modal (tour) ── */}
{isTourMode && tourTestPhase !== "idle" && (
@@ -1278,12 +1509,11 @@ function SettingsPageContent() {
}
export default function SettingsPage() {
- const { t } = useTranslation();
return (
<Suspense
fallback={
<div className="min-h-[50vh] flex items-center justify-center text-[13px] text-[var(--muted-foreground)]">
- {t("Loading settings...")}
+ Loading settings...
</div>
}
>
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index 75b97fb56..1b7c2b280 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -16,13 +16,15 @@ import {
X,
} from "lucide-react";
import { useRouter } from "next/navigation";
-import { useTranslation } from "react-i18next";
import dynamic from "next/dynamic";
import { apiUrl } from "@/lib/api";
-const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {
- ssr: false,
-});
+const MarkdownRenderer = dynamic(
+ () => import("@/components/common/MarkdownRenderer"),
+ {
+ ssr: false,
+ },
+);
/* ── Types ──────────────────────────────────────────────── */
@@ -45,14 +47,19 @@ interface SoulTemplate {
type Tab = "bots" | "profiles" | "souls";
-const BOT_FILES = ["SOUL.md", "USER.md", "TOOLS.md", "AGENTS.md", "HEARTBEAT.md"] as const;
+const BOT_FILES = [
+ "SOUL.md",
+ "USER.md",
+ "TOOLS.md",
+ "AGENTS.md",
+ "HEARTBEAT.md",
+] as const;
type BotFile = (typeof BOT_FILES)[number];
/* ── Main Page ──────────────────────────────────────────── */
export default function AgentsPage() {
const router = useRouter();
- const { t } = useTranslation();
const [bots, setBots] = useState<BotInfo[]>([]);
const [souls, setSouls] = useState<SoulTemplate[]>([]);
const [loading, setLoading] = useState(true);
@@ -61,15 +68,16 @@ export default function AgentsPage() {
useEffect(() => {
if (!toast) return;
- const timer = setTimeout(() => setToast(""), 3500);
- return () => clearTimeout(timer);
+ const t = setTimeout(() => setToast(""), 3500);
+ return () => clearTimeout(t);
}, [toast]);
const loadBots = useCallback(async () => {
setLoading(true);
try {
const res = await fetch(apiUrl("/api/v1/tutorbot"));
- setBots(await res.json());
+ const data = await res.json();
+ setBots(Array.isArray(data) ? data : (data.bots ?? []));
} finally {
setLoading(false);
}
@@ -79,10 +87,15 @@ export default function AgentsPage() {
try {
const res = await fetch(apiUrl("/api/v1/tutorbot/souls"));
if (res.ok) setSouls(await res.json());
- } catch { /* ignore */ }
+ } catch {
+ /* ignore */
+ }
}, []);
- useEffect(() => { void loadBots(); void loadSouls(); }, [loadBots, loadSouls]);
+ useEffect(() => {
+ void loadBots();
+ void loadSouls();
+ }, [loadBots, loadSouls]);
return (
<div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
@@ -90,30 +103,32 @@ export default function AgentsPage() {
{/* Header */}
<div className="mb-6">
<h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
- {t("TutorBot Agents")}
+ TutorBot Agents
</h1>
{toast ? (
- <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">{toast}</p>
+ <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">
+ {toast}
+ </p>
) : (
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Manage your in-process TutorBot instances")}
+ Manage your in-process TutorBot instances
</p>
)}
</div>
{/* Tabs */}
<div className="mb-6 flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">
- {([
- { key: "bots" as Tab, label: t("Bots"), icon: Bot },
- { key: "profiles" as Tab, label: t("Profiles"), icon: FileText },
- { key: "souls" as Tab, label: t("Souls"), icon: Heart },
- ]).map((tab) => {
- const Icon = tab.icon;
- const active = activeTab === tab.key;
+ {[
+ { key: "bots" as Tab, label: "Bots", icon: Bot },
+ { key: "profiles" as Tab, label: "Profiles", icon: FileText },
+ { key: "souls" as Tab, label: "Souls", icon: Heart },
+ ].map((t) => {
+ const Icon = t.icon;
+ const active = activeTab === t.key;
return (
<button
- key={tab.key}
- onClick={() => setActiveTab(tab.key)}
+ key={t.key}
+ onClick={() => setActiveTab(t.key)}
className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
active
? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
@@ -121,7 +136,7 @@ export default function AgentsPage() {
}`}
>
<Icon className="h-3.5 w-3.5" />
- {tab.label}
+ {t.label}
</button>
);
})}
@@ -163,7 +178,6 @@ function BotsTab({
onToast: (msg: string) => void;
router: ReturnType<typeof useRouter>;
}) {
- const { t } = useTranslation();
const [showCreate, setShowCreate] = useState(false);
const [creating, setCreating] = useState(false);
@@ -174,12 +188,19 @@ function BotsTab({
const [formModel, setFormModel] = useState("");
const resetForm = () => {
- setFormName(""); setFormDesc(""); setFormSoulId("_custom");
- setFormSoul(""); setFormModel("");
+ setFormName("");
+ setFormDesc("");
+ setFormSoulId("_custom");
+ setFormSoul("");
+ setFormModel("");
};
const botId = useMemo(() => {
- const slug = formName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ const slug = formName
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
return slug || "";
}, [formName]);
@@ -217,25 +238,52 @@ function BotsTab({
}
}, [botId, formName, formDesc, formSoul, formModel, onReload, onToast]);
- const startBot = useCallback(async (bid: string) => {
- const res = await fetch(apiUrl("/api/v1/tutorbot"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ bot_id: bid }),
- });
- if (res.ok) { onToast(`${bid} started`); await onReload(); }
- }, [onReload, onToast]);
-
- const stopBot = useCallback(async (bid: string) => {
- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), { method: "DELETE" });
- if (res.ok) { onToast(`${bid} stopped`); await onReload(); }
- }, [onReload, onToast]);
-
- const destroyBot = useCallback(async (bid: string, name: string) => {
- if (!window.confirm(t("Permanently delete \"{{name}}\" ({{id}})? This cannot be undone.", { name, id: bid }))) return;
- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), { method: "DELETE" });
- if (res.ok) { onToast(`${name} deleted`); await onReload(); }
- }, [onReload, onToast, t]);
+ const startBot = useCallback(
+ async (bid: string) => {
+ const res = await fetch(apiUrl("/api/v1/tutorbot"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ bot_id: bid }),
+ });
+ if (res.ok) {
+ onToast(`${bid} started`);
+ await onReload();
+ }
+ },
+ [onReload, onToast],
+ );
+
+ const stopBot = useCallback(
+ async (bid: string) => {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), {
+ method: "DELETE",
+ });
+ if (res.ok) {
+ onToast(`${bid} stopped`);
+ await onReload();
+ }
+ },
+ [onReload, onToast],
+ );
+
+ const destroyBot = useCallback(
+ async (bid: string, name: string) => {
+ if (
+ !window.confirm(
+ `Permanently delete "${name}" (${bid})? This cannot be undone.`,
+ )
+ )
+ return;
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), {
+ method: "DELETE",
+ });
+ if (res.ok) {
+ onToast(`${name} deleted`);
+ await onReload();
+ }
+ },
+ [onReload, onToast],
+ );
return (
<>
@@ -246,7 +294,7 @@ function BotsTab({
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
>
<Plus className="h-3 w-3" />
- {t("New Bot")}
+ New Bot
</button>
</div>
@@ -254,35 +302,52 @@ function BotsTab({
{showCreate && (
<div className="mb-6 rounded-xl border border-[var(--border)] p-5">
<div className="mb-4 flex items-center justify-between">
- <h2 className="text-[15px] font-medium text-[var(--foreground)]">{t("Create TutorBot")}</h2>
- <button onClick={() => { setShowCreate(false); resetForm(); }} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">
+ Create TutorBot
+ </h2>
+ <button
+ onClick={() => {
+ setShowCreate(false);
+ resetForm();
+ }}
+ className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
<X className="h-4 w-4" />
</button>
</div>
<div className="grid gap-3">
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Name
+ </label>
<input
value={formName}
onChange={(e) => setFormName(e.target.value)}
- placeholder={t("e.g. Math Tutor")}
+ placeholder="e.g. Math Tutor"
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
/>
{botId && (
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">ID: {botId}</p>
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ ID: {botId}
+ </p>
)}
</div>
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Description")} <span className="font-normal opacity-60">{t("(optional)")}</span></label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Description{" "}
+ <span className="font-normal opacity-60">(optional)</span>
+ </label>
<input
value={formDesc}
onChange={(e) => setFormDesc(e.target.value)}
- placeholder={t("A brief description of what this bot does")}
+ placeholder="A brief description of what this bot does"
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
/>
</div>
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Soul")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Soul
+ </label>
<div className="flex flex-wrap gap-1.5 mb-2">
<button
onClick={() => selectSoul("_custom")}
@@ -292,7 +357,7 @@ function BotsTab({
: "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
- {t("Custom")}
+ Custom
</button>
{souls.map((s) => (
<button
@@ -310,21 +375,27 @@ function BotsTab({
</div>
<textarea
value={formSoul}
- onChange={(e) => { setFormSoul(e.target.value); setFormSoulId("_custom"); }}
- placeholder={t("Define the bot's personality, values, and communication style in markdown...")}
+ onChange={(e) => {
+ setFormSoul(e.target.value);
+ setFormSoulId("_custom");
+ }}
+ placeholder="Define the bot's personality, values, and communication style in markdown..."
rows={8}
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
/>
<p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
- {t("Pick a soul from the library above, or write your own. Manage the library in the Souls tab.")}
+ Pick a soul from the library above, or write your own. Manage
+ the library in the Souls tab.
</p>
</div>
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Model")} <span className="font-normal opacity-60">{t("(optional)")}</span></label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Model <span className="font-normal opacity-60">(optional)</span>
+ </label>
<input
value={formModel}
onChange={(e) => setFormModel(e.target.value)}
- placeholder={t("Uses default model if empty")}
+ placeholder="Uses default model if empty"
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
/>
</div>
@@ -334,8 +405,12 @@ function BotsTab({
disabled={creating || !botId}
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
>
- {creating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
- {t("Create & Start")}
+ {creating ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Play className="h-3.5 w-3.5" />
+ )}
+ Create & Start
</button>
</div>
</div>
@@ -352,9 +427,11 @@ function BotsTab({
<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
<Bot size={18} />
</div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No TutorBots yet")}</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ No TutorBots yet
+ </p>
<p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Create your first TutorBot to get started.")}
+ Create your first TutorBot to get started.
</p>
</div>
) : (
@@ -365,18 +442,26 @@ function BotsTab({
className="flex items-center justify-between rounded-xl border border-[var(--border)] px-5 py-4 transition-colors hover:border-[var(--border)]"
>
<div className="flex items-center gap-4 min-w-0">
- <div className={`h-2 w-2 shrink-0 rounded-full ${bot.running ? "bg-emerald-500" : "bg-[var(--muted-foreground)]/30"}`} />
+ <div
+ className={`h-2 w-2 shrink-0 rounded-full ${bot.running ? "bg-emerald-500" : "bg-[var(--muted-foreground)]/30"}`}
+ />
<div className="min-w-0">
- <p className="text-[14px] font-medium text-[var(--foreground)] truncate">{bot.name}</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)] truncate">
+ {bot.name}
+ </p>
<div className="mt-0.5 flex items-center gap-3 text-[12px] text-[var(--muted-foreground)]">
{bot.description ? (
- <span className="truncate max-w-[300px]">{bot.description}</span>
+ <span className="truncate max-w-[300px]">
+ {bot.description}
+ </span>
) : (
<span>{bot.bot_id}</span>
)}
{bot.model && <span>· {bot.model}</span>}
{bot.started_at && (
- <span>· {t("started {{time}}", { time: new Date(bot.started_at).toLocaleString() })}</span>
+ <span>
+ · started {new Date(bot.started_at).toLocaleString()}
+ </span>
)}
</div>
</div>
@@ -389,14 +474,14 @@ function BotsTab({
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--primary)] transition-colors hover:border-[var(--primary)]/50"
>
<MessageCircle className="h-3 w-3" />
- {t("Chat")}
+ Chat
</button>
<button
onClick={() => stopBot(bot.bot_id)}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-red-400 transition-colors hover:border-red-400/50"
>
<Square className="h-3 w-3" />
- {t("Stop")}
+ Stop
</button>
</>
) : (
@@ -405,7 +490,7 @@ function BotsTab({
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
>
<Play className="h-3 w-3" />
- {t("Start")}
+ Start
</button>
)}
<button
@@ -434,7 +519,6 @@ function ProfilesTab({
loading: boolean;
onToast: (msg: string) => void;
}) {
- const { t } = useTranslation();
const [selectedBot, setSelectedBot] = useState<string>("");
const [activeFile, setActiveFile] = useState<BotFile>("SOUL.md");
const [files, setFiles] = useState<Record<string, string>>({});
@@ -451,18 +535,21 @@ function ProfilesTab({
}
}, [bots, selectedBot]);
- const loadFiles = useCallback(async (bid: string) => {
- if (!bid) return;
- setLoadingFiles(true);
- try {
- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));
- const data: Record<string, string> = await res.json();
- setFiles(data);
- setEditor(data[activeFile] ?? "");
- } finally {
- setLoadingFiles(false);
- }
- }, [activeFile]);
+ const loadFiles = useCallback(
+ async (bid: string) => {
+ if (!bid) return;
+ setLoadingFiles(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));
+ const data: Record<string, string> = await res.json();
+ setFiles(data);
+ setEditor(data[activeFile] ?? "");
+ } finally {
+ setLoadingFiles(false);
+ }
+ },
+ [activeFile],
+ );
useEffect(() => {
if (selectedBot) void loadFiles(selectedBot);
@@ -477,11 +564,14 @@ function ProfilesTab({
if (!selectedBot) return;
setSaving(true);
try {
- const res = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: editor }),
- });
+ const res = await fetch(
+ apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content: editor }),
+ },
+ );
if (res.ok) {
setFiles((prev) => ({ ...prev, [activeFile]: editor }));
onToast(`${activeFile} saved`);
@@ -515,9 +605,11 @@ function ProfilesTab({
<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
<FileText size={18} />
</div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No bots to configure")}</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ 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.")}
+ Create a bot first in the Bots tab.
</p>
</div>
);
@@ -527,7 +619,9 @@ function ProfilesTab({
<div className="space-y-4">
{/* Bot selector */}
<div className="flex items-center gap-3">
- <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">{t("Bot")}</label>
+ <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">
+ Bot
+ </label>
<select
value={selectedBot}
onChange={(e) => setSelectedBot(e.target.value)}
@@ -571,7 +665,7 @@ function ProfilesTab({
: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
- {v === "edit" ? t("Edit") : t("Preview")}
+ {v === "edit" ? "Edit" : "Preview"}
</button>
))}
</div>
@@ -580,8 +674,12 @@ function ProfilesTab({
disabled={saving || !hasChanges}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
>
- {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
- {t("Save")}
+ {saving ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Save className="h-3 w-3" />
+ )}
+ Save
</button>
</div>
@@ -598,22 +696,28 @@ function ProfilesTab({
onKeyDown={handleKeyDown}
spellCheck={false}
className="min-h-[420px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- placeholder={t("Edit {{file}}...", { file: activeFile })}
+ placeholder={`Edit ${activeFile}...`}
/>
<p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">
- {t("Cmd+S to save · Markdown supported")}
- {hasChanges && ` · ${t("Unsaved changes")}`}
+ Cmd+S to save · Markdown supported
+ {hasChanges && " · Unsaved changes"}
</p>
</div>
) : editor.trim() ? (
<div className="rounded-xl border border-[var(--border)] px-6 py-5">
- <MarkdownRenderer content={editor} variant="prose" className="text-[14px] leading-relaxed" />
+ <MarkdownRenderer
+ content={editor}
+ variant="prose"
+ className="text-[14px] leading-relaxed"
+ />
</div>
) : (
<div className="flex min-h-[300px] 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("{{file}} is empty", { file: activeFile })}</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ {activeFile} is empty
+ </p>
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Switch to Edit to add content.")}
+ Switch to Edit to add content.
</p>
</div>
)}
@@ -632,7 +736,6 @@ function SoulsTab({
onReload: () => Promise<void>;
onToast: (msg: string) => void;
}) {
- const { t } = useTranslation();
const [editing, setEditing] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
const [saving, setSaving] = useState(false);
@@ -684,7 +787,10 @@ function SoulsTab({
const createSoul = useCallback(async () => {
const name = newName.trim();
if (!name) return;
- const id = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ const id = name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
if (!id) return;
setSaving(true);
try {
@@ -707,15 +813,20 @@ function SoulsTab({
}
}, [newName, newContent, onReload, onToast]);
- const deleteSoul = useCallback(async (soul: SoulTemplate) => {
- if (!window.confirm(t("Delete soul \"{{name}}\"?", { name: soul.name }))) return;
- const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), { method: "DELETE" });
- if (res.ok) {
- if (editing === soul.id) cancelEdit();
- onToast(`"${soul.name}" deleted`);
- await onReload();
- }
- }, [editing, onReload, onToast, t]);
+ 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}`), {
+ method: "DELETE",
+ });
+ if (res.ok) {
+ if (editing === soul.id) cancelEdit();
+ onToast(`"${soul.name}" deleted`);
+ await onReload();
+ }
+ },
+ [editing, onReload, onToast],
+ );
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>, save: () => void) => {
@@ -732,14 +843,14 @@ function SoulsTab({
{/* Header */}
<div className="flex items-center justify-between">
<p className="text-[13px] text-[var(--muted-foreground)]">
- {t("Reusable soul templates for creating TutorBots.")}
+ Reusable soul templates for creating TutorBots.
</p>
<button
onClick={startCreate}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
>
<Plus className="h-3 w-3" />
- {t("New Soul")}
+ New Soul
</button>
</div>
@@ -747,33 +858,47 @@ function SoulsTab({
{creating && (
<div className="rounded-xl border border-[var(--border)] p-5">
<div className="mb-4 flex items-center justify-between">
- <h2 className="text-[15px] font-medium text-[var(--foreground)]">{t("New Soul")}</h2>
- <button onClick={() => setCreating(false)} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">
+ New Soul
+ </h2>
+ <button
+ onClick={() => setCreating(false)}
+ className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
<X className="h-4 w-4" />
</button>
</div>
<div className="grid gap-3">
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Name
+ </label>
<input
value={newName}
onChange={(e) => setNewName(e.target.value)}
- placeholder={t("e.g. Creative Writer")}
+ placeholder="e.g. Creative Writer"
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
/>
{newName.trim() && (
<p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- ID: {newName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}
+ ID:{" "}
+ {newName
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "")}
</p>
)}
</div>
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Content")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Content
+ </label>
<textarea
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
onKeyDown={(e) => handleKeyDown(e, createSoul)}
- placeholder={t("Define the soul in markdown...")}
+ placeholder="Define the soul in markdown..."
rows={10}
spellCheck={false}
className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
@@ -784,15 +909,19 @@ function SoulsTab({
onClick={() => setCreating(false)}
className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
>
- {t("Cancel")}
+ Cancel
</button>
<button
onClick={createSoul}
disabled={saving || !newName.trim()}
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
>
- {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
- {t("Create")}
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ Create
</button>
</div>
</div>
@@ -805,19 +934,27 @@ function SoulsTab({
<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
<Heart size={18} />
</div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No souls yet")}</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ No souls yet
+ </p>
<p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Create your first soul template. Default presets will be seeded automatically on next server restart.")}
+ Create your first soul template. Default presets will be seeded
+ automatically on next server restart.
</p>
</div>
) : (
<div className="grid gap-3">
{souls.map((soul) =>
editing === soul.id ? (
- <div key={soul.id} className="rounded-xl border border-[var(--ring)] p-5">
+ <div
+ key={soul.id}
+ className="rounded-xl border border-[var(--ring)] p-5"
+ >
<div className="grid gap-3">
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Name")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Name
+ </label>
<input
value={editName}
onChange={(e) => setEditName(e.target.value)}
@@ -825,7 +962,9 @@ function SoulsTab({
/>
</div>
<div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Content")}</label>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
+ Content
+ </label>
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
@@ -840,15 +979,19 @@ function SoulsTab({
onClick={cancelEdit}
className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
>
- {t("Cancel")}
+ Cancel
</button>
<button
onClick={saveSoul}
disabled={saving || !editName.trim()}
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
>
- {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
- {t("Save")}
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Save className="h-3.5 w-3.5" />
+ )}
+ Save
</button>
</div>
</div>
@@ -861,8 +1004,12 @@ function SoulsTab({
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<Heart className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />
- <p className="text-[14px] font-medium text-[var(--foreground)]">{soul.name}</p>
- <span className="text-[11px] text-[var(--muted-foreground)]/60">{soul.id}</span>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ {soul.name}
+ </p>
+ <span className="text-[11px] text-[var(--muted-foreground)]/60">
+ {soul.id}
+ </span>
</div>
<p className="mt-1.5 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)] pl-5.5">
{soul.content.replace(/^#.*\n+/g, "").slice(0, 200)}
diff --git a/web/lib/auth.ts b/web/lib/auth.ts
index 1b8a1a3d1..39eb9bb71 100644
--- a/web/lib/auth.ts
+++ b/web/lib/auth.ts
@@ -43,12 +43,27 @@ export async function login(
if (res.ok) return { ok: true };
const data = await res.json().catch(() => ({}));
- return { ok: false, error: data.detail ?? "Login failed" };
+ return { ok: false, error: extractDetail(data.detail) ?? "Login failed" };
} catch {
return { ok: false, error: "Could not reach the server" };
}
}
+/**
+ * Normalise a FastAPI error detail to a plain string.
+ * FastAPI can return detail as a string (HTTPException) or as an array of
+ * validation error objects (422 Unprocessable Entity).
+ */
+function extractDetail(detail: unknown): string {
+ if (typeof detail === "string") return detail;
+ if (Array.isArray(detail) && detail.length > 0) {
+ const first = detail[0];
+ if (typeof first === "object" && first !== null && "msg" in first)
+ return String((first as { msg: unknown }).msg);
+ }
+ return "Request failed";
+}
+
/**
* Register a new account. The first user to register becomes admin.
*/
@@ -72,7 +87,7 @@ export async function register(
const data = await res.json().catch(() => ({}));
if (res.ok)
return { ok: true, role: data.role, is_first_user: data.is_first_user };
- return { ok: false, error: data.detail ?? "Registration failed" };
+ return { ok: false, error: extractDetail(data.detail) };
} catch {
return { ok: false, error: "Could not reach the server" };
}
diff --git a/web/package-lock.json b/web/package-lock.json
index 6cbf89e4a..80cccb123 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -4817,6 +4817,7 @@
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,