From 4dbab0d257c1580dd01007075a74ac9f2e2bbc25 Mon Sep 17 00:00:00 2001 From: Frank <35180438+Frankisfrank@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:20:55 +1100 Subject: [PATCH] fix: render Markdown in partner conversation archives --- web/components/partners/PartnerArchives.tsx | 88 ++++++++++++++- web/tests/partner-archives-markdown.spec.tsx | 112 +++++++++++++++++++ 2 files changed, 195 insertions(+), 5 deletions(-) create mode 100644 web/tests/partner-archives-markdown.spec.tsx diff --git a/web/components/partners/PartnerArchives.tsx b/web/components/partners/PartnerArchives.tsx index 205e29cbd..ded8fd1de 100644 --- a/web/components/partners/PartnerArchives.tsx +++ b/web/components/partners/PartnerArchives.tsx @@ -12,6 +12,7 @@ import { Trash2, } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { fromMarkdown } from "mdast-util-from-markdown"; import { deletePartnerSession, getPartnerHistoryPage, @@ -20,7 +21,9 @@ import { type PartnerSessionInfo, } from "@/lib/partners-api"; import type { ExportableMessage } from "@/lib/chat-export"; +import { plainTextPreview } from "@/lib/chat-outline"; import { displaySessionTitle } from "@/lib/session-title"; +import AssistantResponse from "@/components/common/AssistantResponse"; import Tooltip from "@/shared/ui/Tooltip"; interface HistoryMessage { @@ -30,6 +33,79 @@ interface HistoryMessage { channel?: string; } +function conversationPreview(content: string): string { + const tableCells = (line: string): string[] | null => { + const cells = [""]; + let hasPipe = false; + for (let index = 0; index < line.length; index++) { + const character = line[index]; + if (character === "\\" && index + 1 < line.length) { + cells[cells.length - 1] += character + line[++index]; + } else if (character === "|") { + hasPipe = true; + cells.push(""); + } else { + cells[cells.length - 1] += character; + } + } + if (!hasPipe) return null; + if (!cells[0].trim()) cells.shift(); + if (!cells.at(-1)?.trim()) cells.pop(); + return cells.map((cell) => cell.trim()); + }; + const lines = content.split("\n"); + const rows = lines.map(tableCells); + let inTable = false; + let separatorIndex = -1; + let text = lines + .map((line, index) => { + if (index === separatorIndex) return ""; + const cells = rows[index]; + const next = rows[index + 1]; + if (!inTable && cells?.length && next?.length === cells.length && next.every((cell) => /^:?-+:?$/.test(cell))) { + inTable = true; + separatorIndex = index + 1; + } + if (inTable && cells) { + return cells.map((cell) => cell.replace(/\\\|/g, "|")).join(" · "); + } + inTable = false; + return line; + }) + .join("\n"); + + // Keep code literal through all Markdown cleanup, including multi-backtick spans. + const literals = new Map(); + const tree = fromMarkdown(text); + const pending: (typeof tree | (typeof tree.children)[number])[] = [tree]; + let markerCode = 0xe000; + while (pending.length) { + const node = pending.pop()!; + if (node.type === "inlineCode") { + const start = node.position?.start.offset; + const end = node.position?.end.offset; + if (start === undefined || end === undefined) continue; + let marker = String.fromCharCode(markerCode++); + while (text.includes(marker)) marker = String.fromCharCode(markerCode++); + literals.set(marker, node.value.replace(/\r\n?|\n/g, " ")); + text = text.slice(0, start) + marker + text.slice(end); + } else if ("children" in node) { + // Visit right to left so replacing a code span preserves earlier offsets. + pending.push(...node.children); + } + } + // The server may truncate the snippet before an emphasis delimiter closes. + const repaired = text.replace( + /(\*\*|__|~~).*?\1|(? paired ? match : "", + ); + const preview = plainTextPreview(repaired, Infinity).replace( + /[\ue000-\uf8ff]/g, + (marker) => literals.get(marker) ?? marker, + ); + return preview.length > 160 ? `${preview.slice(0, 160).trimEnd()}…` : preview; +} + function formatTime(value?: string) { if (!value) return ""; const date = new Date(value); @@ -262,7 +338,7 @@ export default function PartnerArchives({ {session.last_message ? (

- {session.last_message} + {conversationPreview(session.last_message)}

) : null}
@@ -377,13 +453,15 @@ export default function PartnerArchives({ } >
- {message.content} + {message.role === "assistant" ? ( + + ) : message.content}
)) diff --git a/web/tests/partner-archives-markdown.spec.tsx b/web/tests/partner-archives-markdown.spec.tsx new file mode 100644 index 000000000..9434762fd --- /dev/null +++ b/web/tests/partner-archives-markdown.spec.tsx @@ -0,0 +1,112 @@ +import { cleanup, render, screen, within } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +import PartnerArchives from "@/components/partners/PartnerArchives"; + +const api = vi.hoisted(() => ({ sessions: vi.fn(), historyPage: vi.fn() })); +const translate = vi.hoisted(() => (key: string) => key); +vi.mock("@/lib/partners-api", () => ({ + getPartnerSessions: api.sessions, + getPartnerHistoryPage: api.historyPage, + resumePartnerSession: vi.fn(), + deletePartnerSession: vi.fn(), +})); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: translate }), +})); + +const markdown = "# 合成标题\n\n**合成重点**\n\n| 项目 | 状态 |\n| --- | --- |\n| 本地索引 | 就绪 |"; +const userText = "请原样保留 **用户文字** 和 # |"; + +function session(lastMessage: string) { + return { + session_key: "web-synthetic", + title: "Synthetic conversation", + archived: false, + message_count: 2, + updated_at: "2026-10-19T10:00:00", + last_message: lastMessage, + }; +} + +beforeEach(() => { + api.sessions.mockResolvedValue([session(markdown)]); + api.historyPage.mockResolvedValue({ + messages: [ + { role: "user", content: userText }, + { role: "assistant", content: markdown }, + ], + next_before: null, + }); +}); +afterEach(cleanup); + +it("renders assistant Markdown with the real chat renderer and keeps user text literal", async () => { + const onMessagesChange = vi.fn(); + const { container } = render( + , + ); + + expect(await screen.findByRole("heading", { name: "合成标题" })).toBeInTheDocument(); + const article = screen.getByRole("article"); + expect(article.querySelector("strong")).toHaveTextContent("合成重点"); + expect(within(article).getByRole("table")).toHaveTextContent("本地索引"); + expect(within(article).getByRole("table").parentElement).toHaveClass("overflow-x-auto"); + expect(article).not.toHaveTextContent("**"); + const user = screen.getByText(userText); + expect(user).toHaveClass("whitespace-pre-wrap"); + expect(user.querySelector("strong")).toBeNull(); + expect(container.querySelectorAll("table")).toHaveLength(1); + expect(onMessagesChange).toHaveBeenLastCalledWith([ + { role: "user", content: userText }, + { role: "assistant", content: markdown }, + ]); +}); + +it.each([ + ["# 概览\n\n**重点**与[文档](https://example.com)", "概览 重点与文档"], + ["| 名称 | 状态 |\n| --- | --- |\n| 本地 | 就绪 |", "名称 · 状态 本地 · 就绪"], + ["名称 | 状态\n--- | ---\n本地 | 就绪", "名称 · 状态 本地 · 就绪"], + ["**服务端截断的重点", "服务端截断的重点"], +])("shows readable plain text for conversation snippet %s", async (snippet, expected) => { + api.sessions.mockResolvedValue([session(snippet)]); + render(); + + const row = await screen.findByRole("button", { name: /Synthetic conversation/ }); + expect(row.querySelector("p")).toHaveTextContent(expected); + expect(row.querySelector("p")?.textContent).not.toMatch(/\*\*|#|\|/); + expect(row.querySelector("strong,table,a")).toBeNull(); +}); + +it.each([ + ["Calculate `2 ** 3`", "Calculate 2 ** 3"], + ["Keep a__b unchanged", "Keep a__b unchanged"], + ["Literal `**unfinished` code", "Literal **unfinished code"], + ["Calculate `2 ** 3 ** 4`", "Calculate 2 ** 3 ** 4"], + ["Keep `a__b__c` unchanged", "Keep a__b__c unchanged"], + ["Literal ``a`b ** c ** d`` code", "Literal a`b ** c ** d code"], + ["First `**a**` then ``__b__ `c` ~~d~~``", "First **a** then __b__ `c` ~~d~~"], + ["Keep `a\n**b**` code", "Keep a **b** code"], + ["Keep `# | [x](url) {{x}} [^1]` literal", "Keep # | [x](url) {{x}} [^1] literal"], +])("preserves literal punctuation in conversation snippet %s", async (snippet, expected) => { + api.sessions.mockResolvedValue([session(snippet)]); + render(); + + const row = await screen.findByRole("button", { name: /Synthetic conversation/ }); + expect(row.querySelector("p")?.textContent).toBe(expected); +}); + +it.each([ + ["| Header |\n| --- |\n| Value |", "Header Value"], + ["| A | B |\n| - | - |\n| x | y |", "A · B x · y"], + ["| A | B |\n| - | - |\n| x\\|y | z |", "A · B x|y · z"], + ["| A | B |\n| - | - |\n| `x\\|y` | z |", "A · B x|y · z"], + ["A | B\n- | -\nx | y\n\nKeep a|b", "A · B x · y Keep a|b"], + ["Just a paragraph\n--- | ---\nKeep this line", "Just a paragraph --- | --- Keep this line"], +])("preserves table cell content in conversation snippet %s", async (snippet, expected) => { + api.sessions.mockResolvedValue([session(snippet)]); + render(); + + const row = await screen.findByRole("button", { name: /Synthetic conversation/ }); + expect(row.querySelector("p")?.textContent).toBe(expected); +});