Skip to content

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

fix : Tutorbot websocket resilience and CLI config parsing edge case (#354)

Srinivas R Kulkarni6735adf32c4c
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index f2fd8b33a..ae0f47f15 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -329,22 +329,45 @@ async def get_bot_history(bot_id: str, limit: int = 100):
async def bot_chat_ws(ws: WebSocket, bot_id: str):
import asyncio
+ async def _safe_send(payload: dict) -> bool:
+ try:
+ await ws.send_json(payload)
+ return True
+ except (WebSocketDisconnect, RuntimeError):
+ 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 ws.send_json({"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
+
logger.info("WebSocket connected for bot '%s'", bot_id)
async def _handle_user_messages():
while True:
- raw = await ws.receive_text()
+ try:
+ raw = await ws.receive_text()
+ except WebSocketDisconnect:
+ 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,20 +375,27 @@ 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})
+ if not await _safe_send({"type": "thinking", "content": text}):
+ raise WebSocketDisconnect()
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:
+ 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:
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..ca983a123 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,63 @@ 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()
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/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx
index 307265f7e..02c1c71f0 100644
--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx
+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx
@@ -5,6 +5,7 @@ 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";
interface BotInfo {
@@ -20,7 +21,8 @@ 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();
@@ -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;
@@ -102,6 +110,7 @@ export default function BotChatPage() {
}, [botId, scrollToBottom]);
const send = useCallback(() => {
+ if (!botId) return;
const text = input.trim();
if (!text || streaming || !wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
@@ -111,7 +120,7 @@ export default function BotChatPage() {
setThinking([]);
wsRef.current.send(JSON.stringify({ content: text }));
scrollToBottom();
- }, [input, streaming, scrollToBottom]);
+ }, [botId, input, streaming, scrollToBottom]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
diff --git a/web/lib/route-params.ts b/web/lib/route-params.ts
new file mode 100644
index 000000000..ff9de9d24
--- /dev/null
+++ b/web/lib/route-params.ts
@@ -0,0 +1,6 @@
+export function firstParam(value: string | string[] | undefined): string | undefined {
+ if (Array.isArray(value)) {
+ return value[0];
+ }
+ return value;
+}
diff --git a/web/tests/route-params.test.ts b/web/tests/route-params.test.ts
new file mode 100644
index 000000000..85ccf8348
--- /dev/null
+++ b/web/tests/route-params.test.ts
@@ -0,0 +1,16 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { firstParam } from "../lib/route-params.ts";
+
+test("firstParam returns undefined for missing param", () => {
+ assert.equal(firstParam(undefined), undefined);
+});
+
+test("firstParam returns scalar param unchanged", () => {
+ assert.equal(firstParam("ielts-tutor"), "ielts-tutor");
+});
+
+test("firstParam returns first element for catch-all array", () => {
+ assert.equal(firstParam(["ielts-tutor", "extra"]), "ielts-tutor");
+});