DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: preserve raw content during Chinese Markdown streaming (#1178)
Boooobby4069f900cc0b
diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 4d3a11755..5bdf7a523 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -10,6 +10,7 @@ from dataclasses import dataclass, fieldimport loggingimport refrom typing import TYPE_CHECKING, Any, Literal+import unicodedatafrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.llm.utils import clean_thinking_tags@@ -118,6 +119,150 @@ def _assemble_persisted_answer()+_FENCED_CODE_BLOCK_RE = re.compile(r"```[\s\S]*?```")+_INLINE_CODE_SPAN_RE = re.compile(r"`[^`\n]*`")+_MATH_SPAN_RE = re.compile(+ r"\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$\$[\s\S]*?\$\$|\$(?!\s)(?:\\.|[^$\n])*?(?<!\s)\$"+)+++def _is_escaped(text: str, index: int) -> bool:+ """Whether the character at index has an odd-length backslash prefix."""+ slash_count = 0+ cursor = index - 1+ while cursor >= 0 and text[cursor] == "\\":+ slash_count += 1+ cursor -= 1+ return slash_count % 2 == 1+++def _is_emphasis_normal_character(value: str | None) -> bool:+ return bool(value and (value.isalpha() or value.isnumeric()))+++def _is_emphasis_punctuation_or_symbol(value: str | None) -> bool:+ return bool(value and unicodedata.category(value)[0] in {"P", "S"})+++def _can_open_emphasis(line: str, index: int, marker: str) -> bool:+ before = line[index - 1] if index else None+ after_index = index + len(marker)+ after = line[after_index] if after_index < len(line) else None+ if after is None or after.isspace():+ return False+ if _is_emphasis_punctuation_or_symbol(after):+ return (+ before is None+ or before.isspace()+ or _is_emphasis_punctuation_or_symbol(before)+ or _is_emphasis_normal_character(before)+ )+ return True+++def _can_close_emphasis(line: str, index: int, marker: str) -> bool:+ before = line[index - 1] if index else None+ after_index = index + len(marker)+ after = line[after_index] if after_index < len(line) else None+ if before is None or before.isspace():+ return False+ if _is_emphasis_punctuation_or_symbol(before):+ return (+ after is None+ or after.isspace()+ or _is_emphasis_punctuation_or_symbol(after)+ or _is_emphasis_normal_character(after)+ )+ return True+++def _paired_emphasis_delimiters(line: str) -> list[tuple[str, int, int]]:+ """Return only syntactically plausible (marker, left opener, right closer) pairs."""+ openers: dict[str, list[int]] = {"*": [], "**": []}+ pairs: list[tuple[str, int, int]] = []+ cursor = 0+ while cursor < len(line):+ if line[cursor] != "*" or _is_escaped(line, cursor):+ cursor += 1+ continue+ run_end = cursor+ while run_end < len(line) and line[run_end] == "*":+ run_end += 1+ marker = line[cursor:run_end]+ if marker in openers:+ can_open = _can_open_emphasis(line, cursor, marker)+ can_close = _can_close_emphasis(line, cursor, marker)+ if can_close and openers[marker]:+ pairs.append((marker, openers[marker].pop(), cursor))+ elif can_open:+ openers[marker].append(cursor)+ cursor = run_end+ return pairs+++def _repair_chinese_emphasis_line(line: str) -> str:+ insertions: set[int] = set()+ for marker, left_opener, right_closer in _paired_emphasis_delimiters(line):+ left_before = line[left_opener - 1] if left_opener else None+ left_inside = (+ line[left_opener + len(marker)] if left_opener + len(marker) < len(line) else None+ )+ right_inside = line[right_closer - 1] if right_closer else None+ right_after_index = right_closer + len(marker)+ right_after = line[right_after_index] if right_after_index < len(line) else None++ left_needs_space = _is_emphasis_normal_character(+ left_before+ ) and _is_emphasis_punctuation_or_symbol(left_inside)+ right_needs_space = _is_emphasis_punctuation_or_symbol(+ right_inside+ ) and _is_emphasis_normal_character(right_after)+ if left_needs_space:+ insertions.add(left_opener)+ if right_needs_space:+ insertions.add(right_after_index)++ # Only mirror a required repair onto the other marker in THIS pair.+ if left_needs_space != right_needs_space:+ if _is_emphasis_normal_character(right_inside) and _is_emphasis_normal_character(+ right_after+ ):+ insertions.add(right_after_index)+ elif _is_emphasis_normal_character(left_before) and _is_emphasis_normal_character(+ left_inside+ ):+ insertions.add(left_opener)++ for index in sorted(insertions, reverse=True):+ line = f"{line[:index]} {line[index:]}"+ return line+++def _repair_chinese_emphasis_for_persistence(content: str, language: str) -> str:+ """Normalize CJK Markdown emphasis before the assistant answer is stored.++ This deliberately runs only for Chinese model output and leaves code and+ mathematics literal, so the persisted source matches its valid rendering.+ """+ if not content or not str(language or "").lower().startswith("zh"):+ return content+ protected: list[str] = []++ def mask(match: re.Match[str]) -> str:+ protected.append(match.group(0))+ return f"\x00CJK_PROTECTED_{len(protected) - 1}\x00"++ masked = _FENCED_CODE_BLOCK_RE.sub(mask, content)+ masked = _MATH_SPAN_RE.sub(mask, masked)+ masked = _INLINE_CODE_SPAN_RE.sub(mask, masked)+ repaired = "\n".join(_repair_chinese_emphasis_line(line) for line in masked.split("\n"))+ return re.sub(+ r"\x00CJK_PROTECTED_(\d+)\x00",+ lambda match: protected[int(match.group(1))],+ repaired,+ )++def _stamp_ask_user_content_offset(payload_event: dict[str, Any],assistant_content: str,diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 9ff62e8d3..3aa729ed0 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -42,6 +42,7 @@ from .._turn_runtime_shared import (_reading_references,_reading_viewport,_reading_workspace_id,+ _repair_chinese_emphasis_for_persistence,_request_snapshot_metadata,_resolve_selection_tutor_context,_resolve_turn_outcome,@@ -836,8 +837,13 @@ class TurnExecutor:await fill_preview_text(generated_attachments)# The persisted answer is the captured content minus any narration- # rounds (their text stayed in the trace, never the answer).- assistant_content = _persisted_answer()+ # rounds (their text stayed in the trace, never the answer). Apply+ # the CJK Markdown repair only after every streamed segment has+ # arrived, so no incomplete response is ever rewritten.+ assistant_content = _repair_chinese_emphasis_for_persistence(+ _persisted_answer(),+ str(payload.get("language", "en") or "en"),+ )# Assistant continues the same branch as the user message it# answers. If we just persisted a new user row we chain offdiff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex 497cbd446..a1e6a4a8d 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -15,6 +15,7 @@ from deeptutor.services.session.turn_runtime import (_format_followup_question_context,_format_selection_tutor_context,_narration_marker_call_id,+ _repair_chinese_emphasis_for_persistence,_resolve_selection_tutor_context,_should_capture_assistant_content,_stamp_ask_user_content_offset,@@ -118,6 +119,33 @@ class TestNarrationMarkerCallId:class TestAssemblePersistedAnswer:+ def test_repairs_chinese_emphasis_boundaries_before_persistence(self) -> None:+ assert (+ _repair_chinese_emphasis_for_persistence("中文*,重点*内容", "zh")+ == "中文 *,重点* 内容"+ )+ assert _repair_chinese_emphasis_for_persistence("**“你好”**啊", "zh-CN") == "**“你好”** 啊"+ assert _repair_chinese_emphasis_for_persistence("中文*,重点*", "en") == "中文*,重点*"++ def test_does_not_change_inner_whitespace_or_literal_stars(self) -> None:+ inputs = [+ "* 重点 *",+ "** 重点 **",+ "*重点 *",+ "** 重点**",+ "*重点 内容*",+ "前言 * 第一项 * 与 * 第二项 * 后记",+ "Use * as multiplication *",+ r"\* 重点 \*",+ "说明 * 这里不是完整强调,后面有 *正常内容*",+ ]+ for content in inputs:+ assert _repair_chinese_emphasis_for_persistence(content, "zh") == content++ def test_preserves_code_math_and_nested_emphasis(self) -> None:+ content = "`中文*,重点*`\n$中文*,重点*$\n中文***,重点***内容"+ assert _repair_chinese_emphasis_for_persistence(content, "zh") == content+def test_continuation_preserves_exact_visible_boundary(self) -> None:segments = [("round-part-1", "Part one. "),diff --git a/web/app/(workspace)/books/components/BookChatPanel.tsx b/web/app/(workspace)/books/components/BookChatPanel.tsxindex 1b7deaa49..deac0257e 100644--- a/web/app/(workspace)/books/components/BookChatPanel.tsx+++ b/web/app/(workspace)/books/components/BookChatPanel.tsx@@ -500,6 +500,7 @@ export default function BookChatPanel({{m.role === "assistant" ? (<AssistantResponsecontent={m.content}+ language={book?.language || appLanguage}className="text-sm leading-relaxed"isStreaming={Boolean(m.streaming)}/>diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsxindex 2d8b34ed9..72619c91b 100644--- a/web/components/common/AssistantResponse.tsx+++ b/web/components/common/AssistantResponse.tsx@@ -9,6 +9,7 @@ import type { StreamEvent } from "@/features/chat/model/protocol";import { useWatching } from "@/context/WatchingContext";import {hasVisibleMarkdownContent,+ repairChineseEmphasis,repairMalformedStrongEmphasis,stripArtifactAnnotations,} from "@/lib/markdown-display";@@ -36,6 +37,7 @@ interface AssistantResponseProps {readingMaterialId?: string;readingMaterialRevision?: number;events?: StreamEvent[];+ language?: string;}function AssistantResponseImpl({@@ -45,6 +47,7 @@ function AssistantResponseImpl({readingMaterialId,readingMaterialRevision,events,+ language,}: AssistantResponseProps) {const displayContent = useSmoothStreamText(content, isStreaming);// A locator becomes interactive only when this turn's persisted reading-tool@@ -135,7 +138,12 @@ function AssistantResponseImpl({/>);}- const repairedContent = repairMalformedStrongEmphasis(segment.content);+ const repairedContent = isStreaming+ ? repairMalformedStrongEmphasis(segment.content)+ : repairChineseEmphasis(+ repairMalformedStrongEmphasis(segment.content),+ language,+ );if (!hasVisibleMarkdownContent(repairedContent)) {return <Fragment key={`text-${index}`} />;diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex aaba10f98..1901c16ab 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -33,7 +33,10 @@ import {updateSessionTitle,type SessionMessage,} from "@/lib/session-api";-import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";+import {+ normalizeMarkdownForDisplay,+ repairChineseEmphasis,+} from "@/lib/markdown-display";import { normalizeMessageContent } from "@/lib/message-content";import {buildVisiblePath,@@ -205,6 +208,9 @@ export interface MessageItem {id?: number;role: "user" | "assistant" | "system";content: string;+ /** Original model text accumulated during a live stream. Kept separate from+ * `content`, which may be Markdown-normalized for display. */+ rawContent?: string;capability?: string;events?: StreamEvent[];attachments?: MessageAttachment[];@@ -605,6 +611,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {id: nextOptimisticId(),role: "assistant",content: "",+ rawContent: "",events: [],capability: session.activeCapability || "",parentMessageId: tip?.id ?? null,@@ -641,6 +648,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {id: nextOptimisticId(),role: "assistant",content: "",+ rawContent: "",events: [],capability: session.activeCapability || "",parentMessageId: last?.id ?? null,@@ -655,19 +663,22 @@ function reducer(state: ProviderState, action: Action): ProviderState {return state;}const events = [...(last?.events || []), action.event];- let content = last?.content || "";+ const language = session.language;+ let rawContent = last?.rawContent ?? last?.content ?? "";if (isNarrationMarker(action.event)) {// A round just resolved as narration (preamble before a tool call):// drop its already-streamed text from the answer — it stays in the- // trace. Recomputing is cheap here (only fires per narration round).- content = recomputeAnswerContent(events);+ // trace. Recompute from immutable event content, never from display text.+ rawContent = recomputeAnswerContent(events);} else if (shouldAppendEventContent(action.event)) {- content += action.event.content;+ rawContent += action.event.content;}+ const content = repairChineseEmphasis(rawContent, language);const capability = last?.capability || session.activeCapability || "";msgs[msgs.length - 1] = {...(last || { role: "assistant", content: "" }),content,+ rawContent,events,capability,};diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 7cc578b2d..75d48697f 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -545,6 +545,7 @@ export const AssistantMessage = memo(function AssistantMessage({{showResearchBody ? (<AssistantResponsecontent={msg.content}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -570,6 +571,7 @@ export const AssistantMessage = memo(function AssistantMessage({{msg.content ? (<AssistantResponsecontent={msg.content}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -593,6 +595,7 @@ export const AssistantMessage = memo(function AssistantMessage({<AssistantResponsekey={seg.key}content={seg.text}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -620,6 +623,7 @@ export const AssistantMessage = memo(function AssistantMessage({) : (<AssistantResponsecontent={body}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.tsindex 227d14767..852e74082 100644--- a/web/lib/markdown-display.ts+++ b/web/lib/markdown-display.ts@@ -334,7 +334,7 @@ function removeEmptyMarkdownTables(content: string): string {const lines = content.split("\n");const cleaned: string[] = [];- for (let index = 0; index < lines.length; ) {+ for (let index = 0; index < lines.length;) {if (!isMarkdownTableStart(lines, index)) {cleaned.push(lines[index]);index += 1;@@ -591,6 +591,191 @@ export function repairMalformedStrongEmphasis(content: string): string {return fenced.restore(math.restore(inline.restore(repaired)));}+// Handle only standalone italic/strong runs. Triple-star runs can represent nested+// emphasis and require full delimiter-run parsing, so leave them untouched.+const EMPHASIS_DELIMITER_REGEX = /(?<!\*)\*\*(?!\*)|(?<!\*)\*(?!\*)/g;++function isNormalEmphasisCharacter(value: string | undefined): boolean {+ return Boolean(value && /[\p{L}\p{N}]/u.test(value));+}++function isPunctuationOrSymbol(value: string | undefined): boolean {+ return Boolean(value && /[\p{P}\p{S}]/u.test(value));+}++function isCjkCharacter(value: string | undefined): boolean {+ return Boolean(value && value >= "\u4e00" && value <= "\u9fff");+}++function firstNonWhitespaceAfter(+ line: string,+ index: number,+): string | undefined {+ return Array.from(line.slice(index)).find((value) => !/\s/u.test(value));+}++function lastNonWhitespaceBefore(+ line: string,+ index: number,+): string | undefined {+ return Array.from(line.slice(0, index))+ .reverse()+ .find((value) => !/\s/u.test(value));+}++function canOpenEmphasis(line: string, index: number, marker: string): boolean {+ const before = Array.from(line.slice(0, index)).pop();+ const afterIndex = index + marker.length;+ const after = Array.from(line.slice(afterIndex))[0];+ if (!after || /\s/u.test(after)) return false;+ if (isPunctuationOrSymbol(after)) {+ return (+ !before ||+ /\s/u.test(before) ||+ isPunctuationOrSymbol(before) ||+ isNormalEmphasisCharacter(before)+ );+ }+ return true;+}++function canCloseEmphasis(+ line: string,+ index: number,+ marker: string,+): boolean {+ const before = Array.from(line.slice(0, index)).pop();+ const afterIndex = index + marker.length;+ const after = Array.from(line.slice(afterIndex))[0];+ if (!before || /\s/u.test(before)) return false;+ if (isPunctuationOrSymbol(before)) {+ return (+ !after ||+ /\s/u.test(after) ||+ isPunctuationOrSymbol(after) ||+ isNormalEmphasisCharacter(after)+ );+ }+ return true;+}++function pairedEmphasisDelimiters(+ line: string,+): Array<{ marker: string; leftOpener: number; rightCloser: number }> {+ const openers = new Map<string, number[]>([+ ["*", []],+ ["**", []],+ ]);+ const pairs: Array<{+ marker: string;+ leftOpener: number;+ rightCloser: number;+ }> = [];+ let cursor = 0;+ while (cursor < line.length) {+ if (line[cursor] !== "*") {+ cursor += 1;+ continue;+ }+ let slashCount = 0;+ for (+ let previous = cursor - 1;+ previous >= 0 && line[previous] === "\\";+ previous -= 1+ ) {+ slashCount += 1;+ }+ if (slashCount % 2 !== 0) {+ cursor += 1;+ continue;+ }+ let runEnd = cursor;+ while (line[runEnd] === "*") runEnd += 1;+ const marker = line.slice(cursor, runEnd);+ if (openers.has(marker)) {+ const canOpen = canOpenEmphasis(line, cursor, marker);+ const canClose = canCloseEmphasis(line, cursor, marker);+ const candidates = openers.get(marker)!;+ if (canClose && candidates.length) {+ pairs.push({+ marker,+ leftOpener: candidates.pop()!,+ rightCloser: cursor,+ });+ } else if (canOpen) {+ candidates.push(cursor);+ }+ }+ cursor = runEnd;+ }+ return pairs;+}++function repairChineseEmphasisLine(line: string): string {+ const insertions: number[] = [];+ for (const { marker, leftOpener, rightCloser } of pairedEmphasisDelimiters(+ line,+ )) {+ const leftBefore = Array.from(line.slice(0, leftOpener)).pop();+ const leftInside = Array.from(line.slice(leftOpener + marker.length))[0];+ const rightInside = Array.from(line.slice(0, rightCloser)).pop();+ const rightAfterIndex = rightCloser + marker.length;+ const rightAfter = Array.from(line.slice(rightAfterIndex))[0];+ const leftNeedsSpace =+ isNormalEmphasisCharacter(leftBefore) &&+ isPunctuationOrSymbol(leftInside);+ const rightNeedsSpace =+ isPunctuationOrSymbol(rightInside) &&+ isNormalEmphasisCharacter(rightAfter);+ if (leftNeedsSpace) insertions.push(leftOpener);+ if (rightNeedsSpace) insertions.push(rightAfterIndex);+ if (leftNeedsSpace !== rightNeedsSpace) {+ if (+ isNormalEmphasisCharacter(rightInside) &&+ isNormalEmphasisCharacter(rightAfter)+ ) {+ insertions.push(rightAfterIndex);+ } else if (+ isNormalEmphasisCharacter(leftBefore) &&+ isNormalEmphasisCharacter(leftInside)+ ) {+ insertions.push(leftOpener);+ }+ }+ }++ return [...new Set(insertions)]+ .sort((a, b) => b - a)+ .reduce(+ (value, index) => `${value.slice(0, index)} ${value.slice(index)}`,+ line,+ );+}++/** Repair CJK emphasis delimiter boundaries for display without mutating source content. */+export function repairChineseEmphasis(+ content: string,+ language?: string,+): string {+ if (!content || !language?.toLowerCase().startsWith("zh")) return content;+ const fenced = maskProtectedSpans(+ content,+ FENCED_CODE_BLOCK_REGEX,+ "CJK_FENCED",+ );+ const math = maskProtectedSpans(fenced.masked, MATH_SPAN_REGEX, "CJK_MATH");+ const inline = maskProtectedSpans(+ math.masked,+ INLINE_CODE_SPAN_REGEX,+ "CJK_INLINE",+ );+ const repaired = inline.masked+ .split("\n")+ .map(repairChineseEmphasisLine)+ .join("\n");+ return fenced.restore(math.restore(inline.restore(repaired)));+}+/*** Repair one line, or leave it exactly as it was.*diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.tsindex 43acd5fc0..dc5edebf9 100644--- a/web/tests/markdown-display.test.ts+++ b/web/tests/markdown-display.test.ts@@ -6,10 +6,68 @@ import {hasVisibleMarkdownContent,markdownUrlTransform,normalizeMarkdownForDisplay,+ repairChineseEmphasis,repairMalformedStrongEmphasis,safeDecodeURIComponent,} from "../lib/markdown-display";+test("repairChineseEmphasis repairs punctuation boundaries only for Chinese", () => {+ assert.equal(repairChineseEmphasis("中文*,重点*", "zh-CN"), "中文 *,重点*");+ assert.equal(+ repairChineseEmphasis("中文**,重点**", "zh"),+ "中文 **,重点**",+ );+ assert.equal(repairChineseEmphasis("中文*,重点*", "en"), "中文*,重点*");+ assert.equal(repairChineseEmphasis("中文*,重点*"), "中文*,重点*");+});++test("repairChineseEmphasis balances the opposite delimiter when exactly one boundary is repaired", () => {+ assert.equal(+ repairChineseEmphasis("中文*,重点*内容", "zh"),+ "中文 *,重点* 内容",+ );+});++test("repairChineseEmphasis is fed the complete raw stream, not prior display output", () => {+ const chunks = ["中文*,重", "点*", "内容"];+ const rawContent = chunks.join("");++ assert.equal(repairChineseEmphasis(rawContent, "zh"), "中文 *,重点* 内容");+ assert.equal(+ repairChineseEmphasis(+ repairChineseEmphasis(chunks.slice(0, 2).join(""), "zh") + chunks[2],+ "zh",+ ),+ "中文 *,重点*内容",+ );+});+test("repairChineseEmphasis leaves inner whitespace and literal stars unchanged", () => {+ const inputs = [+ "* 重点 *",+ "** 重点 **",+ "*重点 内容*",+ "前言 * 第一项 * 与 * 第二项 * 后记",+ "Use * as multiplication *",+ String.raw`\* 重点 \*`,+ ];+ for (const input of inputs) {+ assert.equal(repairChineseEmphasis(input, "zh"), input);+ }+});++test("repairChineseEmphasis leaves code, math, escaped, and triple-star spans untouched", () => {+ const input = [+ "`中文*,重点*`",+ "```md",+ "中文**,重点**",+ "```",+ "$中文*,重点*$",+ "\\中文\\*,重点\\*",+ "中文***,重点***内容",+ ].join("\n");+ assert.equal(repairChineseEmphasis(input, "zh"), input);+});+test("repairMalformedStrongEmphasis moves label whitespace outside the closing marker", () => {assert.equal(repairMalformedStrongEmphasis("**發布日期: **2026 年 7 月 30 日"),