Skip to content

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

fix: handle non-string message content in TutorBot chat

WeDone583e8aa939cf
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
index 21812fd6d..a4c9531fe 100644
--- a/deeptutor/services/tutorbot/manager.py
+++ b/deeptutor/services/tutorbot/manager.py
@@ -728,6 +728,15 @@ class TutorBotManager:
if data.get("_type") == "metadata":
continue
if data.get("role") in ("user", "assistant") and data.get("content"):
+ raw = data["content"]
+ if isinstance(raw, list):
+ data["content"] = " ".join(
+ p.get("text", "") if isinstance(p, dict) else str(p)
+ for p in raw
+ )
+ elif not isinstance(raw, str):
+ data["content"] = str(raw)
+ data.pop("reasoning_content", None)
all_messages.append(data)
except Exception:
continue
@@ -765,7 +774,16 @@ class TutorBotManager:
if data.get("_type") == "metadata":
continue
if data.get("role") in ("user", "assistant") and data.get("content"):
- last_msg = data["content"]
+ raw = data["content"]
+ if isinstance(raw, list):
+ last_msg = " ".join(
+ p.get("text", "") if isinstance(p, dict) else str(p)
+ for p in raw
+ )
+ elif isinstance(raw, str):
+ last_msg = raw
+ else:
+ last_msg = str(raw)
except Exception:
pass
diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx
index 977064e07..00342a0ec 100644
--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx
+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx
@@ -10,6 +10,10 @@ import { firstParam } from "@/lib/route-params";
import AssistantResponse from "@/components/common/AssistantResponse";
import { SimpleComposerInput } from "@/components/chat/home/SimpleComposerInput";
import { downloadChatMarkdown } from "@/lib/chat-export";
+import {
+ normalizeMessageContent,
+ type RawMessageContent,
+} from "@/lib/message-content";
import type { MessageItem } from "@/context/UnifiedChatContext";
import type {
NotebookSaveMessage,
@@ -125,22 +129,26 @@ export default function BotChatPage() {
fetch(apiUrl(`/api/v1/tutorbot/${botId}/history`))
.then((r) => (r.ok ? r.json() : []))
- .then((history: { role: string; content: string }[]) => {
- const restored: ChatMsg[] = history
- .filter((m) => m.role === "user" || m.role === "assistant")
- .map((m) => ({
- role: m.role as "user" | "assistant",
- content: m.content,
- }));
- if (restored.length) {
- setMessages(restored);
- // Markdown/KaTeX inside AssistantResponse can grow the container after
- // the first paint — re-snap a few times so we land at the bottom.
- requestAnimationFrame(() => scrollToBottom("instant"));
- window.setTimeout(() => scrollToBottom("instant"), 80);
- window.setTimeout(() => scrollToBottom("instant"), 250);
- }
- })
+ .then(
+ (history: {
+ role: string;
+ content: RawMessageContent;
+ reasoning_content?: unknown;
+ }[]) => {
+ const restored: ChatMsg[] = history
+ .filter((m) => m.role === "user" || m.role === "assistant")
+ .map((m) => ({
+ role: m.role as "user" | "assistant",
+ content: normalizeMessageContent(m.content),
+ }));
+ if (restored.length) {
+ setMessages(restored);
+ requestAnimationFrame(() => scrollToBottom("instant"));
+ window.setTimeout(() => scrollToBottom("instant"), 80);
+ window.setTimeout(() => scrollToBottom("instant"), 250);
+ }
+ },
+ )
.catch(() => {});
}, [botId, scrollToBottom]);
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 8924fa10f..455d96647 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -4,6 +4,7 @@ import { Check, Pencil, Trash2 } from "lucide-react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { type SessionSummary } from "@/lib/session-api";
+import { normalizeMessageContent, truncateText } from "@/lib/message-content";
type SessionRuntimeStatus =
| "idle"
@@ -361,7 +362,7 @@ export default function SessionList({
)}
{!isEditing && (
<div className="mt-0.5 line-clamp-1 text-[11px] leading-tight text-[var(--muted-foreground)]">
- {session.last_message ||
+ {truncateText(normalizeMessageContent(session.last_message), 120) ||
relativeTime(session.updated_at)}
</div>
)}
diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsx
index ab4830031..59272f49a 100644
--- a/web/components/chat/HistorySessionPicker.tsx
+++ b/web/components/chat/HistorySessionPicker.tsx
@@ -11,6 +11,7 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { listSessions, type SessionSummary } from "@/lib/session-api";
+import { normalizeMessageContent, truncateText } from "@/lib/message-content";
export interface SelectedHistorySession {
sessionId: string;
@@ -74,7 +75,7 @@ export default function HistorySessionPicker({
if (!keyword) return sessions;
return sessions.filter((session) => {
const title = String(session.title || "").toLowerCase();
- const lastMessage = String(session.last_message || "").toLowerCase();
+ const lastMessage = normalizeMessageContent(session.last_message).toLowerCase();
return title.includes(keyword) || lastMessage.includes(keyword);
});
}, [query, sessions]);
@@ -191,7 +192,7 @@ export default function HistorySessionPicker({
</div>
{session.last_message ? (
<p className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">
- {session.last_message}
+ {truncateText(normalizeMessageContent(session.last_message), 200)}
</p>
) : null}
<div className="mt-2 flex items-center gap-3 text-[11px] text-[var(--muted-foreground)]/85">
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 5cfe6e651..69efcfc43 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -18,6 +18,7 @@ import type { StreamEvent, ChatMessage } from "@/lib/unified-ws";
import { UnifiedWSClient } from "@/lib/unified-ws";
import { getSession, type SessionMessage } from "@/lib/session-api";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
+import { normalizeMessageContent } from "@/lib/message-content";
import { shouldAppendEventContent } from "@/lib/stream";
type SessionRuntimeStatus =
@@ -550,30 +551,33 @@ export function UnifiedChatProvider({
const hydrateMessages = useCallback(
(messages: SessionMessage[]): MessageItem[] => {
- // System messages (e.g. quiz follow-up grounding context written by the
- // backend turn runtime) are LLM-only and must not surface in the chat UI.
return messages
.filter((message) => message.role !== "system")
- .map((message) => ({
- role: message.role,
- content:
- message.role === "assistant"
- ? normalizeMarkdownForDisplay(message.content)
- : message.content,
- capability: message.capability || "",
- events: Array.isArray(message.events) ? message.events : [],
- attachments: Array.isArray(message.attachments)
- ? message.attachments.map((item) => ({
- type: item.type,
- filename: item.filename,
- base64: item.base64,
- url: item.url,
- mime_type: item.mime_type,
- id: item.id,
- extracted_text: item.extracted_text,
- }))
- : [],
- }));
+ .map((message) => {
+ const raw = normalizeMessageContent(
+ message.content as unknown,
+ );
+ return {
+ role: message.role,
+ content:
+ message.role === "assistant"
+ ? normalizeMarkdownForDisplay(raw)
+ : raw,
+ capability: message.capability || "",
+ events: Array.isArray(message.events) ? message.events : [],
+ attachments: Array.isArray(message.attachments)
+ ? message.attachments.map((item) => ({
+ type: item.type,
+ filename: item.filename,
+ base64: item.base64,
+ url: item.url,
+ mime_type: item.mime_type,
+ id: item.id,
+ extracted_text: item.extracted_text,
+ }))
+ : [],
+ };
+ });
},
[],
);
diff --git a/web/lib/message-content.ts b/web/lib/message-content.ts
new file mode 100644
index 000000000..80c79935a
--- /dev/null
+++ b/web/lib/message-content.ts
@@ -0,0 +1,37 @@
+export type MessageContentItem = {
+ type: string;
+ text?: string;
+ url?: string;
+ alt?: string;
+};
+
+export type RawMessageContent =
+ | string
+ | MessageContentItem[]
+ | null
+ | undefined
+ | unknown;
+
+export function normalizeMessageContent(content: RawMessageContent): string {
+ if (content == null) return "";
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ return content
+ .map((item) => {
+ if (!item || typeof item !== "object") return String(item);
+ if (item.type === "image" || item.type === "image_url") {
+ return item.alt || item.text || "[image]";
+ }
+ return item.text ?? String(item);
+ })
+ .filter(Boolean)
+ .join(" ");
+ }
+ return String(content);
+}
+
+export function truncateText(text: string, maxLength: number = 100): string {
+ if (!text) return "";
+ if (text.length <= maxLength) return text;
+ return text.substring(0, maxLength) + "…";
+}