Skip to content

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

release: v1.2.2 โ€” Skills system, input perf, response_format auto-fallback, version badge

Bingxi Zhao (Frank)2f6ac5aa801b
diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml
index 005e88856..c87324ff0 100644
--- a/.github/workflows/docker-release.yml
+++ b/.github/workflows/docker-release.yml
@@ -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
diff --git a/Dockerfile b/Dockerfile
index ce079fbae..75d99d095 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -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* ./
diff --git a/README.md b/README.md
index 7265562a3..8a5a40596 100644
--- a/README.md
+++ b/README.md
@@ -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!
diff --git a/assets/releases/ver1-2-2.md b/assets/releases/ver1-2-2.md
new file mode 100644
index 000000000..dff35f40a
--- /dev/null
+++ b/assets/releases/ver1-2-2.md
@@ -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
diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.py
index 128d40f25..3d4c9c1de 100644
--- a/deeptutor/agents/base_agent.py
+++ b/deeptutor/agents/base_agent.py
@@ -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
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index edd0faadc..14fad5d8b 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -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(
diff --git a/deeptutor/agents/solve/agents/planner_agent.py b/deeptutor/agents/solve/agents/planner_agent.py
index 20cee3c12..d2e9970a5 100644
--- a/deeptutor/agents/solve/agents/planner_agent.py
+++ b/deeptutor/agents/solve/agents/planner_agent.py
@@ -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):
diff --git a/deeptutor/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.py
index 2eecffce3..dc9e6d50f 100644
--- a/deeptutor/agents/solve/agents/solver_agent.py
+++ b/deeptutor/agents/solve/agents/solver_agent.py
@@ -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):
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index ae0f47f15..d275b5263 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -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,13 +346,18 @@ 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()
@@ -344,24 +368,32 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
if not instance or not instance.running:
config = mgr.load_bot_config(bot_id)
if config is None:
- await ws.send_json({"type": "error", "content": "Bot not found"})
+ await _safe_send({"type": "error", "content": "Bot not found"})
await ws.close(code=4004, reason="Bot not found")
return
- try:
- instance = await mgr.start_bot(bot_id, config)
- except Exception:
- logger.exception("Failed to auto-start bot '%s' for websocket", bot_id)
- await ws.send_json({"type": "error", "content": "Failed to start bot"})
- await ws.close(code=1011, reason="Failed to start bot")
- 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:
+ while not disconnected.is_set():
try:
raw = await ws.receive_text()
except WebSocketDisconnect:
+ disconnected.set()
break
try:
data = json.loads(raw)
@@ -375,8 +407,13 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
continue
async def on_progress(text: str) -> None:
- if not await _safe_send({"type": "thinking", "content": text}):
- raise WebSocketDisconnect()
+ # 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(
@@ -391,6 +428,7 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
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)
@@ -398,11 +436,20 @@ async def bot_chat_ws(ws: WebSocket, bot_id: str):
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())
@@ -411,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)
diff --git a/deeptutor/capabilities/_answer_now.py b/deeptutor/capabilities/_answer_now.py
index f28f45c3b..7932cc1b7 100644
--- a/deeptutor/capabilities/_answer_now.py
+++ b/deeptutor/capabilities/_answer_now.py
@@ -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:
diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.py
index 342b97ced..ec8f02f79 100644
--- a/deeptutor/capabilities/deep_solve.py
+++ b/deeptutor/capabilities/deep_solve.py
@@ -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(
diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.py
index 63a494af3..b47b4b190 100644
--- a/deeptutor/services/embedding/adapters/openai_compatible.py
+++ b/deeptutor/services/embedding/adapters/openai_compatible.py
@@ -166,18 +166,25 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
response.raise_for_status()
data = response.json()
break
- except (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.ConnectError) 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:
diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.py
index ca983a123..b0574c506 100644
--- a/tests/api/test_tutorbot_router.py
+++ b/tests/api/test_tutorbot_router.py
@@ -522,3 +522,123 @@ class TestBotChatWebSocketStartup:
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
diff --git a/web/app/api/version/route.ts b/web/app/api/version/route.ts
new file mode 100644
index 000000000..0dd333eb5
--- /dev/null
+++ b/web/app/api/version/route.ts
@@ -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 },
+ );
+ }
+}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 698c9bcf9..875e456e8 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -77,7 +77,6 @@ interface ResearchSourceDef {
icon: LucideIcon;
}
-
export default memo(function ChatComposer({
composerRef,
capMenuRef,
@@ -242,12 +241,13 @@ export default memo(function ChatComposer({
if (!hasMessages) textareaRef.current?.focus();
}, [hasMessages]);
+ // 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 nextHasContent = !!val.trim();
- if (nextHasContent !== hasContent) {
- setHasContent(nextHasContent);
- }
- }, [hasContent]);
+ const next = !!val.trim();
+ setHasContent((prev) => (prev === next ? prev : next));
+ }, []);
const doSend = useCallback((content: string) => {
onSend(content);
@@ -255,23 +255,22 @@ export default memo(function ChatComposer({
inputHandleRef.current?.clear();
}, [onSend]);
- const handleManualSend = useCallback(() => {
- const content = inputHandleRef.current?.getValue() || "";
- if (!!content.trim() || attachments.length || selectedNotebookRecords.length || selectedHistorySessions.length || selectedQuestionEntries.length) {
- doSend(content);
- }
- }, [doSend, attachments.length, selectedNotebookRecords.length, selectedHistorySessions.length, selectedQuestionEntries.length]);
+ const hasReferences =
+ !!attachments.length ||
+ !!selectedNotebookRecords.length ||
+ !!selectedHistorySessions.length ||
+ !!selectedQuestionEntries.length;
const canSend =
- (hasContent ||
- !!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
@@ -340,8 +339,8 @@ export default memo(function ChatComposer({
</div>
)}
- <div className="pt-0.5">
- <div className="px-4 pt-3">
+ {hasReferences && (
+ <div className="px-4 pt-3.5 [&>div]:mb-0">
<ReferenceChips
historySessions={selectedHistorySessions}
notebookGroups={notebookReferenceGroups}
@@ -351,21 +350,21 @@ export default memo(function ChatComposer({
onRemoveQuestion={onRemoveQuestion}
/>
</div>
- <ComposerInput
- ref={inputHandleRef}
- textareaRef={textareaRef}
- activeCapabilityKey={activeCapabilityKey}
- isMathAnimatorMode={isMathAnimatorMode}
- isVisualizeMode={isVisualizeMode}
- onSend={doSend}
- onInputChange={handleInputChange}
- onPaste={onPaste}
- onSelectNotebookPicker={onSelectNotebookPicker}
- onSelectHistoryPicker={onSelectHistoryPicker}
- onSelectQuestionBankPicker={onSelectQuestionBankPicker}
- />
- </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">
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 663fccd81..95f0890fa 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -1,6 +1,6 @@
"use client";
-import { forwardRef, memo, useCallback, useImperativeHandle, useLayoutEffect, useState, type RefObject } from "react";
+import { forwardRef, memo, useCallback, useImperativeHandle, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import AtMentionPopup from "@/components/chat/AtMentionPopup";
@@ -9,6 +9,10 @@ interface ComposerInputProps {
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;
@@ -36,6 +40,7 @@ export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputP
activeCapabilityKey,
isMathAnimatorMode,
isVisualizeMode,
+ canSendEmpty,
onSend,
onInputChange,
onPaste,
@@ -47,14 +52,25 @@ export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputP
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: () => {
- setInput("");
+ setInputBoth("");
onInputChange("");
},
- getValue: () => input,
- }));
-
+ getValue: () => inputRef.current,
+ }), [setInputBoth, onInputChange]);
useLayoutEffect(() => {
const el = textareaRef.current;
@@ -69,10 +85,10 @@ export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputP
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
const cursorPos = e.target.selectionStart ?? value.length;
- setInput(value);
+ setInputBoth(value);
onInputChange(value);
setShowAtPopup(shouldOpenAtPopup(value, cursorPos));
- }, [onInputChange]);
+ }, [setInputBoth, onInputChange]);
const handleTextareaClick = useCallback((e: React.MouseEvent<HTMLTextAreaElement>) => {
const target = e.currentTarget;
@@ -80,13 +96,16 @@ export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputP
}, []);
const doSend = useCallback(() => {
- const content = input.trim();
- if (!content) return;
+ 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);
- setInput("");
+ setInputBoth("");
onInputChange("");
setShowAtPopup(false);
- }, [input, onSend, onInputChange]);
+ }, [canSendEmpty, onSend, setInputBoth, onInputChange]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -98,28 +117,28 @@ export const ComposerInput = memo(forwardRef<ComposerInputHandle, ComposerInputP
}, [doSend]);
const handleSelectNotebook = useCallback(() => {
- const next = stripTrailingAtMention(input);
- setInput(next);
+ const next = stripTrailingAtMention(inputRef.current);
+ setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectNotebookPicker();
- }, [input, onInputChange, onSelectNotebookPicker]);
+ }, [setInputBoth, onInputChange, onSelectNotebookPicker]);
const handleSelectHistory = useCallback(() => {
- const next = stripTrailingAtMention(input);
- setInput(next);
+ const next = stripTrailingAtMention(inputRef.current);
+ setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectHistoryPicker();
- }, [input, onInputChange, onSelectHistoryPicker]);
+ }, [setInputBoth, onInputChange, onSelectHistoryPicker]);
const handleSelectQuestionBank = useCallback(() => {
- const next = stripTrailingAtMention(input);
- setInput(next);
+ const next = stripTrailingAtMention(inputRef.current);
+ setInputBoth(next);
onInputChange(next);
setShowAtPopup(false);
onSelectQuestionBankPicker();
- }, [input, onInputChange, onSelectQuestionBankPicker]);
+ }, [setInputBoth, onInputChange, onSelectQuestionBankPicker]);
return (
<div className="px-4 pt-3.5 pb-2">
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 2b7e3a4b2..e0c4d1635 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -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>
);
diff --git a/web/components/sidebar/VersionBadge.tsx b/web/components/sidebar/VersionBadge.tsx
new file mode 100644
index 000000000..d0167f01d
--- /dev/null
+++ b/web/components/sidebar/VersionBadge.tsx
@@ -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>
+ );
+}
diff --git a/web/lib/api.ts b/web/lib/api.ts
index 90b644452..0b9e8e297 100644
--- a/web/lib/api.ts
+++ b/web/lib/api.ts
@@ -17,6 +17,23 @@ 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.
*
@@ -26,19 +43,27 @@ export const API_BASE_URL =
* 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).
*/
-function resolveBase(): string {
+export function resolveBase(): string {
const base = API_BASE_URL;
if (typeof window === "undefined") return base;
try {
const url = new URL(base);
- const isLoopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
- const clientIsRemote =
- window.location.hostname !== "localhost" &&
- window.location.hostname !== "127.0.0.1";
- if (isLoopback && clientIsRemote) {
- url.hostname = window.location.hostname;
- return url.origin;
+ 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
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 2ef4febc9..002e54942 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -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"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index dac1ee120..e08763a66 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -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": "ๆœ‰ๆ–ฐ็‰ˆๆœฌ"
}
diff --git a/web/next.config.js b/web/next.config.js
index dfff4146c..8580f16c2 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -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",
diff --git a/web/tests/api-resolve-base.test.ts b/web/tests/api-resolve-base.test.ts
new file mode 100644
index 000000000..22e27c257
--- /dev/null
+++ b/web/tests/api-resolve-base.test.ts
@@ -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");
+});