fix: render Markdown in partner conversation archives

This commit is contained in:
Frank
2026-10-20 00:20:55 +11:00
parent a31d82624c
commit 4dbab0d257
2 changed files with 195 additions and 5 deletions

View File

@@ -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<string, string>();
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|(?<![\w\\])(?:\*\*|__|~~)(?=\S)/g,
(match, paired) => 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({
</div>
{session.last_message ? (
<p className="mt-1 line-clamp-2 text-[11.5px] leading-snug text-[var(--muted-foreground)]">
{session.last_message}
{conversationPreview(session.last_message)}
</p>
) : null}
<div className="mt-1 flex items-center gap-2 text-[10.5px] text-[var(--muted-foreground)]">
@@ -377,13 +453,15 @@ export default function PartnerArchives({
}
>
<div
className={`max-w-[78%] whitespace-pre-wrap rounded-lg px-3 py-2 text-[13px] leading-relaxed ${
className={`min-w-0 rounded-lg px-3 py-2 text-[13px] leading-relaxed ${
message.role === "user"
? "bg-[var(--secondary)] text-[var(--foreground)]"
: "border border-[var(--border)] text-[var(--foreground)]"
? "max-w-[78%] whitespace-pre-wrap bg-[var(--secondary)] text-[var(--foreground)]"
: "max-w-full border border-[var(--border)] text-[var(--foreground)]"
}`}
>
{message.content}
{message.role === "assistant" ? (
<AssistantResponse content={message.content} />
) : message.content}
</div>
</div>
))

View File

@@ -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(
<PartnerArchives partnerId="synthetic" onToast={vi.fn()} onMessagesChange={onMessagesChange} />,
);
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(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
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) <tag> {{x}} [^1]` literal", "Keep # | [x](url) <tag> {{x}} [^1] literal"],
])("preserves literal punctuation in conversation snippet %s", async (snippet, expected) => {
api.sessions.mockResolvedValue([session(snippet)]);
render(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
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(<PartnerArchives partnerId="synthetic" onToast={vi.fn()} />);
const row = await screen.findByRole("button", { name: /Synthetic conversation/ });
expect(row.querySelector("p")?.textContent).toBe(expected);
});