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//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 f2fd8b33a..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,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) 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 5788a8d92..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) 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/deeptutor_cli/common.py b/deeptutor_cli/common.py index 9c43597d8..1f4a3ae9d 100644 --- a/deeptutor_cli/common.py +++ b/deeptutor_cli/common.py @@ -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): diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.py index d4f81a5d5..b0574c506 100644 --- a/tests/api/test_tutorbot_router.py +++ b/tests/api/test_tutorbot_router.py @@ -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 diff --git a/tests/cli/test_common.py b/tests/cli/test_common.py new file mode 100644 index 000000000..213b860a9 --- /dev/null +++ b/tests/cli/test_common.py @@ -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("{") diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx index a6e2d7b7c..3bb1f8599 100644 --- a/web/app/(utility)/settings/page.tsx +++ b/web/app/(utility)/settings/page.tsx @@ -9,6 +9,8 @@ import { ChevronDown, ChevronRight, Database, + Eye, + EyeOff, Loader2, Plus, Rocket, @@ -376,6 +378,7 @@ function SettingsPageContent() { const [testRunning, setTestRunning] = useState(null); const [saving, setSaving] = useState(false); const [applying, setApplying] = useState(false); + const [showApiKey, setShowApiKey] = useState(false); const [toast, setToast] = useState(""); const [diagnosticsOpen, setDiagnosticsOpen] = useState(false); const [providers, setProviders] = useState>({ 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() {
{t("API Key")}
- updateProfileField("api_key", e.target.value)} - placeholder="sk-..." - /> +
+ updateProfileField("api_key", e.target.value)} + placeholder="sk-..." + /> + +
{t("API Version")}
diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx index 307265f7e..2328441f1 100644 --- a/web/app/(workspace)/agents/[botId]/chat/page.tsx +++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx @@ -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(null); const [messages, setMessages] = useState([]); - const [input, setInput] = useState(""); const [streaming, setStreaming] = useState(false); const [thinking, setThinking] = useState([]); const thinkingRef = useRef([]); @@ -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) => { - 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 (
@@ -207,25 +211,21 @@ export default function BotChatPage() { {/* Input */}
-