Merge branch 'dev' into main (v1.2.2)

This commit is contained in:
Bingxi Zhao (Frank)
2026-04-22 20:46:08 +08:00
36 changed files with 1221 additions and 233 deletions

View File

@@ -64,6 +64,10 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# Pass the release tag (e.g. "v1.2.3") into the Next.js build so the
# sidebar version badge can show the running version at runtime.
build-args: |
APP_VERSION=${{ github.ref_name }}
# Use GitHub Actions cache to speed up repeated builds
# mode=max caches all intermediate layers (frontend-builder and python-base are expensive)
cache-from: type=gha

View File

@@ -25,6 +25,12 @@ WORKDIR /app/web
# Accept build argument for backend port
ARG BACKEND_PORT=8001
# Application version (e.g. "v1.2.3"). Passed by CI from the release tag
# and inlined into the Next.js bundle via NEXT_PUBLIC_APP_VERSION so the
# sidebar version badge can compare it with the latest GitHub release.
ARG APP_VERSION=""
ENV APP_VERSION=$APP_VERSION
# Copy package files first for better caching
COPY web/package.json web/package-lock.json* ./

View File

@@ -26,6 +26,8 @@
### 📦 Releases
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — User-authored Skills system (CRUD + chat integration), chat input performance overhaul with state colocation, `response_format` auto-fallback for incompatible providers, LAN remote access fix, sidebar version badge, Deep Solve image attachments, TutorBot WebSocket auto-start, Book Library UI, and visualization fullscreen mode.
> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Per-stage chat token limits in `agents.yaml` (8000-token responses), Regenerate last response across CLI / WebSocket / Web UI, RAG `None`-embedding crash fix, Gemma `json_object` compatibility, and dark code-block readability.
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine multi-agent "living book" compiler with 14 block types, multi-document Co-Writer workspace, interactive HTML visualizations, Question Bank @-mention in chat, prompt externalization phase 2, and sidebar overhaul.
@@ -71,6 +73,8 @@
### 📰 News
> **[2026.4.19]** 🎉 We've reached 20k stars after 111 days! Thank you for the incredible support — we're committed to continuous iteration toward truly personalized, intelligent tutoring for everyone.
> **[2026.4.4]** Long time no see! ✨ DeepTutor v1.0.0 is finally here — an agent-native evolution featuring a ground-up architecture rewrite, TutorBot, and flexible mode switching under the Apache-2.0 license. A new chapter begins, and our story continues!
> **[2026.2.6]** 🚀 We've reached 10k stars in just 39 days! A huge thank you to our incredible community for the support!

View File

@@ -0,0 +1,82 @@
# DeepTutor v1.2.2 Release Notes
**Release Date:** 2026.04.22
## Highlights
### User-Authored Skills System
Introduced a full **Skills** subsystem that lets users create, edit, and activate custom `SKILL.md` files from the web UI. Each skill lives under `data/user/workspace/skills/<name>/SKILL.md` with YAML frontmatter (`name`, `description`, optional `triggers`) and a Markdown body that is injected verbatim into the chat system prompt when active.
- **Backend** — `SkillService` (`deeptutor/services/skill/service.py`) provides CRUD + listing + selection with strict name validation (`^[a-z0-9][a-z0-9-]{0,63}$`), frontmatter parsing, and directory-level isolation. REST API mounted at `/api/v1/skills` with `GET /list`, `GET /{name}`, `POST /create`, `PUT /{name}`, `DELETE /{name}`.
- **Frontend** — a new **Skills** tab in the Knowledge management page (`web/app/(utility)/knowledge/page.tsx`) with inline SKILL.md editor, and a skill picker menu in the chat composer. Skills can be toggled individually or set to **auto** mode (sends `["auto"]` to the backend). `web/lib/skills-api.ts` provides a cached client-side API layer. `UnifiedChatContext` carries `skills` through the WebSocket payload.
### Chat Input Performance Overhaul (#351, #360, #362)
Eliminated input lag in long conversations through deep state colocation:
- **`ComposerInput`** — extracted from `ChatComposer` into its own `memo`'d component so frequent keystroke re-renders are isolated from the rest of the composer (capability panels, reference chips, tool menus). Exposes an imperative `ComposerInputHandle` (`clear()`, `getValue()`) to avoid lifting input state.
- **`SimpleComposerInput`** — a lightweight variant for the TutorBot chat page that strips @-mention and capability overhead entirely, fixing residual lag reported after the initial refactor.
- **`React.memo` on config panels** — `QuizConfigPanel`, `MathAnimatorConfigPanel`, `ResearchConfigPanel`, and `VisualizeConfigPanel` are now wrapped in `React.memo`; parent callbacks in `ChatPage` stabilized with `useCallback`.
- **@-mention helpers exported** — `shouldOpenAtPopup` and `stripTrailingAtMention` moved to `ComposerInput.tsx` as named exports for cross-component reuse.
### Auto-Fallback for `response_format` Rejection
Extended the v1.2.1 static `supports_response_format` guard with a **runtime auto-recovery** path. When a provider unexpectedly returns HTTP 400 for `response_format={"type":"json_object"}` (common with LM Studio + Gemma/Qwen-style models), both LLM execution paths now detect the error, drop the field, and retry once:
- **aiohttp path** (`cloud_provider.py`) — `_looks_like_unsupported_response_format` heuristic detects the rejection in `_openai_complete` and `_openai_stream`; on match, the request is retried without `response_format` and the (binding, model) pair is cached.
- **OpenAI SDK path** (`executors.py`) — `_create_with_format_fallback` wraps `client.chat.completions.create`, catching `BadRequestError` and applying the same retry + cache logic.
- **Runtime cache** (`capabilities.py`) — `disable_response_format_at_runtime` / `is_response_format_disabled_at_runtime` record discovered incompatibilities in a module-level `set` so subsequent calls skip `response_format` upfront without paying the retry cost.
- **`_answer_now.py`** — `stream_synthesis` now checks `supports_response_format` before attaching `response_format`, preventing the 400 in the first place for fast-path answer flows.
### LAN / Remote Access Fix (#340)
When another machine on the local network opens the web UI, the build-time `NEXT_PUBLIC_API_BASE` (typically `http://localhost:8001`) would resolve to the remote browser's own loopback instead of the server. A new `resolveBase()` helper in `web/lib/api.ts` detects this mismatch and swaps the hostname for `window.location.hostname` at runtime, so `apiUrl()` and `wsUrl()` reach the correct backend regardless of which machine opened the page.
### Sidebar Version Badge & GitHub Link
The sidebar now displays the current build version alongside a status indicator:
- **`/api/version` route** — a Next.js ISR endpoint that queries `api.github.com/repos/HKUDS/DeepTutor/releases/latest` (hourly revalidation, optional `GITHUB_TOKEN` for rate-limit headroom) and returns the latest tag, name, URL, and publish date.
- **`VersionBadge`** — compares `NEXT_PUBLIC_APP_VERSION` (injected at build time via `next.config.js` / `git describe --tags`) against the fetched latest release. Shows a green dot when up-to-date, amber when outdated, and neutral when unknown. Clicking navigates to the release page.
- **`Dockerfile`** — new `APP_VERSION` build arg piped into the Next.js env so Docker-based deployments also get accurate version display.
- **GitHub icon** — a direct link to the repository added to both collapsed and expanded sidebar states.
### Deep Solve Image Attachment Support
`DeepSolveCapability` now extracts the first image attachment (data-URI or URL) from `context.attachments` via a new `_first_image_url` helper and passes it to the planner and solver agents. Internally, `PlannerAgent` and `SolverAgent` were refactored to use the `Attachment` dataclass through `BaseAgent`'s unified multimodal pipeline instead of manually constructing multimodal message arrays — removing two identical `_build_multimodal_messages` helper functions. `BaseAgent.stream_llm` also gained logic to construct messages from `system_prompt` + `user_prompt` when `attachments` are provided without explicit `messages`, and logs when images are stripped for non-vision models.
### Agentic Chat Pipeline Attachment Passthrough
The `_stage_responding` and `_stage_acting` methods in `AgenticChatPipeline` now call `_prepare_messages_with_attachments` after building messages, ensuring that user-uploaded images are forwarded to the LLM in every chat stage — not just the initial thinking stage.
### TutorBot WebSocket Resilience (#354)
Hardened the `/api/v1/tutorbot/{bot_id}/ws` endpoint:
- **Auto-start** — if the bot is configured but not running when a WebSocket connects, the endpoint now calls `mgr.start_bot()` automatically instead of immediately closing with 4004. Unknown bot IDs still receive a JSON error payload before close.
- **`_safe_send` wrapper** — all `ws.send_json` calls go through a helper that catches `WebSocketDisconnect` / `RuntimeError`, preventing unhandled exceptions when the client drops mid-stream.
- **Graceful disconnect** — `_handle_user_messages` catches `WebSocketDisconnect` on `receive_text` and breaks cleanly.
### Settings Page: API Key Masking (#355)
The API Key field on the Settings page is now rendered as `type="password"` by default with an Eye / EyeOff toggle button. The visibility state resets when switching between services or profiles.
### Book Library UI Overhaul
Replaced the minimal "Select a book" placeholder with a full **BookLibrary** component (`web/app/(workspace)/book/components/BookLibrary.tsx`) featuring search, status-filtered cards with chapter/page counts, creation and deletion actions, and status badges (Draft / Outline / Compiling / Ready). `BookSidebar` was simplified to a single-book reader view with a "← All books" back button, and the book page now conditionally shows either the library or the sidebar based on the current view.
### Visualization Fullscreen Mode
SVG, Mermaid, and ChartJS visualizations now have a **Maximize** button (top-right) that opens the graphic in a fullscreen overlay with Escape-to-close. HTML iframe visualizations are excluded since they already provide their own "Open in new tab" affordance.
### Bug Fixes
- **Embedding adapter `ConnectError` not retried (#353)** — added `httpx.ConnectError` to the retry exception tuple in `OpenAICompatibleEmbeddingAdapter`, so transient connection failures during embedding are retried with exponential backoff instead of raising immediately.
- **RAG `None`-embedding hardening** — `CustomEmbedding._aget_query_embedding` and `_aget_text_embedding` now raise a clear `ValueError` when the provider returns `None` instead of crashing later in similarity computation. The batch method `_aget_text_embeddings` now determines the fallback zero-vector dimension from sibling vectors or the configured `dim`, and raises if neither is available (preventing silent persistence of zero-length vectors).
- **KB delete crash on missing directory** — `KnowledgeBaseManager.delete_knowledge_base` now resolves the path directly via `self.base_dir / name` and handles the case where the on-disk folder was already removed, cleaning up the orphaned `kb_config.json` entry instead of raising `FileNotFoundError`.
- **CLI `parse_json_object` whitespace** — the function now strips leading/trailing whitespace before parsing, so trailing newlines from shell piping no longer cause `json.JSONDecodeError`.
### Test Suite Expansion
- **TutorBot WebSocket** — 2 new tests covering auto-start of stopped-but-configured bots and JSON error payload for unknown bot IDs (`tests/api/test_tutorbot_router.py`).
- **CLI helpers** — 2 tests for `parse_json_object` whitespace handling and invalid JSON (`tests/cli/test_common.py`).
- **Route params** — 3 tests for the new `firstParam` utility (`web/tests/route-params.test.ts`).
- **API resolve base** — tests for the LAN hostname swap logic (`web/tests/api-resolve-base.test.ts`).
## Community Contributions
- **@StarNight2021** — Decouple chat input state to resolve lag in long conversations (#351, #360, #362)
- **@StarNight2021** — Fix LAN access: replace localhost with browser hostname at runtime (#340)
- **@StarNight2021** — TutorBot WebSocket resilience and CLI config parsing edge case (#354)
- **@StarNight2021** — Hide the API key on settings page (#355)
- **@StarNight2021** — Add `ConnectError` to embedding retry exceptions (#353)
**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.2.1...v1.2.2

View File

@@ -564,11 +564,22 @@ class BaseAgent(ABC):
self.logger.debug(f"response_format not supported for {binding}/{model}, skipping")
# Inject image attachments into messages when provided
if messages and attachments:
if attachments:
if not messages:
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
mm_result = prepare_multimodal_messages(
messages, attachments, binding=self.binding, model=model
)
messages = mm_result.messages
if mm_result.images_stripped:
self.logger.info(
"Images stripped for %s/%s – model does not support vision",
self.binding,
model,
)
# Log input
stage_label = stage or self.agent_name

View File

@@ -433,6 +433,7 @@ class AgenticChatPipeline:
system_prompt=self._responding_system_prompt(enabled_tools),
user_content=user_prompt,
)
messages, _ = self._prepare_messages_with_attachments(messages, context)
chunks: list[str] = []
async for chunk in self._stream_messages(
@@ -582,6 +583,7 @@ class AgenticChatPipeline:
system_prompt=self._acting_system_prompt(enabled_tools, context),
user_content=self._acting_user_prompt(context, thinking_text),
)
messages, _ = self._prepare_messages_with_attachments(messages, context)
tool_traces: list[ToolTrace] = []
client = self._build_openai_client()
trace_meta = build_trace_metadata(

View File

@@ -14,6 +14,7 @@ import logging
from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.context import Attachment
from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id
from deeptutor.utils.json_parser import parse_json_response
@@ -28,24 +29,6 @@ _MAX_AGGREGATE_INPUT_CHARS = 6000
_NUM_QUERIES = 3
def _build_multimodal_messages(
system_prompt: str,
user_prompt: str,
image_url: str,
) -> list[dict[str, Any]]:
"""Build OpenAI-compatible multimodal messages with an image."""
return [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_url}},
],
},
]
class PlannerAgent(BaseAgent):
"""Generates a high-level solving plan from the user question."""
@@ -132,9 +115,7 @@ class PlannerAgent(BaseAgent):
}
if image_url:
llm_kwargs["messages"] = _build_multimodal_messages(
system_prompt, user_prompt, image_url,
)
llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]
chunks: list[str] = []
async for chunk in self.stream_llm(**llm_kwargs):

View File

@@ -14,6 +14,7 @@ from __future__ import annotations
from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.context import Attachment
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..memory.scratchpad import PlanStep, Scratchpad
@@ -21,24 +22,6 @@ from ..tool_runtime import SolveToolRuntime
from ..utils.json_utils import extract_json_from_text
def _build_multimodal_messages(
system_prompt: str,
user_prompt: str,
image_url: str,
) -> list[dict[str, Any]]:
"""Build OpenAI-compatible multimodal messages with an image."""
return [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{"type": "image_url", "image_url": {"url": image_url}},
],
},
]
class SolverAgent(BaseAgent):
"""ReAct reasoning agent — one LLM call per iteration."""
@@ -123,9 +106,7 @@ class SolverAgent(BaseAgent):
}
if image_url:
llm_kwargs["messages"] = _build_multimodal_messages(
system_prompt, user_prompt, image_url,
)
llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]
chunks: list[str] = []
async for chunk in self.stream_llm(**llm_kwargs):

View File

@@ -4,6 +4,7 @@ TutorBot management API.
from __future__ import annotations
import asyncio
import json
import logging
@@ -21,6 +22,24 @@ logger = logging.getLogger(__name__)
router = APIRouter()
# Per-bot async locks used to dedupe concurrent WebSocket-driven auto-starts.
# `manager.start_bot` already short-circuits when the bot is already running,
# but that check is not async-safe: two coroutines that both observe a stopped
# bot will each run the full start sequence. Serializing on a per-bot lock
# avoids the duplicated work and noisy logs.
_start_locks: dict[str, asyncio.Lock] = {}
_start_locks_mutex = asyncio.Lock()
async def _get_start_lock(bot_id: str) -> asyncio.Lock:
async with _start_locks_mutex:
lock = _start_locks.get(bot_id)
if lock is None:
lock = asyncio.Lock()
_start_locks[bot_id] = lock
return lock
class CreateBotRequest(BaseModel):
bot_id: str
name: str | None = None
@@ -327,24 +346,60 @@ async def get_bot_history(bot_id: str, limit: int = 100):
@router.websocket("/{bot_id}/ws")
async def bot_chat_ws(ws: WebSocket, bot_id: str):
import asyncio
# `disconnected` is the single source of truth for "client is gone".
# Both task loops watch it so they can exit cooperatively without
# raising exceptions back into manager code (which has broad
# `except Exception:` handlers that would swallow them).
disconnected = asyncio.Event()
async def _safe_send(payload: dict) -> bool:
try:
await ws.send_json(payload)
return True
except (WebSocketDisconnect, RuntimeError):
disconnected.set()
return False
mgr = get_tutorbot_manager()
instance = mgr.get_bot(bot_id)
if not instance or not instance.running:
await ws.close(code=4004, reason="Bot not found or not running")
return
await ws.accept()
if not instance or not instance.running:
config = mgr.load_bot_config(bot_id)
if config is None:
await _safe_send({"type": "error", "content": "Bot not found"})
await ws.close(code=4004, reason="Bot not found")
return
# Serialize concurrent starts of the same bot so only one
# WebSocket connection actually triggers `start_bot`; the rest
# observe the now-running instance and reuse it.
lock = await _get_start_lock(bot_id)
async with lock:
instance = mgr.get_bot(bot_id)
if not instance or not instance.running:
try:
instance = await mgr.start_bot(bot_id, config)
except Exception:
logger.exception("Failed to auto-start bot '%s' for websocket", bot_id)
await _safe_send({"type": "error", "content": "Failed to start bot"})
await ws.close(code=1011, reason="Failed to start bot")
return
logger.info("WebSocket connected for bot '%s'", bot_id)
async def _handle_user_messages():
while True:
raw = await ws.receive_text()
while not disconnected.is_set():
try:
raw = await ws.receive_text()
except WebSocketDisconnect:
disconnected.set()
break
try:
data = json.loads(raw)
except json.JSONDecodeError:
await ws.send_json({"type": "error", "content": "Invalid JSON"})
if not await _safe_send({"type": "error", "content": "Invalid JSON"}):
break
continue
content = data.get("content", "").strip()
@@ -352,27 +407,49 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
continue
async def on_progress(text: str) -> None:
await ws.send_json({"type": "thinking", "content": text})
# Best-effort: never raise. If the client is gone, just stop
# forwarding progress; the surrounding loop will notice the
# `disconnected` event and exit. Raising here would leak
# WebSocketDisconnect into `mgr.send_message`, which catches
# `Exception` broadly and would swallow the disconnect signal,
# leaving the bot to finish an expensive turn for nobody.
await _safe_send({"type": "thinking", "content": text})
try:
response = await mgr.send_message(
bot_id, content, chat_id=data.get("chat_id", "web"),
on_progress=on_progress,
)
await ws.send_json({"type": "content", "content": response})
await ws.send_json({"type": "done"})
if not await _safe_send({"type": "content", "content": response}):
break
if not await _safe_send({"type": "done"}):
break
except RuntimeError as exc:
await ws.send_json({"type": "error", "content": str(exc)})
if not await _safe_send({"type": "error", "content": str(exc)}):
break
except WebSocketDisconnect:
disconnected.set()
break
except Exception:
logger.exception("Error processing message for bot '%s'", bot_id)
await ws.send_json({"type": "error", "content": "Internal error"})
if not await _safe_send({"type": "error", "content": "Internal error"}):
break
async def _handle_notifications():
while True:
content = await instance.notify_queue.get()
try:
await ws.send_json({"type": "proactive", "content": content})
except Exception:
# Race the queue read against the disconnect signal so this loop
# cooperates with client disconnects detected by the other task.
while not disconnected.is_set():
get_task = asyncio.create_task(instance.notify_queue.get())
wait_task = asyncio.create_task(disconnected.wait())
done, pending = await asyncio.wait(
{get_task, wait_task}, return_when=asyncio.FIRST_COMPLETED,
)
for t in pending:
t.cancel()
if get_task not in done:
break
content = get_task.result()
if not await _safe_send({"type": "proactive", "content": content}):
break
user_task = asyncio.create_task(_handle_user_messages())
@@ -381,12 +458,14 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
done, pending = await asyncio.wait(
[user_task, notify_task], return_when=asyncio.FIRST_COMPLETED,
)
disconnected.set()
for t in pending:
t.cancel()
for t in done:
if t.exception() and not isinstance(t.exception(), WebSocketDisconnect):
logger.exception("WebSocket task error for bot '%s'", bot_id, exc_info=t.exception())
except Exception:
disconnected.set()
user_task.cancel()
notify_task.cancel()
logger.info("WebSocket closed for bot '%s'", bot_id)

View File

@@ -36,6 +36,7 @@ from deeptutor.services.llm import (
get_llm_config,
get_token_limit_kwargs,
stream as llm_stream,
supports_response_format,
)
from deeptutor.services.prompt.manager import get_prompt_manager
@@ -198,7 +199,9 @@ async def stream_synthesis(
if model:
extra_kwargs.update(get_token_limit_kwargs(model, max_tokens))
if response_format is not None:
extra_kwargs["response_format"] = response_format
binding = getattr(llm_config, "binding", None) or "openai"
if supports_response_format(binding, model):
extra_kwargs["response_format"] = response_format
chunks: list[str] = []
try:

View File

@@ -18,6 +18,20 @@ from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import derive_trace_metadata, merge_trace_metadata
def _first_image_url(attachments: list[Any]) -> str | None:
"""Extract a data-URI or URL from the first image attachment, if any."""
for att in attachments or []:
if getattr(att, "type", "") != "image":
continue
if getattr(att, "url", ""):
return att.url
b64 = getattr(att, "base64", "")
if b64:
mime = getattr(att, "mime_type", "") or "image/png"
return f"data:{mime};base64,{b64}"
return None
class DeepSolveCapability(BaseCapability):
manifest = CapabilityManifest(
name="deep_solve",
@@ -266,8 +280,11 @@ class DeepSolveCapability(BaseCapability):
solver._content_callback = _content_sink
image_url = _first_image_url(context.attachments)
result = await solver.solve(
question=context.user_message,
image_url=image_url,
verbose=False,
detailed=detailed,
conversation_context=str(

View File

@@ -166,18 +166,25 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
response.raise_for_status()
data = response.json()
break
except (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.PoolTimeout) as exc:
except httpx.TransportError as exc:
# httpx.TransportError covers all transient transport-layer
# failures: ConnectError, ReadError, WriteError, ConnectTimeout,
# ReadTimeout, WriteTimeout, PoolTimeout, RemoteProtocolError, etc.
# Retrying any of these with backoff is safe and obviates the
# need to keep extending an explicit allow-list.
last_exc = exc
if attempt < self._MAX_RETRIES:
wait = self._RETRY_BACKOFF * (2 ** attempt)
logger.warning(
f"Embedding request timeout (attempt {attempt + 1}/{1 + self._MAX_RETRIES}), "
f"Embedding request transport error ({type(exc).__name__}: {exc}) "
f"on attempt {attempt + 1}/{1 + self._MAX_RETRIES}, "
f"retrying in {wait:.1f}s..."
)
await asyncio.sleep(wait)
else:
logger.error(
f"Embedding request failed after {1 + self._MAX_RETRIES} attempts: {exc}"
f"Embedding request failed after {1 + self._MAX_RETRIES} attempts "
f"({type(exc).__name__}: {exc})"
)
raise
else:

View File

@@ -27,10 +27,11 @@ def parse_config_items(items: list[str]) -> dict[str, Any]:
def parse_json_object(raw: str | None) -> dict[str, Any]:
if not raw:
normalized = (raw or "").strip()
if not normalized:
return {}
try:
value = json.loads(raw)
value = json.loads(normalized)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON config: {exc.msg}") from exc
if not isinstance(value, dict):

View File

@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import importlib
from typing import Any
from unittest.mock import MagicMock
@@ -461,3 +462,183 @@ class TestPatchBotStoppedAndRunning:
detail = resp.json()["detail"]
assert "RuntimeError" in detail
assert "stopping and starting" in detail.lower()
class TestBotChatWebSocketStartup:
"""WebSocket endpoint should auto-start stopped configured bots."""
def test_ws_autostarts_stopped_bot(self, monkeypatch):
from deeptutor.services.tutorbot.manager import BotConfig
class FakeInstance:
running = True
def __init__(self):
self.notify_queue = asyncio.Queue()
class FakeMgr:
def __init__(self):
self.started: list[str] = []
def get_bot(self, bot_id: str):
return None
def load_bot_config(self, bot_id: str):
return BotConfig(name=bot_id)
async def start_bot(self, bot_id: str, config: BotConfig):
self.started.append(bot_id)
return FakeInstance()
mgr = FakeMgr()
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: mgr)
app = FastAPI()
app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
client = TestClient(app)
with client.websocket_connect("/api/v1/tutorbot/ielts-tutor/ws") as ws:
ws.close()
assert mgr.started == ["ielts-tutor"]
def test_ws_unknown_bot_returns_error_payload(self, monkeypatch):
class FakeMgr:
def get_bot(self, bot_id: str):
return None
def load_bot_config(self, bot_id: str):
return None
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())
app = FastAPI()
app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
client = TestClient(app)
with client.websocket_connect("/api/v1/tutorbot/missing/ws") as ws:
payload = ws.receive_json()
assert payload["type"] == "error"
assert "not found" in payload["content"].lower()
def test_ws_reuses_running_bot_on_reconnect(self, monkeypatch):
"""A second WS connect must not re-trigger start_bot if bot is running."""
from deeptutor.services.tutorbot.manager import BotConfig
class FakeInstance:
running = True
def __init__(self):
self.notify_queue = asyncio.Queue()
class FakeMgr:
def __init__(self):
self.start_calls = 0
self._instance: FakeInstance | None = None
def get_bot(self, bot_id: str):
return self._instance
def load_bot_config(self, bot_id: str):
return BotConfig(name=bot_id)
async def start_bot(self, bot_id: str, config: BotConfig):
self.start_calls += 1
self._instance = FakeInstance()
return self._instance
mgr = FakeMgr()
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: mgr)
# Ensure no leftover lock from a prior test affects this one.
tutorbot_router_mod._start_locks.clear()
app = FastAPI()
app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
client = TestClient(app)
with client.websocket_connect("/api/v1/tutorbot/dedup-bot/ws") as ws:
ws.close()
with client.websocket_connect("/api/v1/tutorbot/dedup-bot/ws") as ws:
ws.close()
assert mgr.start_calls == 1
class TestStartLockDedup:
"""Direct test that the per-bot start lock serializes concurrent starts."""
def test_get_start_lock_serializes_concurrent_blocks(self):
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
tutorbot_router_mod._start_locks.clear()
async def runner():
in_critical = 0
max_in_critical = 0
start_calls = 0
async def fake_start():
nonlocal in_critical, max_in_critical, start_calls
lock = await tutorbot_router_mod._get_start_lock("concurrent-bot")
async with lock:
in_critical += 1
max_in_critical = max(max_in_critical, in_critical)
await asyncio.sleep(0.02)
start_calls += 1
in_critical -= 1
await asyncio.gather(fake_start(), fake_start(), fake_start())
return start_calls, max_in_critical
start_calls, max_in_critical = asyncio.run(runner())
assert start_calls == 3
assert max_in_critical == 1
class TestBotChatWebSocketResilience:
"""The WS handler must tolerate client disconnects during a turn."""
def test_ws_loop_breaks_on_client_disconnect_before_message(self, monkeypatch):
from deeptutor.services.tutorbot.manager import BotConfig
class FakeInstance:
running = True
def __init__(self):
self.notify_queue = asyncio.Queue()
class FakeMgr:
def __init__(self):
self.send_calls = 0
def get_bot(self, bot_id: str):
return FakeInstance()
def load_bot_config(self, bot_id: str):
return BotConfig(name=bot_id)
async def start_bot(self, bot_id: str, config: BotConfig):
return FakeInstance()
async def send_message(self, *args, **kwargs):
self.send_calls += 1
return "should not be reached"
mgr = FakeMgr()
tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")
monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: mgr)
tutorbot_router_mod._start_locks.clear()
app = FastAPI()
app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")
client = TestClient(app)
# Open and immediately close without sending any payload. Both task
# loops should observe the disconnect and exit cleanly without a
# background task error.
with client.websocket_connect("/api/v1/tutorbot/d-bot/ws") as ws:
ws.close()
assert mgr.send_calls == 0

16
tests/cli/test_common.py Normal file
View File

@@ -0,0 +1,16 @@
"""Unit tests for shared CLI helpers."""
from __future__ import annotations
import pytest
from deeptutor_cli.common import parse_json_object
def test_parse_json_object_whitespace_is_empty_dict() -> None:
assert parse_json_object(" ") == {}
def test_parse_json_object_invalid_json_still_errors() -> None:
with pytest.raises(ValueError, match="Invalid JSON config"):
parse_json_object("{")

View File

@@ -9,6 +9,8 @@ import {
ChevronDown,
ChevronRight,
Database,
Eye,
EyeOff,
Loader2,
Plus,
Rocket,
@@ -376,6 +378,7 @@ function SettingsPageContent() {
const [testRunning, setTestRunning] = useState<ServiceName | null>(null);
const [saving, setSaving] = useState(false);
const [applying, setApplying] = useState(false);
const [showApiKey, setShowApiKey] = useState(false);
const [toast, setToast] = useState<string>("");
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [providers, setProviders] = useState<Record<ServiceName, ProviderOption[]>>({ llm: [], embedding: [], search: [] });
@@ -458,6 +461,10 @@ function SettingsPageContent() {
searchProviderRaw === "perplexity" &&
!String(activeProfile?.api_key || "").trim();
useEffect(() => {
setShowApiKey(false);
}, [activeService, activeProfile?.id]);
// -- UI preference helpers ----------------------------------------------
const persistUi = async (nextTheme: "light" | "dark" | "glass" | "snow", nextLanguage: "en" | "zh") => {
@@ -1081,12 +1088,26 @@ function SettingsPageContent() {
</div>
<div className="sm:col-span-2">
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Key")}</div>
<input
className={inputClass}
value={activeProfile.api_key}
onChange={(e) => updateProfileField("api_key", e.target.value)}
placeholder="sk-..."
/>
<div className="relative">
<input
type={showApiKey ? "text" : "password"}
autoComplete="new-password"
spellCheck={false}
className={`${inputClass} pr-10 font-mono`}
value={activeProfile.api_key}
onChange={(e) => updateProfileField("api_key", e.target.value)}
placeholder="sk-..."
/>
<button
type="button"
onClick={() => setShowApiKey((prev) => !prev)}
className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
aria-label={showApiKey ? t("Hide API key") : t("Show API key")}
title={showApiKey ? t("Hide API key") : t("Show API key")}
>
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{t("API Version")}</div>

View File

@@ -5,7 +5,9 @@ import { useParams, useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { ArrowLeft, Bot, Loader2, Send } from "lucide-react";
import { apiUrl, wsUrl } from "@/lib/api";
import { firstParam } from "@/lib/route-params";
import AssistantResponse from "@/components/common/AssistantResponse";
import { SimpleComposerInput } from "@/components/chat/home/SimpleComposerInput";
interface BotInfo {
bot_id: string;
@@ -20,13 +22,13 @@ interface ChatMsg {
}
export default function BotChatPage() {
const { botId } = useParams<{ botId: string }>();
const params = useParams<{ botId?: string | string[] }>();
const botId = firstParam(params?.botId);
const router = useRouter();
const { t } = useTranslation();
const [bot, setBot] = useState<BotInfo | null>(null);
const [messages, setMessages] = useState<ChatMsg[]>([]);
const [input, setInput] = useState("");
const [streaming, setStreaming] = useState(false);
const [thinking, setThinking] = useState<string[]>([]);
const thinkingRef = useRef<string[]>([]);
@@ -42,6 +44,9 @@ export default function BotChatPage() {
}, []);
useEffect(() => {
if (!botId) {
return;
}
fetch(apiUrl(`/api/v1/tutorbot/${botId}`))
.then((r) => (r.ok ? r.json() : null))
.then(setBot)
@@ -59,6 +64,9 @@ export default function BotChatPage() {
}, [botId]);
useEffect(() => {
if (!botId) {
return;
}
const ws = new WebSocket(wsUrl(`/api/v1/tutorbot/${botId}/ws`));
wsRef.current = ws;
@@ -101,27 +109,23 @@ export default function BotChatPage() {
};
}, [botId, scrollToBottom]);
const send = useCallback(() => {
const text = input.trim();
if (!text || streaming || !wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
const handleSend = useCallback((content: string) => {
if (!botId || streaming || !wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
setMessages((msgs) => [...msgs, { role: "user", content: text }]);
setInput("");
setMessages((msgs) => [...msgs, { role: "user", content }]);
setStreaming(true);
setThinking([]);
wsRef.current.send(JSON.stringify({ content: text }));
wsRef.current.send(JSON.stringify({ content }));
scrollToBottom();
}, [input, streaming, scrollToBottom]);
}, [botId, streaming, scrollToBottom]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
}
},
[send],
);
const handleManualSend = useCallback(() => {
const content = inputRef.current?.value.trim();
if (content) {
handleSend(content);
if (inputRef.current) inputRef.current.value = "";
}
}, [handleSend]);
return (
<div className="flex h-full flex-col">
@@ -207,25 +211,21 @@ export default function BotChatPage() {
{/* Input */}
<div className="border-t border-[var(--border)] px-5 py-3">
<div className="mx-auto flex max-w-[720px] items-end gap-2">
<textarea
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={t("Type a message...")}
rows={1}
<SimpleComposerInput
textareaRef={inputRef}
onSend={handleSend}
disabled={streaming}
className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"
/>
<button
onClick={send}
disabled={streaming || !input.trim()}
onClick={handleManualSend}
disabled={streaming}
className="flex h-[42px] w-[42px] items-center justify-center rounded-xl bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-30"
>
<Send className="h-4 w-4" />
</button>
</div>
</div>
</div>
);
}

View File

@@ -666,6 +666,18 @@ export default function ChatPage() {
const handleRemoveQuestion = useCallback((entryId: number) => {
setSelectedQuestionEntries((prev) => prev.filter((entry) => entry.id !== entryId));
}, []);
const handleToggleSkill = useCallback((name: string) => {
setSkillsAutoMode(false);
setSelectedSkills((prev) =>
prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],
);
}, []);
const handleSetSkillsAuto = useCallback((auto: boolean) => {
setSkillsAutoMode(auto);
if (auto) setSelectedSkills([]);
}, []);
const handleTogglePanelCollapsed = useCallback(() => { setPanelCollapsed((prev) => !prev); }, []);
const handleCloseNotebookPicker = useCallback(() => { setShowNotebookPicker(false); }, []);
const handleApplyNotebookRecords = useCallback((records: SelectedRecord[]) => { setSelectedNotebookRecords(records); }, []);
@@ -800,16 +812,8 @@ export default function ChatPage() {
onSelectHistoryPicker={handleSelectHistoryPicker}
onSelectQuestionBankPicker={handleSelectQuestionBankPicker}
onToggleTool={toggleTool}
onToggleSkill={(name) => {
setSkillsAutoMode(false);
setSelectedSkills((prev) =>
prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],
);
}}
onSetSkillsAuto={(auto) => {
setSkillsAutoMode(auto);
if (auto) setSelectedSkills([]);
}}
onToggleSkill={handleToggleSkill}
onSetSkillsAuto={handleSetSkillsAuto}
onToggleResearchSource={toggleResearchSource}
onSend={handleSend}
onRemoveAttachment={removeAttachment}

View File

@@ -0,0 +1,85 @@
import { NextResponse } from "next/server";
/**
* Returns the latest GitHub release for the project, used by the sidebar
* version badge. The response is cached on the server side (ISR) so that
* each visit doesn't hit GitHub directly — at most one upstream request
* per `revalidate` window across all clients.
*/
// Refresh at most once per hour. Tune via env if needed.
export const revalidate = 3600;
const DEFAULT_REPO = "HKUDS/DeepTutor";
interface GithubRelease {
tag_name: string;
html_url: string;
name: string | null;
published_at: string | null;
prerelease: boolean;
draft: boolean;
}
interface VersionPayload {
tag: string | null;
name: string | null;
url: string | null;
publishedAt: string | null;
source: "github" | "fallback";
}
const FALLBACK: VersionPayload = {
tag: null,
name: null,
url: `https://github.com/${DEFAULT_REPO}/releases`,
publishedAt: null,
source: "fallback",
};
export async function GET() {
const repo = process.env.NEXT_PUBLIC_GITHUB_REPO || DEFAULT_REPO;
const url = `https://api.github.com/repos/${repo}/releases/latest`;
const headers: Record<string, string> = {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "deeptutor-web",
};
if (process.env.GITHUB_TOKEN) {
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
}
try {
const res = await fetch(url, {
headers,
next: { revalidate },
});
if (!res.ok) {
return NextResponse.json(
{ ...FALLBACK, url: `https://github.com/${repo}/releases` },
{ status: 200 },
);
}
const data = (await res.json()) as GithubRelease;
const payload: VersionPayload = {
tag: data.tag_name ?? null,
name: data.name ?? null,
url: data.html_url ?? `https://github.com/${repo}/releases`,
publishedAt: data.published_at ?? null,
source: "github",
};
return NextResponse.json(payload, {
status: 200,
headers: {
// Browser-side cache hint; server-side caching already handled by ISR.
"Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
},
});
} catch {
return NextResponse.json(
{ ...FALLBACK, url: `https://github.com/${repo}/releases` },
{ status: 200 },
);
}
}

View File

@@ -1,5 +1,6 @@
"use client";
import { memo } from "react";
import { useTranslation } from "react-i18next";
interface AtMentionPopupProps {
@@ -9,7 +10,7 @@ interface AtMentionPopupProps {
onSelectQuestionBank: () => void;
}
export default function AtMentionPopup({
export default memo(function AtMentionPopup({
open,
onSelectNotebook,
onSelectHistory,
@@ -41,4 +42,4 @@ export default function AtMentionPopup({
</button>
</div>
);
}
});

View File

@@ -22,13 +22,13 @@ import {
import { useTranslation } from "react-i18next";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
import AtMentionPopup from "@/components/chat/AtMentionPopup";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { DeepQuestionFormConfig } from "@/lib/quiz-types";
import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";
import type { VisualizeFormConfig } from "@/lib/visualize-types";
import type { DeepResearchFormConfig, ResearchSource } from "@/lib/research-types";
import { ReferenceChips } from "./ChatMessages";
import { ComposerInput, type ComposerInputHandle } from "./ComposerInput";
const QuizConfigPanel = dynamic(() => import("@/components/quiz/QuizConfigPanel"), {
ssr: false,
@@ -77,15 +77,6 @@ interface ResearchSourceDef {
icon: LucideIcon;
}
function shouldOpenAtPopup(value: string, cursorPos: number): boolean {
const prefix = value.slice(0, cursorPos);
return /(^|\s)@[^\s]*$/.test(prefix);
}
function stripTrailingAtMention(value: string): string {
return value.replace(/(^|\s)@[^\s]*$/, "$1").replace(/\s+$/, "");
}
export default memo(function ChatComposer({
composerRef,
capMenuRef,
@@ -240,9 +231,9 @@ export default memo(function ChatComposer({
const { t } = useTranslation();
const CapIcon = activeCap.icon;
const [input, setInput] = useState("");
const [showAtPopup, setShowAtPopup] = useState(false);
const [hasContent, setHasContent] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const inputHandleRef = useRef<ComposerInputHandle>(null);
const activeCapabilityKey = activeCap.value || "chat";
@@ -250,71 +241,37 @@ export default memo(function ChatComposer({
if (!hasMessages) textareaRef.current?.focus();
}, [hasMessages]);
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "28px";
const next = Math.max(el.scrollHeight, 28);
const bounded = Math.min(next, 200);
el.style.height = `${bounded}px`;
el.style.overflowY = next > 200 ? "auto" : "hidden";
}, [input, activeCapabilityKey]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
const cursorPos = e.target.selectionStart ?? value.length;
setInput(value);
setShowAtPopup(shouldOpenAtPopup(value, cursorPos));
// Functional-update form keeps `handleInputChange` identity stable across
// every keystroke (no `hasContent` in deps), so the memoized ComposerInput
// doesn't get re-rendered just because we observed a content-empty toggle.
const handleInputChange = useCallback((val: string) => {
const next = !!val.trim();
setHasContent((prev) => (prev === next ? prev : next));
}, []);
const handleTextareaClick = useCallback((e: React.MouseEvent<HTMLTextAreaElement>) => {
const target = e.currentTarget;
setShowAtPopup(shouldOpenAtPopup(target.value, target.selectionStart ?? target.value.length));
}, []);
const doSend = useCallback(() => {
const content = input.trim();
const doSend = useCallback((content: string) => {
onSend(content);
setInput("");
setShowAtPopup(false);
}, [input, onSend]);
setHasContent(false);
inputHandleRef.current?.clear();
}, [onSend]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
doSend();
} else if (e.key === "Escape") {
setShowAtPopup(false);
}
}, [doSend]);
const handleSelectNotebook = useCallback(() => {
setInput((prev) => stripTrailingAtMention(prev));
setShowAtPopup(false);
onSelectNotebookPicker();
}, [onSelectNotebookPicker]);
const handleSelectHistory = useCallback(() => {
setInput((prev) => stripTrailingAtMention(prev));
setShowAtPopup(false);
onSelectHistoryPicker();
}, [onSelectHistoryPicker]);
const handleSelectQuestionBank = useCallback(() => {
setInput((prev) => stripTrailingAtMention(prev));
setShowAtPopup(false);
onSelectQuestionBankPicker();
}, [onSelectQuestionBankPicker]);
const hasReferences =
!!attachments.length ||
!!selectedNotebookRecords.length ||
!!selectedHistorySessions.length ||
!!selectedQuestionEntries.length;
const canSend =
(!!input.trim() ||
!!attachments.length ||
!!selectedNotebookRecords.length ||
!!selectedHistorySessions.length ||
!!selectedQuestionEntries.length) &&
(hasContent || hasReferences) &&
!isStreaming &&
!(isResearchMode && Object.keys(researchValidationErrors).length > 0);
const handleManualSend = useCallback(() => {
if (!canSend) return;
const content = inputHandleRef.current?.getValue() || "";
doSend(content);
}, [canSend, doSend]);
return (
<div
ref={composerRef}
@@ -361,13 +318,6 @@ export default memo(function ChatComposer({
)}
<div className="relative">
<AtMentionPopup
open={showAtPopup}
onSelectNotebook={handleSelectNotebook}
onSelectHistory={handleSelectHistory}
onSelectQuestionBank={handleSelectQuestionBank}
/>
<div
className={`relative rounded-2xl border bg-[var(--card)] shadow-[0_1px_8px_rgba(0,0,0,0.03)] transition-colors ${
dragging
@@ -389,35 +339,32 @@ export default memo(function ChatComposer({
</div>
)}
<div className="px-4 pt-3.5 pb-2">
<ReferenceChips
historySessions={selectedHistorySessions}
notebookGroups={notebookReferenceGroups}
questionEntries={selectedQuestionEntries}
onRemoveHistory={onRemoveHistory}
onRemoveNotebook={onRemoveNotebook}
onRemoveQuestion={onRemoveQuestion}
/>
<textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onClick={handleTextareaClick}
onPaste={onPaste}
rows={1}
suppressHydrationWarning
placeholder={
isMathAnimatorMode
? t("Describe the math animation or storyboard you want...")
: isVisualizeMode
? t("Describe the chart or diagram you want to visualize...")
: t("How can I help you today?")
}
className="w-full resize-none overflow-hidden bg-transparent text-[15px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
style={{ transition: "height 0.15s ease-out", minHeight: 28 }}
/>
</div>
{hasReferences && (
<div className="px-4 pt-3.5 [&>div]:mb-0">
<ReferenceChips
historySessions={selectedHistorySessions}
notebookGroups={notebookReferenceGroups}
questionEntries={selectedQuestionEntries}
onRemoveHistory={onRemoveHistory}
onRemoveNotebook={onRemoveNotebook}
onRemoveQuestion={onRemoveQuestion}
/>
</div>
)}
<ComposerInput
ref={inputHandleRef}
textareaRef={textareaRef}
activeCapabilityKey={activeCapabilityKey}
isMathAnimatorMode={isMathAnimatorMode}
isVisualizeMode={isVisualizeMode}
canSendEmpty={hasReferences}
onSend={doSend}
onInputChange={handleInputChange}
onPaste={onPaste}
onSelectNotebookPicker={onSelectNotebookPicker}
onSelectHistoryPicker={onSelectHistoryPicker}
onSelectQuestionBankPicker={onSelectQuestionBankPicker}
/>
{!!attachments.length && (
<div className="flex flex-wrap gap-2 px-4 pb-2">
@@ -756,7 +703,7 @@ export default memo(function ChatComposer({
) : (
<button
type="button"
onClick={doSend}
onClick={handleManualSend}
disabled={!canSend}
className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)] disabled:opacity-25 disabled:shadow-none"
aria-label={t("Send")}

View File

@@ -0,0 +1,172 @@
"use client";
import { forwardRef, memo, useCallback, useImperativeHandle, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import AtMentionPopup from "@/components/chat/AtMentionPopup";
interface ComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
activeCapabilityKey: string;
isMathAnimatorMode: boolean;
isVisualizeMode: boolean;
// When true, parent has attachments/references queued and will accept a
// send even if the text body is empty. Without this, Enter would silently
// do nothing for an attachment-only message.
canSendEmpty: boolean;
onSend: (content: string) => void;
onInputChange: (content: string) => void;
onPaste: (e: React.ClipboardEvent) => void;
onSelectNotebookPicker: () => void;
onSelectHistoryPicker: () => void;
onSelectQuestionBankPicker: () => void;
}
export interface ComposerInputHandle {
clear: () => void;
getValue: () => string;
}
export function shouldOpenAtPopup(value: string, cursorPos: number): boolean {
const prefix = value.slice(0, cursorPos);
return /(^|\s)@[^\s]*$/.test(prefix);
}
export function stripTrailingAtMention(value: string): string {
return value.replace(/(^|\s)@[^\s]*$/, "$1").replace(/\s+$/, "");
}
export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputProps>(function ComposerInput({
textareaRef,
activeCapabilityKey,
isMathAnimatorMode,
isVisualizeMode,
canSendEmpty,
onSend,
onInputChange,
onPaste,
onSelectNotebookPicker,
onSelectHistoryPicker,
onSelectQuestionBankPicker,
}, ref) {
const { t } = useTranslation();
const [input, setInput] = useState("");
const [showAtPopup, setShowAtPopup] = useState(false);
// Latest text mirrored into a ref by the change handlers (never updated
// during render). The select-* handlers and the imperative handle read
// from this ref so their identities stay stable across keystrokes,
// letting `memo` on AtMentionPopup actually skip re-renders when
// `showAtPopup` doesn't change.
const inputRef = useRef("");
// Helper that always updates state and ref together so they can't drift.
const setInputBoth = useCallback((value: string) => {
inputRef.current = value;
setInput(value);
}, []);
useImperativeHandle(ref, () => ({
clear: () => {
setInputBoth("");
onInputChange("");
},
getValue: () => inputRef.current,
}), [setInputBoth, onInputChange]);
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "28px";
const next = Math.max(el.scrollHeight, 28);
const bounded = Math.min(next, 200);
el.style.height = `${bounded}px`;
el.style.overflowY = next > 200 ? "auto" : "hidden";
}, [input, activeCapabilityKey, textareaRef]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
const cursorPos = e.target.selectionStart ?? value.length;
setInputBoth(value);
onInputChange(value);
setShowAtPopup(shouldOpenAtPopup(value, cursorPos));
}, [setInputBoth, onInputChange]);
const handleTextareaClick = useCallback((e: React.MouseEvent<HTMLTextAreaElement>) => {
const target = e.currentTarget;
setShowAtPopup(shouldOpenAtPopup(target.value, target.selectionStart ?? target.value.length));
}, []);
const doSend = useCallback(() => {
const content = inputRef.current.trim();
// Allow sending when text is empty but the parent has attachments or
// references queued (canSendEmpty). This matches the send-button's
// own enablement logic in ChatComposer (`canSend`).
if (!content && !canSendEmpty) return;
onSend(content);
setInputBoth("");
onInputChange("");
setShowAtPopup(false);
}, [canSendEmpty, onSend, setInputBoth, onInputChange]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
doSend();
} else if (e.key === "Escape") {
setShowAtPopup(false);
}
}, [doSend]);
const handleSelectNotebook = useCallback(() => {
const next = stripTrailingAtMention(inputRef.current);
setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectNotebookPicker();
}, [setInputBoth, onInputChange, onSelectNotebookPicker]);
const handleSelectHistory = useCallback(() => {
const next = stripTrailingAtMention(inputRef.current);
setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectHistoryPicker();
}, [setInputBoth, onInputChange, onSelectHistoryPicker]);
const handleSelectQuestionBank = useCallback(() => {
const next = stripTrailingAtMention(inputRef.current);
setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectQuestionBankPicker();
}, [setInputBoth, onInputChange, onSelectQuestionBankPicker]);
return (
<div className="px-4 pt-3.5 pb-2">
<AtMentionPopup
open={showAtPopup}
onSelectNotebook={handleSelectNotebook}
onSelectHistory={handleSelectHistory}
onSelectQuestionBank={handleSelectQuestionBank}
/>
<textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onClick={handleTextareaClick}
onPaste={onPaste}
rows={1}
suppressHydrationWarning
placeholder={
isMathAnimatorMode
? t("Describe the math animation or storyboard you want...")
: isVisualizeMode
? t("Describe the chart or diagram you want to visualize...")
: t("How can I help you today?")
}
className="w-full resize-none overflow-hidden bg-transparent text-[15px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
style={{ transition: "height 0.15s ease-out", minHeight: 28 }}
/>
</div>
);
}));

View File

@@ -0,0 +1,56 @@
"use client";
import { memo, useCallback, useLayoutEffect, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
interface SimpleComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
onSend: (content: string) => void;
disabled?: boolean;
}
export const SimpleComposerInput = memo(function SimpleComposerInput({
textareaRef,
onSend,
disabled,
}: SimpleComposerInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState("");
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "auto";
const next = Math.max(el.scrollHeight, 42);
el.style.height = `${Math.min(next, 200)}px`;
}, [input, textareaRef]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
const content = input.trim();
if (content && !disabled) {
onSend(content);
setInput("");
}
}
}, [input, onSend, disabled]);
return (
<textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder={t("Type a message...")}
rows={1}
disabled={disabled}
className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"
style={{ minHeight: 42 }}
/>
);
});

View File

@@ -1,5 +1,6 @@
"use client";
import { memo } from "react";
import { useTranslation } from "react-i18next";
import {
summarizeMathAnimatorConfig,
@@ -18,7 +19,7 @@ interface MathAnimatorConfigPanelProps {
onToggleCollapsed: () => void;
}
export default function MathAnimatorConfigPanel({
export default memo(function MathAnimatorConfigPanel({
value,
onChange,
collapsed,
@@ -71,5 +72,5 @@ export default function MathAnimatorConfigPanel({
</Field>
</CollapsibleConfigSection>
);
}
});

View File

@@ -1,6 +1,6 @@
"use client";
import { useRef, useState } from "react";
import { memo, useRef, useState } from "react";
import { FileText, Upload, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
@@ -23,7 +23,7 @@ interface QuizConfigPanelProps {
onToggleCollapsed: () => void;
}
export default function QuizConfigPanel({
export default memo(function QuizConfigPanel({
value,
onChange,
uploadedPdf,
@@ -204,5 +204,5 @@ export default function QuizConfigPanel({
)}
</CollapsibleConfigSection>
);
}
});

View File

@@ -1,5 +1,6 @@
"use client";
import { memo } from "react";
import { useTranslation } from "react-i18next";
import type {
DeepResearchFormConfig,
@@ -69,7 +70,7 @@ function NumberSlider({
);
}
export default function ResearchConfigPanel({
export default memo(function ResearchConfigPanel({
value,
errors: _errors,
collapsed,
@@ -142,4 +143,4 @@ export default function ResearchConfigPanel({
)}
</CollapsibleConfigSection>
);
}
});

View File

@@ -9,6 +9,7 @@ import {
BookOpen,
Bot,
Brain,
Github,
Library,
MessageSquare,
PanelLeftClose,
@@ -23,6 +24,7 @@ import SessionList from "@/components/SessionList";
import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";
import { BookRecent } from "@/components/sidebar/BookRecent";
import { CoWriterRecent } from "@/components/sidebar/CoWriterRecent";
import { VersionBadge } from "@/components/sidebar/VersionBadge";
import type { SessionSummary } from "@/lib/session-api";
interface NavEntry {
@@ -42,6 +44,7 @@ const PRIMARY_NAV: NavEntry[] = [
const SECONDARY_NAV: NavEntry[] = [{ href: "/settings", label: "Settings", icon: Settings }];
const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[112px]";
const GITHUB_REPO_URL = "https://github.com/HKUDS/DeepTutor";
interface SidebarShellProps {
sessions?: SessionSummary[];
@@ -172,6 +175,17 @@ export function SidebarShell({
);
})}
{footerSlot}
<a
href={GITHUB_REPO_URL}
target="_blank"
rel="noreferrer noopener"
title="GitHub"
aria-label="GitHub"
className="mt-1 flex h-9 w-9 items-center justify-center rounded-xl text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
>
<Github size={15} strokeWidth={1.6} />
</a>
<VersionBadge collapsed />
</div>
</aside>
);
@@ -279,6 +293,19 @@ export function SidebarShell({
);
})}
{footerSlot}
<div className="mt-0.5 flex items-center gap-0.5">
<VersionBadge />
<a
href={GITHUB_REPO_URL}
target="_blank"
rel="noreferrer noopener"
title="GitHub"
aria-label="GitHub"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"
>
<Github size={13} strokeWidth={1.7} />
</a>
</div>
</div>
</aside>
);

View File

@@ -0,0 +1,128 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
interface VersionPayload {
tag: string | null;
name: string | null;
url: string | null;
publishedAt: string | null;
source: "github" | "fallback";
}
interface VersionBadgeProps {
/** Render the compact variant for the collapsed sidebar (currently hidden). */
collapsed?: boolean;
}
let _cache: VersionPayload | null = null;
let _inflight: Promise<VersionPayload | null> | null = null;
async function loadVersion(): Promise<VersionPayload | null> {
if (_cache) return _cache;
if (_inflight) return _inflight;
_inflight = (async () => {
try {
const res = await fetch("/api/version", { cache: "force-cache" });
if (!res.ok) return null;
const data = (await res.json()) as VersionPayload;
_cache = data;
return data;
} catch {
return null;
} finally {
_inflight = null;
}
})();
return _inflight;
}
// Normalize a version-like string ("v1.2.3", "v1.2.3-3-gabc", "1.2.3-dev")
// down to its canonical "v1.2.3" form for equality comparison.
function normalize(raw: string | null | undefined): string | null {
if (!raw) return null;
const m = raw.match(/v?(\d+\.\d+\.\d+)/);
return m ? `v${m[1]}` : null;
}
type Status = "latest" | "outdated" | "unknown";
export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
const { t } = useTranslation();
const [data, setData] = useState<VersionPayload | null>(_cache);
useEffect(() => {
let cancelled = false;
if (!_cache) {
loadVersion().then((v) => {
if (!cancelled) setData(v);
});
}
return () => {
cancelled = true;
};
}, []);
const buildRaw = process.env.NEXT_PUBLIC_APP_VERSION || "";
const buildNorm = normalize(buildRaw);
const latestNorm = normalize(data?.tag);
const { status, displayTag, href, tooltip } = useMemo(() => {
let status: Status = "unknown";
if (buildNorm && latestNorm) {
status = buildNorm === latestNorm ? "latest" : "outdated";
}
// Show what the user is actually running when we know it; otherwise
// fall back to the latest release as a passive informational display.
const displayTag = buildNorm ?? latestNorm ?? null;
const href =
data?.url ??
(latestNorm
? `https://github.com/HKUDS/DeepTutor/releases/tag/${latestNorm}`
: "https://github.com/HKUDS/DeepTutor/releases");
let tooltip: string;
if (status === "latest" && displayTag) {
tooltip = `${displayTag} · ${t("Up to date")}`;
} else if (status === "outdated" && displayTag && latestNorm) {
tooltip = `${displayTag} · ${t("Update available")}: ${latestNorm}`;
} else if (displayTag) {
tooltip = `${t("Latest release")}: ${displayTag}`;
} else {
tooltip = t("Loading...");
}
return { status, displayTag, href, tooltip };
}, [buildNorm, latestNorm, data?.url, t]);
// Keep the collapsed sidebar entirely free of version chrome.
if (collapsed) return null;
const dotClass =
status === "latest"
? "bg-emerald-500/45"
: status === "outdated"
? "bg-amber-500/55"
: "bg-[var(--muted-foreground)]/25";
return (
<a
href={href}
target="_blank"
rel="noreferrer noopener"
title={tooltip}
className="group/ver flex min-w-0 flex-1 items-center gap-2 rounded-lg px-3 py-1.5 text-[11px] font-mono tabular-nums tracking-tight text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"
>
<span
className={`h-1.5 w-1.5 shrink-0 rounded-full transition-colors ${dotClass}`}
aria-hidden="true"
/>
<span className="truncate leading-none decoration-[var(--muted-foreground)]/40 decoration-dotted underline-offset-[3px] group-hover/ver:underline">
{displayTag ?? "—"}
</span>
</a>
);
}

View File

@@ -1,5 +1,6 @@
"use client";
import { memo } from "react";
import { useTranslation } from "react-i18next";
import {
summarizeVisualizeConfig,
@@ -18,7 +19,7 @@ interface VisualizeConfigPanelProps {
onToggleCollapsed: () => void;
}
export default function VisualizeConfigPanel({
export default memo(function VisualizeConfigPanel({
value,
onChange,
collapsed,
@@ -50,4 +51,4 @@ export default function VisualizeConfigPanel({
</Field>
</CollapsibleConfigSection>
);
}
});

View File

@@ -17,6 +17,60 @@ export const API_BASE_URL =
);
})();
// Hostnames that always refer to the local machine. When the build-time base
// URL points to one of these, but the page is opened from a non-local origin,
// we rewrite the hostname so requests reach the actual server.
const LOOPBACK_HOSTS = new Set([
"localhost",
"127.0.0.1",
"0.0.0.0",
"::1",
"[::1]",
]);
let warnedAboutHostSwap = false;
function isLoopbackHost(host: string): boolean {
return LOOPBACK_HOSTS.has(host.toLowerCase());
}
/**
* Resolve the effective API base URL at runtime.
*
* NEXT_PUBLIC_API_BASE is a build-time constant that is typically set to
* http://localhost:<port>. When another machine on the LAN opens the app that
* constant still points at "localhost", which the remote browser resolves to
* its *own* loopback address instead of the server. We detect this situation
* and swap the hostname for window.location.hostname so the request reaches
* the actual server regardless of which machine opened the page.
*
* The full path/search is preserved (so deployments behind a reverse proxy
* like `http://localhost:8001/api` continue to work after the rewrite).
*/
export function resolveBase(): string {
const base = API_BASE_URL;
if (typeof window === "undefined") return base;
try {
const url = new URL(base);
const clientHost = window.location.hostname;
if (isLoopbackHost(url.hostname) && !isLoopbackHost(clientHost)) {
url.hostname = clientHost;
if (!warnedAboutHostSwap) {
warnedAboutHostSwap = true;
console.warn(
`[api] NEXT_PUBLIC_API_BASE points to "${base}" but the page is served from "${clientHost}"; ` +
`routing API/WebSocket calls to "${url.toString()}" instead.`,
);
}
// Use href (full URL) instead of origin so we keep any path/search.
return url.toString().replace(/\/+$/, "");
}
} catch {
// base is not a valid absolute URL – return as-is
}
return base;
}
/**
* Construct a full API URL from a path
* @param path - API path (e.g., '/api/v1/knowledge/list')
@@ -27,11 +81,10 @@ export function apiUrl(path: string): string {
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
// Remove trailing slash from base URL if present
const base = API_BASE_URL.endsWith("/")
? API_BASE_URL.slice(0, -1)
: API_BASE_URL;
const base = resolveBase();
const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
return `${base}${normalizedPath}`;
return `${normalizedBase}${normalizedPath}`;
}
/**
@@ -42,7 +95,7 @@ export function apiUrl(path: string): string {
export function wsUrl(path: string): string {
// Security Hardening: Convert http to ws and https to wss.
// In production environments (where API_BASE_URL starts with https), this ensures secure websockets.
const base = API_BASE_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
const base = resolveBase().replace(/^http:/, "ws:").replace(/^https:/, "wss:");
// Remove leading slash if present to avoid double slashes
const normalizedPath = path.startsWith("/") ? path : `/${path}`;

6
web/lib/route-params.ts Normal file
View File

@@ -0,0 +1,6 @@
export function firstParam(value: string | string[] | undefined): string | undefined {
if (Array.isArray(value)) {
return value[0];
}
return value;
}

View File

@@ -170,6 +170,8 @@
"Base URL": "Base URL",
"Use .env": "Use .env",
"API Key": "API Key",
"Show API key": "Show API key",
"Hide API key": "Hide API key",
"optional for local providers": "optional for local providers",
"Not required": "Not required",
"Base URL is required for testing": "Base URL is required for testing",
@@ -1025,5 +1027,8 @@
"Incomplete settings": "Incomplete settings",
"llm-only": "llm-only",
"Copy": "Copy",
"Regenerate": "Regenerate"
"Regenerate": "Regenerate",
"Latest release": "Latest release",
"Up to date": "Up to date",
"Update available": "Update available"
}

View File

@@ -170,6 +170,8 @@
"Base URL": "Base URL",
"Use .env": "使用 .env",
"API Key": "API Key",
"Show API key": "显示 API Key",
"Hide API key": "隐藏 API Key",
"optional for local providers": "本地服务可选",
"Not required": "不需要",
"Base URL is required for testing": "测试需要 Base URL",
@@ -1025,5 +1027,8 @@
"Incomplete settings": "设置不完整",
"llm-only": "仅 LLM",
"Copy": "复制",
"Regenerate": "重新生成"
"Regenerate": "重新生成",
"Latest release": "最新版本",
"Up to date": "已是最新",
"Update available": "有新版本"
}

View File

@@ -1,6 +1,31 @@
/** @type {import('next').NextConfig} */
// Resolve the build-time application version. Priority:
// 1. Explicit APP_VERSION env (set by CI from the release tag)
// 2. `git describe --tags` when building from a checkout (local dev)
// 3. Empty string → frontend treats it as "unknown" and shows the
// latest GitHub release as a neutral fallback.
const APP_VERSION = (() => {
if (process.env.APP_VERSION) return process.env.APP_VERSION;
try {
const { execSync } = require("child_process");
return execSync("git describe --tags --always --dirty=-dev", {
stdio: ["ignore", "pipe", "ignore"],
})
.toString()
.trim();
} catch {
return "";
}
})();
const nextConfig = {
// Expose the build-time version to the browser so the sidebar badge
// can compare it against GitHub's latest release.
env: {
NEXT_PUBLIC_APP_VERSION: APP_VERSION,
},
// Standalone output: self-contained server.js + minimal node_modules
// This eliminates the need to copy the full node_modules into Docker production images
output: "standalone",

View File

@@ -0,0 +1,59 @@
import test from "node:test";
import assert from "node:assert/strict";
// Must be set before importing the module under test, since API_BASE_URL is
// read at module-load time and the module throws if it's missing.
process.env.NEXT_PUBLIC_API_BASE = "http://localhost:8001/api";
const { resolveBase, apiUrl, wsUrl } = await import("../lib/api.ts");
function setWindow(hostname: string | undefined): void {
if (hostname === undefined) {
delete (globalThis as { window?: unknown }).window;
return;
}
(globalThis as { window?: unknown }).window = {
location: { hostname },
} as unknown;
}
test("resolveBase returns the build-time base in SSR (no window)", () => {
setWindow(undefined);
assert.equal(resolveBase(), "http://localhost:8001/api");
});
test("resolveBase returns base unchanged when client is also on localhost", () => {
setWindow("localhost");
assert.equal(resolveBase(), "http://localhost:8001/api");
});
test("resolveBase rewrites loopback hostname to remote LAN host and preserves path", () => {
setWindow("192.168.1.10");
assert.equal(resolveBase(), "http://192.168.1.10:8001/api");
});
test("resolveBase treats IPv6 loopback as loopback (no swap when client is also ::1)", () => {
setWindow("::1");
assert.equal(resolveBase(), "http://localhost:8001/api");
});
test("apiUrl composes correctly after rewrite, without losing the base path", () => {
setWindow("10.0.0.5");
assert.equal(
apiUrl("/api/v1/knowledge/list"),
"http://10.0.0.5:8001/api/api/v1/knowledge/list",
);
});
test("wsUrl converts http to ws and respects rewritten host", () => {
setWindow("10.0.0.5");
assert.equal(
wsUrl("/api/v1/ws"),
"ws://10.0.0.5:8001/api/api/v1/ws",
);
});
test("wsUrl keeps original loopback when client is also loopback", () => {
setWindow("127.0.0.1");
assert.equal(wsUrl("/api/v1/ws"), "ws://localhost:8001/api/api/v1/ws");
});

View File

@@ -0,0 +1,16 @@
import test from "node:test";
import assert from "node:assert/strict";
import { firstParam } from "../lib/route-params.ts";
test("firstParam returns undefined for missing param", () => {
assert.equal(firstParam(undefined), undefined);
});
test("firstParam returns scalar param unchanged", () => {
assert.equal(firstParam("ielts-tutor"), "ielts-tutor");
});
test("firstParam returns first element for catch-all array", () => {
assert.equal(firstParam(["ielts-tutor", "extra"]), "ielts-tutor");
});