Skip to content

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

feat(tutorbot): Channels tab, Telegram UI, API channel reload, token reveal (#338)

Srinivas R Kulkarni0166009c0b3e
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
index 58f0b4369..cfe5ff5bc 100644
--- a/deeptutor/api/routers/tutorbot.py
+++ b/deeptutor/api/routers/tutorbot.py
@@ -124,9 +124,14 @@ async def get_bot(bot_id: str):
cfg = mgr.load_bot_config(bot_id)
if cfg:
return {
- "bot_id": bot_id, "name": cfg.name, "description": cfg.description,
- "persona": cfg.persona, "channels": list(cfg.channels.keys()),
- "model": cfg.model, "running": False, "started_at": None,
+ "bot_id": bot_id,
+ "name": cfg.name,
+ "description": cfg.description,
+ "persona": cfg.persona,
+ "channels": cfg.channels,
+ "model": cfg.model,
+ "running": False,
+ "started_at": None,
}
raise HTTPException(status_code=404, detail="Bot not found")
@@ -147,26 +152,64 @@ async def destroy_bot(bot_id: str):
return {"bot_id": bot_id, "destroyed": True}
+def _stopped_bot_dict(bot_id: str, cfg: BotConfig) -> dict:
+ return {
+ "bot_id": bot_id,
+ "name": cfg.name,
+ "description": cfg.description,
+ "persona": cfg.persona,
+ "channels": cfg.channels,
+ "model": cfg.model,
+ "running": False,
+ "started_at": None,
+ }
+
+
@router.patch("/{bot_id}")
async def update_bot(bot_id: str, payload: UpdateBotRequest):
mgr = get_tutorbot_manager()
instance = mgr.get_bot(bot_id)
- if not instance:
+ if instance:
+ if payload.name is not None:
+ instance.config.name = payload.name
+ if payload.description is not None:
+ instance.config.description = payload.description
+ if payload.persona is not None:
+ instance.config.persona = payload.persona
+ if payload.channels is not None:
+ instance.config.channels = payload.channels
+ if payload.model is not None:
+ instance.config.model = payload.model
+
+ mgr.save_bot_config(bot_id, instance.config)
+ if payload.channels is not None:
+ try:
+ await mgr.reload_channels(bot_id)
+ except Exception:
+ logger.exception("reload_channels failed for bot '%s'", bot_id)
+ raise HTTPException(
+ status_code=500,
+ detail="Channels saved but failed to restart listeners; try stopping and starting the bot.",
+ ) from None
+ return instance.to_dict()
+
+ cfg = mgr.load_bot_config(bot_id)
+ if not cfg:
raise HTTPException(status_code=404, detail="Bot not found")
if payload.name is not None:
- instance.config.name = payload.name
+ cfg.name = payload.name
if payload.description is not None:
- instance.config.description = payload.description
+ cfg.description = payload.description
if payload.persona is not None:
- instance.config.persona = payload.persona
+ cfg.persona = payload.persona
if payload.channels is not None:
- instance.config.channels = payload.channels
+ cfg.channels = payload.channels
if payload.model is not None:
- instance.config.model = payload.model
+ cfg.model = payload.model
- mgr.save_bot_config(bot_id, instance.config)
- return instance.to_dict()
+ mgr.save_bot_config(bot_id, cfg)
+ return _stopped_bot_dict(bot_id, cfg)
# ── Workspace file endpoints ──────────────────────────────────
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index f239e3702..97ad46300 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -67,7 +67,7 @@ class TutorBotInstance:
"name": self.config.name,
"description": self.config.description,
"persona": self.config.persona,
- "channels": list(self.config.channels.keys()),
+ "channels": self.config.channels,
"model": self.config.model,
"running": self.running,
"started_at": self.started_at.isoformat(),
@@ -453,6 +453,64 @@ class TutorBotManager:
logger.info("TutorBot '%s' stopped", bot_id)
return True
+ async def reload_channels(self, bot_id: str) -> None:
+ """Restart channel listeners from ``instance.config.channels`` (same MessageBus).
+
+ Cancels only ``tutorbot:{bot_id}:ch:*`` tasks; agent loop and outbound router keep running.
+ """
+ instance = self._bots.get(bot_id)
+ if not instance or not instance.running:
+ return
+
+ ch_prefix = f"tutorbot:{bot_id}:ch:"
+ to_remove = [t for t in instance.tasks if (t.get_name() or "").startswith(ch_prefix)]
+ for t in to_remove:
+ if not t.done():
+ t.cancel()
+ for t in to_remove:
+ try:
+ await asyncio.wait_for(asyncio.shield(t), timeout=5.0)
+ except (asyncio.CancelledError, asyncio.TimeoutError):
+ pass
+ instance.tasks = [t for t in instance.tasks if t not in to_remove]
+
+ if instance.channel_manager:
+ try:
+ await instance.channel_manager.stop_all()
+ except Exception:
+ logger.exception("Error stopping channels before reload for bot '%s'", bot_id)
+
+ instance.channel_manager = None
+ instance.channel_bindings.clear()
+
+ bus = instance.agent_loop.bus
+ config = instance.config
+ channel_manager = None
+ if config.channels:
+ try:
+ from deeptutor.tutorbot.channels.manager import ChannelManager
+ from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+ channels_config = ChannelsConfig(**config.channels)
+ channel_manager = ChannelManager(channels_config, bus)
+ if not channel_manager.channels:
+ channel_manager = None
+ except Exception:
+ logger.exception("Failed to reload channels for bot '%s'", bot_id)
+ raise
+
+ instance.channel_manager = channel_manager
+ if channel_manager:
+ for ch_name, ch in channel_manager.channels.items():
+ ch_task = asyncio.create_task(
+ ch.start(), name=f"tutorbot:{bot_id}:ch:{ch_name}",
+ )
+ instance.tasks.append(ch_task)
+ logger.info(
+ "Reloaded channels for bot '%s': %s",
+ bot_id, list(channel_manager.channels.keys()),
+ )
+
# ── Listing & discovery ───────────────────────────────────────
def _discover_bot_ids(self) -> set[str]:
@@ -473,7 +531,9 @@ class TutorBotManager:
result: dict[str, dict[str, Any]] = {}
for inst in self._bots.values():
- result[inst.bot_id] = inst.to_dict()
+ row = inst.to_dict()
+ row["channels"] = list(inst.config.channels.keys())
+ result[inst.bot_id] = row
for bid in self._discover_bot_ids():
if bid in result:
diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.py
index 5ccb75d63..47009b3a8 100644
--- a/tests/api/test_tutorbot_router.py
+++ b/tests/api/test_tutorbot_router.py
@@ -70,7 +70,7 @@ def _make_fake_manager(existing: dict | None = None):
instance.to_dict.return_value = {
"bot_id": bot_id,
"name": config.name,
- "channels": list(config.channels.keys()),
+ "channels": config.channels,
"running": True,
}
return instance
@@ -251,3 +251,113 @@ class TestCreateBotExplicitClearSemantics:
assert resp.status_code == 200
assert saved["config"].description == "Disk Desc"
+
+
+class TestGetBotStoppedReturnsFullChannels:
+ """GET /{bot_id} must return nested channel config when the bot is not running."""
+
+ def test_get_stopped_bot_includes_telegram_config(self, monkeypatch):
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ channels = {"telegram": {"enabled": True, "token": "x:y", "allow_from": ["1"]}}
+
+ class FakeMgr:
+ def get_bot(self, bot_id: str):
+ return None
+
+ def load_bot_config(self, bot_id: str) -> BotConfig | None:
+ return BotConfig(name="b", channels=channels)
+
+ 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)
+
+ resp = client.get("/api/v1/tutorbot/b")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["channels"] == channels
+ assert body["running"] is False
+
+
+class TestPatchBotStoppedAndRunning:
+ """PATCH must work when the bot is stopped; running + channels triggers reload."""
+
+ def test_patch_stopped_saves_and_returns_channels(self, monkeypatch):
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ saved_cfg: list[BotConfig | None] = []
+
+ class FakeMgr:
+ def get_bot(self, bot_id: str):
+ return None
+
+ def load_bot_config(self, bot_id: str) -> BotConfig | None:
+ return BotConfig(
+ name="b",
+ channels={"telegram": {"enabled": False, "token": ""}},
+ )
+
+ def save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ saved_cfg.append(config)
+
+ 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)
+
+ new_ch = {"telegram": {"enabled": True, "token": "1:2"}}
+ resp = client.patch("/api/v1/tutorbot/b", json={"channels": new_ch})
+ assert resp.status_code == 200
+ assert resp.json()["channels"] == new_ch
+ assert len(saved_cfg) == 1
+ assert saved_cfg[0].channels == new_ch
+
+ def test_patch_running_channels_calls_reload(self, monkeypatch):
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ reloaded: list[bool] = []
+
+ class FakeInst:
+ def __init__(self):
+ self.config = BotConfig(name="b", channels={"telegram": {"enabled": True}})
+ self._running = True
+
+ @property
+ def running(self) -> bool:
+ return self._running
+
+ def to_dict(self):
+ return {
+ "bot_id": "b",
+ "name": self.config.name,
+ "channels": self.config.channels,
+ "running": True,
+ }
+
+ inst = FakeInst()
+
+ class FakeMgr:
+ def get_bot(self, bot_id: str):
+ return inst if bot_id == "b" else None
+
+ def save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ pass
+
+ async def reload_channels(self, bot_id: str) -> None:
+ reloaded.append(True)
+
+ 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)
+
+ resp = client.patch("/api/v1/tutorbot/b", json={"channels": {"telegram": {"enabled": False}}})
+ assert resp.status_code == 200
+ assert reloaded == [True]
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index 75b97fb56..452e49b33 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -3,6 +3,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Bot,
+ Eye,
+ EyeOff,
FileText,
Heart,
Loader2,
@@ -11,6 +13,7 @@ import {
Play,
Plus,
Save,
+ Settings2,
Square,
Trash2,
X,
@@ -31,7 +34,8 @@ interface BotInfo {
name: string;
description: string;
persona: string;
- channels: string[];
+ /** Compact list from `GET /tutorbot`; full dict from `GET /tutorbot/{id}` */
+ channels: string[] | Record<string, unknown>;
model: string | null;
running: boolean;
started_at: string | null;
@@ -43,7 +47,7 @@ interface SoulTemplate {
content: string;
}
-type Tab = "bots" | "profiles" | "souls";
+type Tab = "bots" | "profiles" | "channels" | "souls";
const BOT_FILES = ["SOUL.md", "USER.md", "TOOLS.md", "AGENTS.md", "HEARTBEAT.md"] as const;
type BotFile = (typeof BOT_FILES)[number];
@@ -106,6 +110,7 @@ export default function AgentsPage() {
{([
{ key: "bots" as Tab, label: t("Bots"), icon: Bot },
{ key: "profiles" as Tab, label: t("Profiles"), icon: FileText },
+ { key: "channels" as Tab, label: t("Channels"), icon: Settings2 },
{ key: "souls" as Tab, label: t("Souls"), icon: Heart },
]).map((tab) => {
const Icon = tab.icon;
@@ -138,6 +143,8 @@ export default function AgentsPage() {
/>
) : activeTab === "profiles" ? (
<ProfilesTab bots={bots} loading={loading} onToast={setToast} />
+ ) : activeTab === "channels" ? (
+ <ChannelsTab bots={bots} loading={loading} onToast={setToast} onReload={loadBots} />
) : (
<SoulsTab souls={souls} onReload={loadSouls} onToast={setToast} />
)}
@@ -146,6 +153,278 @@ export default function AgentsPage() {
);
}
+/* ── Channels tab (Telegram + globals) ─────────────────── */
+
+const DEFAULT_TELEGRAM = {
+ enabled: false,
+ token: "",
+ allow_from: [] as string[],
+ proxy: "" as string,
+ reply_to_message: false,
+ group_policy: "mention" as "open" | "mention",
+};
+
+function normalizeChannelsDict(raw: Record<string, unknown> | undefined): Record<string, unknown> {
+ const r = { ...(raw ?? {}) };
+ const tg = (r.telegram as Record<string, unknown> | undefined) ?? {};
+ const allowRaw = tg.allow_from;
+ const allow_from = Array.isArray(allowRaw) ? allowRaw.map(String) : [];
+ return {
+ ...r,
+ send_progress: r.send_progress !== false,
+ send_tool_hints: !!r.send_tool_hints,
+ telegram: {
+ ...DEFAULT_TELEGRAM,
+ ...tg,
+ allow_from,
+ group_policy: tg.group_policy === "open" ? "open" : "mention",
+ },
+ };
+}
+
+function ChannelsTab({
+ bots,
+ loading,
+ onToast,
+ onReload,
+}: {
+ bots: BotInfo[];
+ loading: boolean;
+ onToast: (msg: string) => void;
+ onReload: () => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const [selectedBot, setSelectedBot] = useState("");
+ const [channels, setChannels] = useState<Record<string, unknown>>({});
+ const [loadingDetail, setLoadingDetail] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [showToken, setShowToken] = useState(false);
+
+ useEffect(() => {
+ if (bots.length > 0 && !selectedBot) setSelectedBot(bots[0].bot_id);
+ }, [bots, selectedBot]);
+
+ useEffect(() => {
+ setShowToken(false);
+ }, [selectedBot]);
+
+ const loadDetail = useCallback(async (bid: string) => {
+ if (!bid) return;
+ setLoadingDetail(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`));
+ if (!res.ok) return;
+ const data = await res.json();
+ setChannels(normalizeChannelsDict(data.channels as Record<string, unknown> | undefined));
+ } finally {
+ setLoadingDetail(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (selectedBot) void loadDetail(selectedBot);
+ }, [selectedBot, loadDetail]);
+
+ const tg = (channels.telegram as typeof DEFAULT_TELEGRAM) ?? DEFAULT_TELEGRAM;
+
+ const setTg = (patch: Partial<typeof DEFAULT_TELEGRAM>) => {
+ setChannels((prev) => ({
+ ...prev,
+ telegram: { ...DEFAULT_TELEGRAM, ...(prev.telegram as object), ...patch },
+ }));
+ };
+
+ const buildPayload = (): Record<string, unknown> => {
+ const allow_from = Array.isArray(tg.allow_from)
+ ? tg.allow_from.map(String)
+ : [];
+ const proxyVal = typeof tg.proxy === "string" && tg.proxy.trim() ? tg.proxy.trim() : null;
+ const next: Record<string, unknown> = { ...channels };
+ next.send_progress = !!channels.send_progress;
+ next.send_tool_hints = !!channels.send_tool_hints;
+ next.telegram = {
+ enabled: !!tg.enabled,
+ token: String(tg.token ?? ""),
+ allow_from,
+ proxy: proxyVal,
+ reply_to_message: !!tg.reply_to_message,
+ group_policy: tg.group_policy === "open" ? "open" : "mention",
+ };
+ return next;
+ };
+
+ const save = async () => {
+ if (!selectedBot) return;
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ channels: buildPayload() }),
+ });
+ if (res.ok) {
+ onToast(t("Channels saved"));
+ await onReload();
+ await loadDetail(selectedBot);
+ } else {
+ const err = await res.json().catch(() => ({}));
+ onToast((err as { detail?: string }).detail ?? t("Save failed"));
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex min-h-[320px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ );
+ }
+
+ if (bots.length === 0) {
+ return (
+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <p className="text-[14px] font-medium text-[var(--foreground)]">{t("No bots to configure")}</p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ {t("Create a bot first in the Bots tab.")}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-center gap-3">
+ <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">{t("Bot")}</label>
+ <select
+ value={selectedBot}
+ onChange={(e) => setSelectedBot(e.target.value)}
+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ >
+ {bots.map((b) => (
+ <option key={b.bot_id} value={b.bot_id}>
+ {b.name} ({b.bot_id})
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ onClick={() => void save()}
+ disabled={saving || loadingDetail}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"
+ >
+ {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
+ {t("Save")}
+ </button>
+ </div>
+
+ {loadingDetail ? (
+ <div className="flex justify-center py-8">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : (
+ <>
+ <div className="rounded-xl border border-[var(--border)] p-4 space-y-3">
+ <h3 className="text-[13px] font-medium text-[var(--foreground)]">{t("Delivery")}</h3>
+ <label className="flex items-center gap-2 text-[13px]">
+ <input
+ type="checkbox"
+ checked={!!channels.send_progress}
+ onChange={(e) => setChannels((c) => ({ ...c, send_progress: e.target.checked }))}
+ />
+ {t("Stream progress text to channels")}
+ </label>
+ <label className="flex items-center gap-2 text-[13px]">
+ <input
+ type="checkbox"
+ checked={!!channels.send_tool_hints}
+ onChange={(e) => setChannels((c) => ({ ...c, send_tool_hints: e.target.checked }))}
+ />
+ {t("Stream tool hints to channels")}
+ </label>
+ </div>
+
+ <div className="rounded-xl border border-[var(--border)] p-4 space-y-3">
+ <h3 className="text-[13px] font-medium text-[var(--foreground)]">{t("Telegram")}</h3>
+ <label className="flex items-center gap-2 text-[13px]">
+ <input
+ type="checkbox"
+ checked={!!tg.enabled}
+ onChange={(e) => setTg({ enabled: e.target.checked })}
+ />
+ {t("Enabled")}
+ </label>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Bot token")}</label>
+ <div className="relative">
+ <input
+ type={showToken ? "text" : "password"}
+ autoComplete="off"
+ value={tg.token}
+ onChange={(e) => setTg({ token: e.target.value })}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent py-2 pl-3 pr-10 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
+ />
+ <button
+ type="button"
+ onClick={() => setShowToken((v) => !v)}
+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={showToken ? t("Hide token") : t("Show token")}
+ title={showToken ? t("Hide token") : t("Show token")}
+ >
+ {showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
+ </button>
+ </div>
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Allowed user IDs (one per line)")}</label>
+ <textarea
+ value={tg.allow_from.join("\n")}
+ onChange={(e) =>
+ setTg({
+ allow_from: e.target.value.split("\n").map((s) => s.trim()).filter(Boolean),
+ })
+ }
+ rows={4}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Proxy URL")} <span className="font-normal opacity-60">{t("(optional)")}</span></label>
+ <input
+ value={tg.proxy ?? ""}
+ onChange={(e) => setTg({ proxy: e.target.value })}
+ placeholder="http://127.0.0.1:7890"
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ <label className="flex items-center gap-2 text-[13px]">
+ <input
+ type="checkbox"
+ checked={!!tg.reply_to_message}
+ onChange={(e) => setTg({ reply_to_message: e.target.checked })}
+ />
+ {t("Reply to the user message (vs new message)")}
+ </label>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">{t("Group policy")}</label>
+ <select
+ value={tg.group_policy}
+ onChange={(e) => setTg({ group_policy: e.target.value as "open" | "mention" })}
+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
+ >
+ <option value="mention">{t("Mention only")}</option>
+ <option value="open">{t("Open (all messages)")}</option>
+ </select>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
/* ── Bots Tab ───────────────────────────────────────────── */
function BotsTab({