Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(rich-content): unify Chat and Issue/Comment on one RichContent renderer (MUL-4922) (#5578)

Naiyuan Qing5a11232c474b
diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsx
index 8c9651e545..beaa5d53e8 100644
--- a/packages/ui/markdown/Markdown.tsx
+++ b/packages/ui/markdown/Markdown.tsx
@@ -1,8 +1,8 @@
import * as React from 'react'
-import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdown'
+import ReactMarkdown, { type Components } from 'react-markdown'
import rehypeKatex from 'rehype-katex'
import rehypeRaw from 'rehype-raw'
-import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'
+import rehypeSanitize from 'rehype-sanitize'
import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
@@ -14,6 +14,7 @@ import { isAllowedFileCardHref, preprocessFileCards } from './file-cards'
import { preprocessLinks } from './linkify'
import { preprocessIssueIdentifiers } from './issue-identifiers'
import { preprocessMentionShortcodes } from './mentions'
+import { markdownSanitizeSchema, markdownUrlTransform } from './sanitize'
import 'katex/dist/katex.min.css'
import './markdown.css'
@@ -87,64 +88,6 @@ export interface MarkdownProps {
autolinkIssueIdentifiers?: boolean
}
-// Sanitization schema — extends GitHub defaults to allow code highlighting classes
-// and Multica's internal mention/slash protocols.
-const sanitizeSchema = {
- ...defaultSchema,
- protocols: {
- ...defaultSchema.protocols,
- href: [...(defaultSchema.protocols?.href ?? []), 'mention', 'slash'],
- // Permit inline data-URI images (QR codes, charts, base64 screenshots).
- // The scheme gate only allows `data:` through here; attributes.img below
- // narrows it to image/* so non-image data URIs are still rejected.
- src: [...(defaultSchema.protocols?.src ?? []), 'data'],
- },
- attributes: {
- ...defaultSchema.attributes,
- div: [
- ...(defaultSchema.attributes?.div ?? []),
- 'dataType',
- 'dataHref',
- 'dataFilename',
- ],
- code: [
- ...(defaultSchema.attributes?.code ?? []),
- ['className', /^language-/],
- ['className', /^math-/],
- ['className', /^hljs/],
- ],
- img: [
- // Drop the default plain `src` entry so the value allow-list below is the
- // one findDefinition resolves — it returns the first match by name, so a
- // bare `src` string would otherwise shadow (and disable) the allow-list.
- ...(defaultSchema.attributes?.img ?? []).filter(
- (attr) => (typeof attr === 'string' ? attr : attr[0]) !== 'src',
- ),
- 'alt',
- // Allow inline data:image/* URIs while leaving every other src form
- // (http/https/site-relative) exactly as before: the negative lookahead
- // keeps all non-data values, and data: is narrowed to images only.
- ['src', /^data:image\//i, /^(?!data:)/i],
- ],
- },
-}
-
-/**
- * Custom URL transform that allows Multica internal protocols while keeping
- * the default security for all other URLs.
- */
-function urlTransform(url: string): string {
- if (url.startsWith('mention://')) return url
- if (url.startsWith('slash://skill/')) return url
- // Allow inline data:image/* URIs — defaultUrlTransform strips every data: URL
- // to '', which would blank the src even after rehype-sanitize keeps it. Kept
- // in sync with the image/* narrowing in sanitizeSchema (protocols.src +
- // attributes.img) so both gates agree on what a valid inline image is.
- if (/^data:image\//i.test(url)) return url
- return defaultUrlTransform(url)
-}
-
-
// File path detection regex - matches paths starting with /, ~/, or ./
const FILE_PATH_REGEX =
/^(?:\/|~\/|\.\/)[\w\-./@]+\.(?:ts|tsx|js|jsx|mjs|cjs|md|json|yaml|yml|py|go|rs|css|scss|less|html|htm|txt|log|sh|bash|zsh|swift|kt|java|c|cpp|h|hpp|rb|php|xml|toml|ini|cfg|conf|env|sql|graphql|vue|svelte|astro|prisma)$/i
@@ -483,8 +426,8 @@ export function Markdown({
remarkBreaks,
[remarkGfm, { singleTilde: false }],
]}
- rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]}
- urlTransform={urlTransform}
+ rehypePlugins={[rehypeRaw, [rehypeSanitize, markdownSanitizeSchema], rehypeKatex]}
+ urlTransform={markdownUrlTransform}
components={components}
>
{processedContent}
diff --git a/packages/ui/markdown/index.ts b/packages/ui/markdown/index.ts
index ce609eb5d5..a800eb5091 100644
--- a/packages/ui/markdown/index.ts
+++ b/packages/ui/markdown/index.ts
@@ -8,6 +8,7 @@ export {
ISSUE_IDENTIFIER_PATTERN,
} from './issue-identifiers'
export { preprocessMentionShortcodes } from './mentions'
+export { markdownSanitizeSchema, markdownUrlTransform } from './sanitize'
export {
preprocessFileCards,
isCdnUrl,
diff --git a/packages/ui/markdown/sanitize.ts b/packages/ui/markdown/sanitize.ts
new file mode 100644
index 0000000000..bc828d1042
--- /dev/null
+++ b/packages/ui/markdown/sanitize.ts
@@ -0,0 +1,75 @@
+import { defaultUrlTransform } from 'react-markdown'
+import { defaultSchema, type Options } from 'rehype-sanitize'
+
+/**
+ * Canonical sanitize schema + URL transform for every product-level Markdown
+ * renderer (Chat via ui/markdown/Markdown.tsx, Issue/Comment via
+ * views/editor/readonly-content.tsx).
+ *
+ * This is the ONLY copy. Both renderers previously carried a verbatim fork of
+ * this schema, which had already drifted — the readonly fork whitelisted <mark>
+ * for `==highlight==` and the chat fork did not. A security-relevant allow-list
+ * maintained in two places means any future XSS fix has to land twice, and
+ * missing one is a hole. Adding a surface means importing this, never copying
+ * it (MUL-4922).
+ *
+ * The two gates below must agree on what a valid inline image is:
+ * `protocols.src` + `attributes.img` (sanitize) and `markdownUrlTransform`
+ * (react-markdown). Change them together.
+ */
+export const markdownSanitizeSchema: Options = {
+ ...defaultSchema,
+ // Allow <mark> (text highlight) — emitted by highlightToHtml from `==text==`.
+ // It carries no attributes, so only the tag name needs whitelisting.
+ tagNames: [...(defaultSchema.tagNames ?? []), 'mark'],
+ protocols: {
+ ...defaultSchema.protocols,
+ href: [...(defaultSchema.protocols?.href ?? []), 'mention', 'slash'],
+ // Permit inline data-URI images (QR codes, charts, base64 screenshots).
+ // The scheme gate only allows `data:` through here; attributes.img below
+ // narrows it to image/* so non-image data URIs are still rejected.
+ src: [...(defaultSchema.protocols?.src ?? []), 'data'],
+ },
+ attributes: {
+ ...defaultSchema.attributes,
+ div: [
+ ...(defaultSchema.attributes?.div ?? []),
+ 'dataType',
+ 'dataHref',
+ 'dataFilename',
+ ],
+ code: [
+ ...(defaultSchema.attributes?.code ?? []),
+ ['className', /^language-/],
+ ['className', /^math-/],
+ ['className', /^hljs/],
+ ],
+ img: [
+ // Drop the default plain `src` entry so the value allow-list below is the
+ // one findDefinition resolves — it returns the first match by name, so a
+ // bare `src` string would otherwise shadow (and disable) the allow-list.
+ ...(defaultSchema.attributes?.img ?? []).filter(
+ (attr) => (typeof attr === 'string' ? attr : attr[0]) !== 'src',
+ ),
+ 'alt',
+ // Allow inline data:image/* URIs while leaving every other src form
+ // (http/https/site-relative) exactly as before: the negative lookahead
+ // keeps all non-data values, and data: is narrowed to images only.
+ ['src', /^data:image\//i, /^(?!data:)/i],
+ ],
+ },
+}
+
+/**
+ * Allows Multica internal protocols and inline images through react-markdown's
+ * URL gate while keeping default security for everything else.
+ */
+export function markdownUrlTransform(url: string): string {
+ if (url.startsWith('mention://')) return url
+ if (url.startsWith('slash://skill/')) return url
+ // defaultUrlTransform strips every data: URL to '', which would blank the src
+ // even after rehype-sanitize keeps it. Kept in sync with the image/* narrowing
+ // in markdownSanitizeSchema so both gates agree on what a valid inline image is.
+ if (/^data:image\//i.test(url)) return url
+ return defaultUrlTransform(url)
+}
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index ef281515ad..e5bbb42e9e 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -1,11 +1,46 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { chatKeys } from "@multica/core/chat/queries";
import type { TaskMessagePayload } from "@multica/core/types";
+import type { ReactElement } from "react";
import enChat from "../../locales/en/chat.json";
+// The live timeline is a real list row rather than Virtuoso chrome (MUL-4922),
+// so it shares one identity with the persisted assistant row and keeps its
+// Mermaid/HTML blocks mounted across task completion. Real react-virtuoso
+// renders its Footer but NO data rows under jsdom's zero-height viewport, so
+// these tests must stub it to see rows at all. computeItemKey is still applied
+// here — it is what expresses the live -> persisted identity.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({
+ data,
+ itemContent,
+ computeItemKey,
+ components,
+ context,
+ }: {
+ data: unknown[];
+ itemContent: (i: number, item: unknown) => ReactElement;
+ computeItemKey: (i: number, item: unknown) => string;
+ components?: { Footer?: (p: { context?: unknown }) => ReactElement | null };
+ context?: unknown;
+ }) => {
+ const Footer = components?.Footer;
+ return (
+ <div>
+ {data.map((item, i) => (
+ <div key={computeItemKey(i, item)} data-row-key={computeItemKey(i, item)}>
+ {itemContent(i, item)}
+ </div>
+ ))}
+ {Footer ? <Footer context={context} /> : null}
+ </div>
+ );
+ },
+}));
+
import { ChatMessageList } from "./chat-message-list";
const TEST_RESOURCES = { en: { chat: enChat } };
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 1ed5f24aa0..cec109038c 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -1,6 +1,6 @@
"use client";
-import { memo, useCallback, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
import { Virtuoso, type Components } from "react-virtuoso";
@@ -20,7 +20,8 @@ import {
import { ChevronRight, ChevronDown, Brain, AlertCircle, AlertTriangle, Copy } from "lucide-react";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
import { isTaskMessageTaskId, taskMessagesOptions } from "@multica/core/chat/queries";
-import { MemoizedMarkdown } from "@multica/views/common/markdown";
+import { RichContent } from "../../rich-content";
+import { RichContentScrollRootProvider } from "../../rich-content/scroll-root";
import { copyText } from "@multica/ui/lib/clipboard";
import { AttachmentList } from "../../issues/components/comment-card";
import type { AgentAvailability } from "@multica/core/agents";
@@ -70,14 +71,34 @@ interface ChatMessageListProps {
interface ChatListContext {
isFetchingOlderMessages: boolean;
- hasLive: boolean;
- liveTimeline: ChatTimelineItem[];
showStatusPill: boolean;
pendingTask: ChatPendingTask | null | undefined;
liveTaskMessages: readonly TaskMessagePayload[] | undefined;
availability: AgentAvailability | undefined;
}
+/**
+ * One Virtuoso row. A live (still-streaming) task and the persisted assistant
+ * message it becomes share ONE key — `task:<taskId>` — so the handoff replaces
+ * this item's data in place instead of unmounting a Footer subtree and mounting
+ * a different row (MUL-4922). That identity is what keeps an already-rendered
+ * Mermaid diagram or HTML iframe mounted across task completion.
+ */
+type ChatRenderItem =
+ | { key: string; kind: "message"; message: ChatMessage; taskId: string | null }
+ | { key: string; kind: "live"; taskId: string };
+
+/**
+ * Row key for a persisted message. Assistant turns carrying a task_id key on
+ * the task so they can inherit the live row; everything else keys on its own
+ * id.
+ */
+function messageRowKey(message: ChatMessage): string {
+ return message.role === "assistant" && message.task_id
+ ? `task:${message.task_id}`
+ : message.id;
+}
+
function ChatListHeader({ context }: { context?: ChatListContext }) {
const { t } = useT("chat");
return (
@@ -91,27 +112,24 @@ function ChatListHeader({ context }: { context?: ChatListContext }) {
);
}
+// The Footer now carries only the status pill — task chrome, not content. The
+// live timeline moved into a real row so it can keep its identity when the
+// task completes (see ChatRenderItem).
function ChatListFooter({ context }: { context?: ChatListContext }) {
if (!context) return null;
+ if (!context.showStatusPill || !context.pendingTask) return null;
return (
<div className="mx-auto w-full max-w-4xl px-5 pb-4 space-y-4">
- {context.hasLive && (
- <div className="w-full space-y-1.5">
- <TimelineView items={context.liveTimeline} isStreaming />
- </div>
- )}
- {context.showStatusPill && context.pendingTask && (
- <TaskStatusPill
- pendingTask={context.pendingTask}
- taskMessages={context.liveTaskMessages ?? []}
- availability={context.availability}
- />
- )}
+ <TaskStatusPill
+ pendingTask={context.pendingTask}
+ taskMessages={context.liveTaskMessages ?? []}
+ availability={context.availability}
+ />
</div>
);
}
-const LIST_COMPONENTS: Components<ChatMessage, ChatListContext> = {
+const LIST_COMPONENTS: Components<ChatRenderItem, ChatListContext> = {
Header: ChatListHeader,
Footer: ChatListFooter,
};
@@ -148,30 +166,39 @@ export function ChatMessageList({
);
// Live timeline for the in-flight task. useRealtimeSync keeps this cache
- // current via setQueryData on task:message events.
+ // current via setQueryData on task:message events. Only used here to decide
+ // whether the live row exists and to feed the status pill — the row itself
+ // reads the same cache entry through AssistantMessage.
const showLiveTimeline = !!pendingTaskId && !pendingAlreadyPersisted;
const canFetchLiveTimeline = isTaskMessageTaskId(pendingTaskId) && !pendingAlreadyPersisted;
const { data: liveTaskMessages } = useQuery({
...taskMessagesOptions(pendingTaskId ?? ""),
enabled: canFetchLiveTimeline,
});
- // Memoized on the cache array identity: mergeTaskMessagesBySeq preserves
- // the array reference when a duplicate event arrives, so this recomputes
- // only when a genuinely new message lands — not on unrelated re-renders.
- const liveTimeline: ChatTimelineItem[] = useMemo(
- () => transformTimeline(buildTimeline(liveTaskMessages ?? []), transformContent),
- [liveTaskMessages, transformContent],
- );
- const hasLive = showLiveTimeline && liveTimeline.length > 0;
+ const hasLive = showLiveTimeline && (liveTaskMessages?.length ?? 0) > 0;
const showStatusPill = !!pendingTaskId && !pendingAlreadyPersisted && !!pendingTask;
- const totalCount = messages.length + (hasLive || showStatusPill ? 1 : 0);
- const firstIndex = totalCount > 0 ? firstItemIndex : 0;
+ // Persisted messages plus, while a task is in flight, one synthetic trailing
+ // row for it. When the assistant message persists, `hasLive` goes false and
+ // the message takes the SAME key at the SAME position — an in-place data
+ // swap, not a remount.
+ const renderItems: ChatRenderItem[] = useMemo(() => {
+ const items: ChatRenderItem[] = messages.map((message) => ({
+ key: messageRowKey(message),
+ kind: "message" as const,
+ message,
+ taskId: message.task_id ?? null,
+ }));
+ if (hasLive && pendingTaskId) {
+ items.push({ key: `task:${pendingTaskId}`, kind: "live", taskId: pendingTaskId });
+ }
+ return items;
+ }, [messages, hasLive, pendingTaskId]);
+
+ const firstIndex = renderItems.length > 0 ? firstItemIndex : 0;
const listContext: ChatListContext = {
isFetchingOlderMessages,
- hasLive,
- liveTimeline,
showStatusPill,
pendingTask,
liveTaskMessages,
@@ -190,9 +217,13 @@ export function ChatMessageList({
<ChatMessageSkeleton />
</div>
) : (
+ // Chat scrolls inside its own element, so rich blocks must measure
+ // "near-viewport" against that element rather than the browser viewport —
+ // otherwise a diagram only starts loading once it is already on screen.
+ <RichContentScrollRootProvider scrollRoot={scrollContainerEl}>
<Virtuoso
customScrollParent={scrollContainerEl}
- data={messages}
+ data={renderItems}
firstItemIndex={firstIndex}
// Open pinned to the newest message. The list is remounted per session
// (`key={activeSessionId}` upstream), so this initial position is
@@ -213,19 +244,20 @@ export function ChatMessageList({
onLoadOlderMessages?.();
}
}}
- computeItemKey={(_, msg) => msg.id}
+ computeItemKey={(_, item) => item.key}
context={listContext}
components={LIST_COMPONENTS}
- itemContent={(_, msg) => (
+ itemContent={(_, item) => (
<div className="mx-auto w-full max-w-4xl px-5 py-2">
<MessageBubble
- message={msg}
- isPending={!!pendingTaskId && msg.task_id === pendingTaskId}
+ item={item}
+ isPending={!!pendingTaskId && item.taskId === pendingTaskId}
transformContent={transformContent}
/>
</div>
)}
/>
+ </RichContentScrollRootProvider>
)}
</div>
);
@@ -266,25 +298,44 @@ export function ChatMessageSkeleton() {
// memo skips reconciling rows the stream didn't touch — the persisted
// history stays inert while only the live footer updates.
const MessageBubble = memo(function MessageBubble({
- message,
+ item,
isPending,
transformContent,
}: {
- message: ChatMessage;
+ item: ChatRenderItem;
isPending: boolean;
transformContent?: (content: string) => string;
}) {
+ // The live row and the persisted assistant row both land here under one key,
+ // and both render <AssistantMessage> — same component type, same position —
+ // so React reconciles rather than remounts at task completion.
+ if (item.kind === "live") {
+ return (
+ <AssistantMessage
+ taskId={item.taskId}
+ isPending={isPending}
+ transformContent={transformContent}
+ />
+ );
+ }
+
+ const { message } = item;
+
if (message.role === "user") {
return (
<div className="flex justify-end">
<div className="rounded-2xl bg-muted px-3.5 py-2 text-sm max-w-[80%] break-words">
- {/* User messages are authored as markdown in ContentEditor, so
- * render them through the same pipeline as assistant replies.
- * Neutralise prose's leading/trailing margin so single-line
- * bubbles stay as compact as the plain-text version used to. */}
- <div className="prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
- <MemoizedMarkdown attachments={message.attachments}>{message.content}</MemoizedMarkdown>
- </div>
+ {/* User messages are authored as markdown in ContentEditor, so they
+ * render through the SAME RichContent as assistant replies and as
+ * Issue/Comment — a Mermaid fence a user pastes is a diagram here
+ * too. `compact` trims the leading/trailing block margins so a
+ * single-line bubble stays as tight as the plain-text version. */}
+ <RichContent
+ content={message.content}
+ attachments={message.attachments}
+ density="compact"
+ phase="settled"
+ />
<AttachmentList
attachments={message.attachments}
content={message.content}
@@ -297,6 +348,7 @@ const MessageBubble = memo(function MessageBubble({
return (
<AssistantMessage
+ taskId={message.task_id ?? null}
message={message}
isPending={isPending}
transformContent={transformContent}
@@ -304,16 +356,34 @@ const MessageBubble = memo(function MessageBubble({
);
});
+/**
+ * Assistant turn body — renders BOTH the in-flight (live) and the persisted
+ * form of one task (MUL-4922).
+ *
+ * `message` is undefined while the task streams and becomes the persisted
+ * `chat_message` when it lands. Both forms are rendered by this one component,
+ * mounted under one stable row key (`task:<taskId>`), so the live → persisted
+ * handoff is a prop change rather than an unmount: the RichContent subtree and
+ * any Mermaid diagram / HTML iframe inside it stay mounted, keep their pan-zoom
+ * state, and never re-run their expensive render. Before this, the live
+ * timeline lived in Virtuoso's Footer and the persisted row keyed on
+ * `message.id`, so every completed task tore down and rebuilt its diagrams.
+ *
+ * The timeline itself comes from `taskMessagesOptions(taskId)` in both forms —
+ * the same cache entry useRealtimeSync seeds during execution — so no refetch
+ * and no data discontinuity happens at the handoff either.
+ */
function AssistantMessage({
+ taskId,
message,
isPending,
transformContent,
}: {
- message: ChatMessage;
+ taskId: string | null;
+ message?: ChatMessage;
isPending: boolean;
transformContent?: (content: string) => string;
}) {
- const taskId = message.task_id;
const canFetchTaskMessages = isTaskMessageTaskId(taskId);
// Use the shared taskMessagesOptions so this cache entry is the same one
@@ -324,17 +394,23 @@ function AssistantMessage({
enabled: canFetchTaskMessages,
});
- // Same memoization rationale as the live timeline in ChatMessageList.
+ // Memoized on the cache array identity: mergeTaskMessagesBySeq preserves the
+ // array reference when a duplicate event arrives, so this recomputes only
+ // when a genuinely new message lands.
const timeline: ChatTimelineItem[] = useMemo(
() => transformTimeline(buildTimeline(taskMessages ?? []), transformContent),
[taskMessages, transformContent],
);
+ // Content is settled once the persisted message exists; until then text is
+ // still arriving and a trailing fence may be half-written.
+ const phase: "streaming" | "settled" = message ? "settled" : "streaming";
+
// Failure bubble path: when the server's FailTask wrote a failure
// chat_message (failure_reason set), render a destructive bubble with the
// human-readable reason label + collapsible raw errMsg + the same timeline
// so the user can see exactly where the run broke.
- if (message.failure_reason) {
+ if (message?.failure_reason) {
return (
<FailureBubble
reason={message.failure_reason}
@@ -348,29 +424,42 @@ function AssistantMessage({
// no_response path (MUL-4351): the agent completed this direct-chat turn
// without any text. Keep whatever tool/thinking timeline the run produced and
// show a localized "no text reply" notice instead of an empty markdown block.
- const isNoResponse = message.message_kind === "no_response";
+ const isNoResponse = message?.message_kind === "no_response";
return (
<div className="w-full space-y-1.5">
{timeline.length > 0 && (
- <TimelineView items={timeline} attachments={message.attachments} />
+ <TimelineView
+ items={timeline}
+ attachments={message?.attachments}
+ phase={phase}
+ isStreaming={!message}
+ />
)}
{isNoResponse ? (
<NoResponseNotice />
- ) : timeline.length === 0 ? (
- <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <MemoizedMarkdown attachments={message.attachments}>{message.content}</MemoizedMarkdown>
- </div>
+ ) : message && timeline.length === 0 ? (
+ <RichContent
+ content={message.content}
+ attachments={message.attachments}
+ density="compact"
+ phase="settled"
+ className="leading-relaxed"
+ />
) : null}
- <AttachmentList
- attachments={message.attachments}
- content={message.content}
- />
- <MessageFooter
- message={message}
- timeline={timeline}
- isPending={isPending}
- />
+ {message && (
+ <>
+ <AttachmentList
+ attachments={message.attachments}
+ content={message.content}
+ />
+ <MessageFooter
+ message={message}
+ timeline={timeline}
+ isPending={isPending}
+ />
+ </>
+ )}
</div>
);
}
@@ -584,35 +673,42 @@ function TimelineView({
items,
isStreaming,
attachments,
+ phase = "settled",
}: {
items: ChatTimelineItem[];
isStreaming?: boolean;
attachments?: import("@multica/core/types").Attachment[];
+ phase?: "streaming" | "settled";
}) {
const { preface, middle, final } = splitTimeline(items);
return (
<>
{preface.length > 0 && (
- <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <MemoizedMarkdown attachments={attachments}>
- {preface.map((t) => t.content ?? "").join("")}
- </MemoizedMarkdown>
- </div>
+ <RichContent
+ content={preface.map((t) => t.content ?? "").join("")}
+ attachments={attachments}
+ density="compact"
+ phase={phase}
+ className="leading-relaxed"
+ />
)}
{middle.length > 0 && (
<OuterProcessFold
items={middle}
- defaultOpen={!!isStreaming}
+ isStreaming={!!isStreaming}
attachments={attachments}
+ phase={phase}
/>
)}
{final.length > 0 && (
- <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <MemoizedMarkdown attachments={attachments}>
- {final.map((t) => t.content ?? "").join("")}
- </MemoizedMarkdown>
- </div>
+ <RichContent
+ content={final.map((t) => t.content ?? "").join("")}
+ attachments={attachments}
+ density="compact"
+ phase={phase}
+ className="leading-relaxed"
+ />
)}
</>
);
@@ -620,20 +716,27 @@ function TimelineView({
function OuterProcessFold({
items,
- defaultOpen,
+ isStreaming,
attachments,
+ phase = "settled",
}: {
items: ChatTimelineItem[];
- defaultOpen?: boolean;
+ isStreaming?: boolean;
attachments?: import("@multica/core/types").Attachment[];
+ phase?: "streaming" | "settled";
}) {
const { t } = useT("chat");
- // useState seeds once at mount — subsequent renders never overwrite the
- // user's manual toggle. The streaming → completed transition unmounts
- // the live <TimelineView> and mounts the persisted AssistantMessage's
- // own <TimelineView>, so the persisted instance starts closed (default)
- // even if the live one was open. That's the desired collapsed-default.
- const [open, setOpen] = useState(defaultOpen ?? false);
+ // Open while the task streams (so the user watches progress), collapsed once
+ // it settles. This used to fall out of a remount: the live TimelineView was
+ // torn down and the persisted one mounted closed. The row is now stable
+ // across that handoff (MUL-4922) — which is the point, it keeps Mermaid and
+ // HTML blocks alive — so the collapse has to be expressed directly.
+ const [open, setOpen] = useState(!!isStreaming);
+ const wasStreaming = useRef(!!isStreaming);
+ useEffect(() => {
+ if (wasStreaming.current && !isStreaming) setOpen(false);
+ wasStreaming.current = !!isStreaming;
+ }, [isStreaming]);
const stepCount = items.length;
return (
@@ -646,7 +749,12 @@ function OuterProcessFold({
<div className="mt-1 rounded-lg border bg-muted/20 p-2 space-y-0.5">
{items.map((item) =>
item.type === "text" ? (
- <MiddleTextRow key={item.seq} item={item} attachments={attachments} />
+ <MiddleTextRow
+ key={item.seq}
+ item={item}
+ attachments={attachments}
+ phase={phase}
+ />
) : (
<ItemRow key={item.seq} item={item} />
),
@@ -664,13 +772,20 @@ function OuterProcessFold({
function MiddleTextRow({
item,
attachments,
+ phase = "settled",
}: {
item: ChatTimelineItem;
attachments?: import("@multica/core/types").Attachment[];
+ phase?: "streaming" | "settled";
}) {
return (
- <div className="py-0.5 text-xs text-muted-foreground prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
- <MemoizedMarkdown attachments={attachments}>{item.content ?? ""}</MemoizedMarkdown>
+ <div className="py-0.5 text-xs text-muted-foreground">
+ <RichContent
+ content={item.content ?? ""}
+ attachments={attachments}
+ density="compact"
+ phase={phase}
+ />
</div>
);
}
diff --git a/packages/views/common/markdown.test.tsx b/packages/views/common/markdown.test.tsx
deleted file mode 100644
index 0e3450e33f..0000000000
--- a/packages/views/common/markdown.test.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-import type { ReactNode } from "react";
-import { render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { Markdown as MarkdownBase } from "@multica/ui/markdown";
-import { Markdown } from "./markdown";
-
-const { resolveMock } = vi.hoisted(() => ({ resolveMock: vi.fn() }));
-
-vi.mock("../issues/hooks", () => ({
- useResolveIssueIdentifier: (identifier: string) => resolveMock(identifier),
-}));
-
-vi.mock("@multica/core/config", () => ({
- useConfigStore: (selector: (state: { cdnDomain: string }) => unknown) =>
- selector({ cdnDomain: "" }),
-}));
-
-vi.mock("../issues/components/issue-mention-card", () => ({
- IssueMentionCard: ({ issueId }: { issueId: string }) => (
- <span data-testid="issue-mention-card">{issueId}</span>
- ),
-}));
-
-vi.mock("@multica/core/paths", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@multica/core/paths")>();
- return {
- ...actual,
- useWorkspaceSlug: () => "acme",
- useRequiredWorkspaceSlug: () => "acme",
- useWorkspacePaths: () => ({
- ...actual.paths.workspace("acme"),
- projectDetail: (projectId: string) => `/projects/${projectId}`,
- }),
- };
-});
-
-vi.mock("../navigation", () => ({
- AppLink: ({
- href,
- children,
- className,
- }: {
- href: string;
- children: ReactNode;
- className?: string;
- }) => (
- <a href={href} className={className}>
- {children}
- </a>
- ),
-}));
-
-vi.mock("../projects/components/project-chip", () => ({
- ProjectChip: ({ projectId }: { projectId: string }) => (
- <span data-testid="project-chip">{projectId}</span>
- ),
-}));
-
-const ligatureClasses = [
- "[font-variant-ligatures:none]",
- "[font-feature-settings:'liga'_0]",
-];
-
-describe("Markdown", () => {
- it("disables ligatures inside raw code tags", () => {
- render(<Markdown>{"<code>uv run --extra dev pytest -q</code>"}</Markdown>);
-
- expect(screen.getByText("uv run --extra dev pytest -q")).toHaveClass(...ligatureClasses);
- });
-
- it("disables ligatures inside fenced code blocks", () => {
- render(<Markdown>{"```sh\nuv run --extra dev pytest -q\n```"}</Markdown>);
-
- expect(screen.getByText("uv run --extra dev pytest -q")).toHaveClass(...ligatureClasses);
- });
-
- it("disables ligatures in terminal-mode code", () => {
- render(<Markdown mode="terminal">{"<code>uv run --extra dev pytest -q</code>"}</Markdown>);
-
- expect(screen.getByText("uv run --extra dev pytest -q")).toHaveClass(...ligatureClasses);
- });
-
- it("renders slash skill links as slash command pills", () => {
- const { container } = render(
- <Markdown>[/deploy](slash://skill/abc-123)</Markdown>,
- );
-
- const pill = container.querySelector(".slash-command");
- expect(pill).not.toBeNull();
- expect(pill?.textContent).toBe("/deploy");
- });
-
- it("renders project mention links as project chips", () => {
- render(<Markdown>{"[Roadmap](mention://project/project-123)"}</Markdown>);
-
- expect(screen.getByTestId("project-chip")).toHaveTextContent("project-123");
- expect(screen.getByRole("link")).toHaveAttribute("href", "/projects/project-123");
- });
-});
-
-describe("Markdown bare issue identifier autolink", () => {
- afterEach(() => {
- resolveMock.mockReset();
- });
-
- it("renders a resolved bare identifier as an issue chip", () => {
- resolveMock.mockImplementation((id: string) =>
- id === "MUL-1" ? { id: "issue-1", identifier: "MUL-1" } : null,
- );
-
- render(<Markdown>{"Related to MUL-1 today"}</Markdown>);
-
- expect(screen.getByTestId("issue-mention-card")).toHaveTextContent("issue-1");
- expect(resolveMock).toHaveBeenCalledWith("MUL-1");
- });
-
- it("leaves an unresolved bare identifier as plain text", () => {
- resolveMock.mockReturnValue(null);
-
- render(<Markdown>{"Related to MUL-999 today"}</Markdown>);
-
- expect(screen.queryByTestId("issue-mention-card")).toBeNull();
- expect(screen.getByText(/Related to/)).toHaveTextContent("MUL-999");
- });
-
- it("does not autolink identifiers inside inline code", () => {
- resolveMock.mockReturnValue(null);
-
- render(<Markdown>{"use `MUL-1` here"}</Markdown>);
-
- expect(resolveMock).not.toHaveBeenCalled();
- expect(screen.queryByTestId("issue-mention-card")).toBeNull();
- });
-
- it("routes a canonical UUID mention straight to the chip (no identifier resolve)", () => {
- render(
- <Markdown>
- {"[MUL-2](mention://issue/00000000-0000-0000-0000-000000000002)"}
- </Markdown>,
- );
-
- expect(screen.getByTestId("issue-mention-card")).toHaveTextContent(
- "00000000-0000-0000-0000-000000000002",
- );
- expect(resolveMock).not.toHaveBeenCalled();
- });
-});
-
-// The base renderer uses a plain <img>; exercising it here (instead of the
-// views wrapper, which swaps in <Attachment>) lets us assert the sanitized
-// `src` directly. Covers the two gates that used to blank data-URI images:
-// rehype-sanitize's protocols.src and react-markdown's urlTransform.
-describe("Markdown inline data-URI images", () => {
- const PNG_1X1 =
- "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
-
- it("preserves the src of an inline data:image/png image", () => {
- render(<MarkdownBase>{`![demo](${PNG_1X1})`}</MarkdownBase>);
-
- const img = screen.getByAltText("demo");
- expect(img.tagName).toBe("IMG");
- expect(img).toHaveAttribute("src", PNG_1X1);
- });
-
- it("keeps regular http(s) images working", () => {
- render(<MarkdownBase>{"![cat](https://cdn.example.com/cat.png)"}</MarkdownBase>);
-
- expect(screen.getByAltText("cat")).toHaveAttribute(
- "src",
- "https://cdn.example.com/cat.png",
- );
- });
-
- it("strips non-image data URIs (data:text/html)", () => {
- render(
- <MarkdownBase>{"![x](data:text/html,<script>alert(1)</script>)"}</MarkdownBase>,
- );
-
- const img = screen.getByAltText("x");
- expect(img.getAttribute("src") ?? "").toBe("");
- });
-});
diff --git a/packages/views/common/markdown.tsx b/packages/views/common/markdown.tsx
deleted file mode 100644
index 920efda33c..0000000000
--- a/packages/views/common/markdown.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-"use client";
-
-import * as React from "react";
-import {
- Markdown as MarkdownBase,
- type MarkdownProps as MarkdownBaseProps,
- type RenderMode,
- isIssueIdentifier,
-} from "@multica/ui/markdown";
-import { useConfigStore } from "@multica/core/config";
-import type { Attachment as AttachmentRecord } from "@multica/core/types";
-import { useWorkspacePaths } from "@multica/core/paths";
-import { IssueMentionCard } from "../issues/components/issue-mention-card";
-import { useResolveIssueIdentifier } from "../issues/hooks";
-import { ProjectChip } from "../projects/components/project-chip";
-import { AppLink } from "../navigation";
-import {
- Attachment as AttachmentRenderer,
- AttachmentDownloadProvider,
-} from "../editor";
-
-export type { RenderMode };
-
-export interface MarkdownProps extends MarkdownBaseProps {
- /**
- * Attachments associated with the surrounding entity (chat message, skill
- * file). When passed, the renderer resolves inline image / file-card URLs
- * to full attachment records via AttachmentDownloadProvider, unlocking the
- * unified hover toolbar / lightbox / preview-modal behavior used in
- * editor surfaces.
- */
- attachments?: AttachmentRecord[];
-}
-
-/**
- * Default renderMention that delegates to entity chips for issue/project mentions
- * and renders a styled span for other mention types.
- */
-function ProjectMentionCard({ projectId }: { projectId: string }): React.ReactNode {
- const p = useWorkspacePaths();
- return (
- <AppLink href={p.projectDetail(projectId)} className="project-mention not-prose inline-flex">
- <ProjectChip
- projectId={projectId}
- className="cursor-pointer hover:bg-accent transition-colors"
- />
- </AppLink>
- );
-}
-
-/**
- * Autolinked bare identifier (e.g. `MUL-123`) routed through
- * `mention://issue/<identifier>`. Resolves the identifier to a real issue in
- * the current workspace; renders a navigable chip on a hit, plain text on a
- * miss / while loading / cross-workspace.
- */
-function AutolinkedIssueMention({ identifier }: { identifier: string }): React.ReactNode {
- const issue = useResolveIssueIdentifier(identifier);
- if (!issue) return identifier;
- return <IssueMentionCard issueId={issue.id} fallbackLabel={identifier} />;
-}
-
-function defaultRenderMention({
- type,
- id,
-}: {
- type: string;
- id: string;
-}): React.ReactNode {
- if (type === "issue") {
- // A bare identifier (from the autolink preprocessor) is carried as the id
- // segment; a real mention carries a UUID. Dispatch on the id shape.
- if (isIssueIdentifier(id)) {
- return <AutolinkedIssueMention identifier={id} />;
- }
- return <IssueMentionCard issueId={id} />;
- }
- if (type === "project") {
- return <ProjectMentionCard projectId={id} />;
- }
- return null;
-}
-
-function renderImage({ src, alt }: { src: string; alt: string }): React.ReactNode {
- return (
- <AttachmentRenderer
- attachment={{
- kind: "url",
- url: src,
- filename: alt,
- // chat / skill markdown `![]()` is structurally an image. Without
- // forceKind, empty/descriptive alt strings would route to the
- // file-card chrome via getPreviewKind autodetect.
- forceKind: "image",
- }}
- />
- );
-}
-
-function renderFileCard({
- href,
- filename,
-}: {
- href: string;
- filename: string;
-}): React.ReactNode {
- return (
- <AttachmentRenderer
- attachment={{ kind: "url", url: href, filename }}
- />
- );
-}
-
-/**
- * App-level Markdown wrapper. Injects:
- * - entity chips for issue/project mentions
- * - cdnDomain from the config store (drives fileCard preprocessing)
- * - unified <Attachment> as the image / file-card renderer
- * - AttachmentDownloadProvider so url → record resolution works inside
- * the injected <Attachment> components
- */
-export function Markdown(props: MarkdownProps): React.JSX.Element {
- const cdnDomain = useConfigStore((s) => s.cdnDomain);
- const { attachments, ...rest } = props;
- return (
- <AttachmentDownloadProvider attachments={attachments}>
- <MarkdownBase
- renderMention={defaultRenderMention}
- renderImage={renderImage}
- renderFileCard={renderFileCard}
- cdnDomain={cdnDomain}
- autolinkIssueIdentifiers
- {...rest}
- />
- </AttachmentDownloadProvider>
- );
-}
-
-export const MemoizedMarkdown = React.memo(Markdown);
-MemoizedMarkdown.displayName = "MemoizedMarkdown";
diff --git a/packages/views/common/rich-content-sanitize-contract.test.tsx b/packages/views/common/rich-content-sanitize-contract.test.tsx
new file mode 100644
index 0000000000..12a4de5610
--- /dev/null
+++ b/packages/views/common/rich-content-sanitize-contract.test.tsx
@@ -0,0 +1,184 @@
+/**
+ * Cross-surface sanitize contract (MUL-4922).
+ *
+ * The two product-level Markdown chains — Chat (ui/markdown/Markdown.tsx) and
+ * Issue/Comment (views/editor/readonly-content.tsx) — used to carry a verbatim
+ * fork of the sanitize schema and urlTransform each, and had already drifted:
+ * readonly whitelisted <mark>, chat did not. Both now import the single
+ * canonical base from @multica/ui/markdown.
+ *
+ * This suite runs one set of security fixtures through BOTH surfaces and
+ * asserts the same outcome. It is the mechanism that stops a third fork from
+ * growing back: a schema change that lands on only one chain fails here.
+ */
+import { describe, expect, it, vi } from "vitest";
+import { render } from "@testing-library/react";
+import {
+ Markdown as MarkdownBase,
+ markdownSanitizeSchema,
+} from "@multica/ui/markdown";
+
+vi.mock("@multica/core/config", () => ({
+ useConfigStore: (selector: (state: { cdnDomain: string }) => unknown) =>
+ selector({ cdnDomain: "" }),
+ configStore: { getState: () => ({ cdnDomain: "" }) },
+}));
+
+vi.mock("../issues/hooks", () => ({
+ useResolveIssueIdentifier: () => null,
+}));
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string) => select(editor),
+ }),
+ useTimeAgo: () => "just now",
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: vi.fn() },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/test/issues/${id}`,
+ projectDetail: (id: string) => `/test/projects/${id}`,
+ }),
+ useWorkspaceSlug: () => "test",
+}));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+vi.mock("../issues/components/issue-mention-card", () => ({
+ IssueMentionCard: ({ issueId }: { issueId: string }) => <span>{issueId}</span>,
+}));
+
+vi.mock("../projects/components/project-chip", () => ({
+ ProjectChip: ({ projectId }: { projectId: string }) => <span>{projectId}</span>,
+}));
+
+vi.mock("../editor/link-hover-card", () => ({
+ useLinkHover: () => ({}),
+ LinkHoverCard: () => null,
+}));
+
+vi.mock("../editor/utils/link-handler", () => ({
+ openLink: vi.fn(),
+ isMentionHref: (href?: string) => Boolean(href?.startsWith("mention://")),
+}));
+
+// Expose the sanitized url/filename that survived the schema, so image
+// fixtures can be asserted identically on both surfaces (readonly routes
+// images through <Attachment>, the ui base renders a plain <img>).
+vi.mock("../editor/attachment", () => ({
+ Attachment: ({
+ attachment,
+ }: {
+ attachment: { url: string; filename: string };
+ }) => <img src={attachment.url} alt={attachment.filename} />,
+}));
+
+import { ReadonlyContent } from "../editor/readonly-content";
+
+const PNG_1X1 =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
+
+const SURFACES: ReadonlyArray<{
+ name: string;
+ render: (markdown: string) => HTMLElement;
+}> = [
+ {
+ name: "Chat (ui/markdown)",
+ render: (markdown) => render(<MarkdownBase>{markdown}</MarkdownBase>).container,
+ },
+ {
+ name: "Issue/Comment (ReadonlyContent)",
+ render: (markdown) => render(<ReadonlyContent content={markdown} />).container,
+ },
+];
+
+describe.each(SURFACES)("sanitize contract — $name", ({ render: renderSurface }) => {
+ it("strips <script>", () => {
+ const container = renderSurface("hi\n\n<script>alert(1)</script>");
+
+ expect(container.querySelector("script")).toBeNull();
+ expect(container.textContent).not.toContain("alert(1)");
+ });
+
+ it("strips event-handler attributes from raw HTML", () => {
+ const container = renderSurface('<img src="x" onerror="alert(1)">');
+
+ expect(container.querySelector("[onerror]")).toBeNull();
+ expect(container.innerHTML).not.toContain("onerror");
+ });
+
+ it("neutralizes javascript: hrefs", () => {
+ const container = renderSurface("[click](javascript:alert(1))");
+
+ const href = container.querySelector("a")?.getAttribute("href") ?? "";
+ expect(href.toLowerCase()).not.toContain("javascript:");
+ });
+
+ it("preserves an inline data:image/* src", () => {
+ const container = renderSurface(`![demo](${PNG_1X1})`);
+
+ expect(container.querySelector("img")).toHaveAttribute("src", PNG_1X1);
+ });
+
+ it("blanks a non-image data: URI", () => {
+ const container = renderSurface("![x](data:text/html,<script>alert(1)</script>)");
+
+ expect(container.querySelector("img")?.getAttribute("src") ?? "").toBe("");
+ });
+
+ it("keeps http(s) image src intact", () => {
+ const container = renderSurface("![cat](https://cdn.example.com/cat.png)");
+
+ expect(container.querySelector("img")).toHaveAttribute(
+ "src",
+ "https://cdn.example.com/cat.png",
+ );
+ });
+
+ // The drift this sweep closes: <mark> was whitelisted on readonly only, so
+ // the same content highlighted in a comment and rendered in chat disagreed.
+ it("allows <mark> (==highlight== lowering target)", () => {
+ const container = renderSurface("<mark>hi</mark>");
+
+ expect(container.querySelector("mark")?.textContent).toBe("hi");
+ });
+
+ it("allows the slash:// protocol", () => {
+ const container = renderSurface("[/deploy](slash://skill/abc-123)");
+
+ expect(container.querySelector(".slash-command")?.textContent).toBe("/deploy");
+ });
+});
+
+// Code-block *rendering* is deliberately not asserted cross-surface yet: chat
+// highlights with Shiki and readonly with lowlight, so the emitted class tokens
+// still differ. Converging them is the RichCodeBlock phase of MUL-4922; until
+// the highlight engine is picked, only the schema-level allow-list is shared.
+describe("canonical sanitize schema", () => {
+ it("permits language-/math-/hljs class tokens on <code>", () => {
+ const codeAttrs = markdownSanitizeSchema.attributes?.code ?? [];
+ const patterns = codeAttrs
+ .filter((attr): attr is [string, RegExp] => Array.isArray(attr))
+ .filter(([name]) => name === "className")
+ .map(([, pattern]) => pattern.source);
+
+ expect(patterns).toEqual(
+ expect.arrayContaining(["^language-", "^math-", "^hljs"]),
+ );
+ });
+});
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index c85d9abb2c..534579d057 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -14,9 +14,9 @@
* Call sites:
* - extensions/file-card.tsx FileCardView (Tiptap NodeView)
* - extensions/image-view.tsx ImageView (Tiptap NodeView)
- * - readonly-content.tsx (markdown img + fileCard div renderers)
+ * - rich-content/rich-content.tsx (markdown img + fileCard div renderers,
+ * serving Chat, Issue descriptions and Comments through one renderer)
* - issues/components/comment-card.tsx AttachmentList (standalone fallback)
- * - common/markdown.tsx (chat / skill viewer Markdown wrapper)
*
* The component owns its own preview modal and download dispatcher — callers
* just pass `attachment` and (for editor surfaces) optional editor chrome
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 3ee8e4ba79..327615a670 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -58,6 +58,7 @@ import type { MentionItem } from "./extensions/mention-suggestion";
import type { IssueIdentifierResolver } from "./extensions/issue-identifier-autolink";
import { createEditorExtensions } from "./extensions";
import { uploadAndInsertFile } from "./extensions/file-upload";
+import { configStore } from "@multica/core/config";
import { preprocessMarkdown } from "./utils/preprocess";
import { repairEmptyListItems } from "./utils/repair-list-items";
import { openLink, isMentionHref } from "./utils/link-handler";
@@ -439,7 +440,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const initialMarkdown = value ?? defaultValue ?? "";
const initialContent = initialMarkdown
- ? preprocessMarkdown(initialMarkdown)
+ ? // One-shot read: the editor preprocesses its initial document once at
+ // load. Unlike the readonly renderer it does not need to re-run when
+ // the CDN config lands later — the user's own edits drive the document
+ // from here on.
+ preprocessMarkdown(initialMarkdown, {
+ cdnDomain: configStore.getState().cdnDomain,
+ })
: "";
// With `immediatelyRender: false` the Tiptap instance is created after
// mount, so an imperative `focus()` fired on the same tick (e.g. chat
@@ -623,7 +630,11 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// example `dev.de` used to become a link during a debounce pause).
if (normalizeMarkdown(markdown) === before) return;
- const incoming = markdown ? preprocessMarkdown(markdown) : "";
+ const incoming = markdown
+ ? preprocessMarkdown(markdown, {
+ cdnDomain: configStore.getState().cdnDomain,
+ })
+ : "";
const incomingNormalized = normalizeMarkdown(incoming);
// Normalized-equal short-circuit. Avoids a no-op transaction when the
// preprocessed input serializes to the document already on screen.
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index ccf4be50f3..8659f689a1 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -36,6 +36,14 @@ import { HtmlPreviewBody } from "./html-preview-body";
const CODE_BLOCK_IFRAME_HEIGHT = "h-[480px]";
+/**
+ * Pixel twin of CODE_BLOCK_IFRAME_HEIGHT. The preview iframe is a fixed height,
+ * so the near-viewport lazy shell (rich-content/lazy-rich-block.tsx) can
+ * reserve exactly the space this component will occupy and mount with zero
+ * layout shift. Keep the two in sync.
+ */
+export const HTML_BLOCK_PREVIEW_HEIGHT_PX = 480;
+
// Label shown in the code-block header. Not a translatable string — it's a
// language identifier (matches the `lang === "html"` token below).
const HTML_LANGUAGE_LABEL = "html";
diff --git a/packages/views/editor/mermaid-diagram.tsx b/packages/views/editor/mermaid-diagram.tsx
index 892f475b8a..3f14b69dec 100644
--- a/packages/views/editor/mermaid-diagram.tsx
+++ b/packages/views/editor/mermaid-diagram.tsx
@@ -147,7 +147,7 @@ function getMermaidLayout(svg: string): Size | null {
// in this session. Picked to absorb most issue-detail diagrams without
// excessive empty space; web.dev's CLS guidance recommends reserving any
// such space upfront so async content doesn't shift surrounding layout.
-const MERMAID_SKELETON_HEIGHT_PX = 280;
+export const MERMAID_SKELETON_HEIGHT_PX = 280;
const MERMAID_LAYOUT_CACHE_PREFIX = "multica:mermaid:layout:";
// DJB2 — small, fast, sufficient for sessionStorage cache keys. The chart
@@ -161,6 +161,23 @@ function hashChart(chart: string): string {
return (hash >>> 0).toString(36);
}
+/**
+ * Height to reserve for a diagram that has not rendered yet: the real height
+ * when this exact chart already rendered in this session, otherwise the
+ * skeleton default. Exported so the near-viewport lazy shell
+ * (rich-content/lazy-rich-block.tsx) reserves the SAME space this component
+ * would, instead of maintaining a second guess at the size.
+ *
+ * NOT safe to call during render: it reads sessionStorage, which does not exist
+ * on the server, so the value differs between the server frame and the browser's
+ * hydration frame whenever the cache is warm. Callers must use the skeleton
+ * default for the first frame and call this from an effect (see
+ * useReservedMermaidHeightPx in rich-content/rich-code-block.tsx).
+ */
+export function reservedMermaidHeightPx(chart: string): number {
+ return readCachedLayout(chart)?.height ?? MERMAID_SKELETON_HEIGHT_PX;
+}
+
function readCachedLayout(chart: string): Size | null {
if (typeof window === "undefined") return null;
try {
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index 703dcb5842..0fb60c7af0 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -1,501 +1,46 @@
"use client";
/**
- * ReadonlyContent — lightweight markdown renderer for readonly content display.
+ * ReadonlyContent — compatibility wrapper over the canonical <RichContent>.
*
- * Replaces <ContentEditor editable={false}> for comment cards and other
- * read-only surfaces. Uses react-markdown instead of a full Tiptap/ProseMirror
- * instance, eliminating EditorView, Plugin, and NodeView overhead.
+ * The renderer itself moved to packages/views/rich-content/ (MUL-4922) so Chat,
+ * Issue descriptions and Comments all share ONE implementation of Markdown
+ * parsing, sanitize, fenced-code dispatch, mentions, links and attachments.
+ * This file stays only so existing document-density callers (comment cards,
+ * issue detail, autopilot detail, Markdown attachment preview) keep their
+ * import path and props.
*
- * Visual parity with ContentEditor is achieved by:
- * - Wrapping output in <div class="rich-text-editor readonly"> so the same
- * styles/index.css rules apply to standard HTML tags
- * - Using the same preprocessMarkdown pipeline (mention shortcodes + linkify)
- * - Using lowlight for code highlighting (same engine as Tiptap's CodeBlockLowlight)
- * so .hljs-* CSS rules from styles/code.css produce identical colors
- * - Rendering mentions with the same IssueMentionCard component and .mention class
+ * Do not reintroduce rendering logic here. New behaviour belongs in
+ * RichContent, where every surface picks it up at once.
*/
-import { isValidElement, memo, useMemo, useRef, useState } from "react";
-import ReactMarkdown, {
- defaultUrlTransform,
- type Components,
-} from "react-markdown";
-import type { ReactNode } from "react";
-import rehypeKatex from "rehype-katex";
-import remarkBreaks from "remark-breaks";
-import remarkGfm from "remark-gfm";
-import remarkMath from "remark-math";
-import rehypeRaw from "rehype-raw";
-import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
-import { toHtml } from "hast-util-to-html";
-import { Check, Copy } from "lucide-react";
-import { cn } from "@multica/ui/lib/utils";
-import { copyText } from "@multica/ui/lib/clipboard";
-import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";
+import { memo } from "react";
import type { Attachment } from "@multica/core/types";
-import { useT } from "../i18n";
-import { useNavigation } from "../navigation";
-import { IssueMentionCard } from "../issues/components/issue-mention-card";
-import { useResolveIssueIdentifier } from "../issues/hooks";
-import { ProjectChip } from "../projects/components/project-chip";
-import { useLinkHover, LinkHoverCard } from "./link-hover-card";
-import { openLink, isMentionHref } from "./utils/link-handler";
-import { isAllowedFileCardHref, isIssueIdentifier } from "@multica/ui/markdown";
-import { preprocessMarkdown } from "./utils/preprocess";
-import { highlightToHtml } from "./utils/highlight-markdown";
-import { MermaidDiagram } from "./mermaid-diagram";
-import { HtmlBlockPreview } from "./html-block-preview";
-import { AttachmentDownloadProvider } from "./attachment-download-context";
-import { Attachment as AttachmentRenderer } from "./attachment";
-import { highlightCode } from "./syntax-highlight";
-import "katex/dist/katex.min.css";
-import "./styles/index.css";
-
-// Code fences that the `code` renderer returns as a non-<code> React element
-// (Mermaid diagram, HTML preview iframe). The `pre` renderer below unwraps
-// these so the default <pre><code> envelope doesn't clamp their styles.
-// Anchored to whole class tokens so `language-htmlbars` / `language-mermaidx`
-// don't accidentally match and lose their <pre> wrapper.
-const PRE_UNWRAP_RE = /(^|\s)language-(html|mermaid)(\s|$)/;
-
-// ---------------------------------------------------------------------------
-// Sanitization schema — extends GitHub defaults to allow file-card data attrs
-// ---------------------------------------------------------------------------
-
-const sanitizeSchema = {
- ...defaultSchema,
- // Allow <mark> (text highlight) — emitted by highlightToHtml from `==text==`.
- // It carries no attributes, so only the tag name needs whitelisting.
- tagNames: [...(defaultSchema.tagNames ?? []), "mark"],
- protocols: {
- ...defaultSchema.protocols,
- href: [...(defaultSchema.protocols?.href ?? []), "mention", "slash"],
- // Permit inline data-URI images (QR codes, charts, base64 screenshots).
- // The scheme gate only allows `data:` through here; attributes.img below
- // narrows it to image/* so non-image data URIs are still rejected.
- src: [...(defaultSchema.protocols?.src ?? []), "data"],
- },
- attributes: {
- ...defaultSchema.attributes,
- div: [
- ...(defaultSchema.attributes?.div ?? []),
- "dataType",
- "dataHref",
- "dataFilename",
- ],
- code: [
- ...(defaultSchema.attributes?.code ?? []),
- ["className", /^language-/],
- ["className", /^math-/],
- ["className", /^hljs/],
- ],
- img: [
- // Drop the default plain `src` entry so the value allow-list below is the
- // one findDefinition resolves — it returns the first match by name, so a
- // bare `src` string would otherwise shadow (and disable) the allow-list.
- ...(defaultSchema.attributes?.img ?? []).filter(
- (attr) => (typeof attr === "string" ? attr : attr[0]) !== "src",
- ),
- "alt",
- // Allow inline data:image/* URIs while leaving every other src form
- // (http/https/site-relative) exactly as before: the negative lookahead
- // keeps all non-data values, and data: is narrowed to images only.
- ["src", /^data:image\//i, /^(?!data:)/i],
- ],
- },
-};
-
-// ---------------------------------------------------------------------------
-// URL transform — allow mention:// protocol through react-markdown's sanitizer
-// ---------------------------------------------------------------------------
-
-function urlTransform(url: string): string {
- if (url.startsWith("mention://")) return url;
- if (url.startsWith("slash://skill/")) return url;
- // Allow inline data:image/* URIs — defaultUrlTransform strips every data: URL
- // to '', which would blank the src even after rehype-sanitize keeps it. Kept
- // in sync with the image/* narrowing in sanitizeSchema (protocols.src +
- // attributes.img) so both gates agree on what a valid inline image is.
- if (/^data:image\//i.test(url)) return url;
- return defaultUrlTransform(url);
-}
-
-// ---------------------------------------------------------------------------
-// Custom react-markdown components
-// ---------------------------------------------------------------------------
-
-/**
- * Issue mention chip. Navigation — plain click, modifier click, and the
- * "open issue links in new tab" preference — is owned by the AppLink inside
- * IssueMentionCard; the wrapper only shields surrounding click handlers
- * (e.g. collapsed-comment expanders) from mention clicks.
- */
-function IssueMentionLink({ issueId, label }: { issueId: string; label?: string }) {
- return (
- <span className="inline align-middle" onClick={(e) => e.stopPropagation()}>
- <IssueMentionCard issueId={issueId} fallbackLabel={label} />
- </span>
- );
-}
-
-/**
- * Autolinked bare identifier (e.g. `MUL-123`) routed through
- * `mention://issue/<identifier>` by the readonly preprocessor. Resolves to a
- * real issue in the current workspace; renders a navigable mention on a hit,
- * plain text on a miss / while loading / cross-workspace.
- */
-function AutolinkedIssueMentionLink({ identifier }: { identifier: string }) {
- const issue = useResolveIssueIdentifier(identifier);
- if (!issue) return <>{identifier}</>;
- return <IssueMentionLink issueId={issue.id} label={identifier} />;
-}
-
-function ProjectMentionLink({ projectId, label }: { projectId: string; label?: string }) {
- const { push, openInNewTab } = useNavigation();
- const p = useWorkspacePaths();
- const path = p.projectDetail(projectId);
- return (
- <span
- className="inline align-middle"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (e.metaKey || e.ctrlKey || e.shiftKey) {
- if (openInNewTab) {
- openInNewTab(path, label);
- }
- return;
- }
- push(path);
- }}
- >
- <ProjectChip projectId={projectId} fallbackLabel={label} className="cursor-pointer hover:bg-accent transition-colors" />
- </span>
- );
-}
-
-function getTextContent(node: ReactNode): string {
- if (node == null || typeof node === "boolean") return "";
- if (typeof node === "string" || typeof node === "number") return String(node);
- if (Array.isArray(node)) return node.map(getTextContent).join("");
- if (isValidElement(node)) {
- const props = node.props as { children?: ReactNode };
- return getTextContent(props.children);
- }
- return "";
-}
-
-function ReadonlyCodeBlock({
- children,
- language,
-}: {
- children: ReactNode;
- language?: string;
-}) {
- const { t } = useT("editor");
- const [copied, setCopied] = useState(false);
- const code = useMemo(
- () => getTextContent(children).replace(/\n$/, ""),
- [children],
- );
- const copyLabel = t(($) => $.code_block.copy_code) || "Copy code";
-
- const handleCopy = async () => {
- if (!code) return;
- if (await copyText(code)) {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }
- };
-
- return (
- <div className="code-block-wrapper group/code relative my-3">
- <div className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100">
- {/* Same hover chrome as the editable code block's header
- (code-block-view.tsx): language label + copy. */}
- {language && (
- <span className="text-xs text-muted-foreground select-none">
- {language}
- </span>
- )}
- <button
- type="button"
- onClick={handleCopy}
- className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title={copyLabel}
- aria-label={copyLabel}
- >
- {copied ? (
- <Check className="h-3.5 w-3.5" />
- ) : (
- <Copy className="h-3.5 w-3.5" />
- )}
- </button>
- </div>
- {/* No extra right padding: `.rich-text-editor pre` outranks utility
- padding classes anyway, and the editable NodeView uses the same
- 1rem — keeping them identical keeps line wrapping identical. */}
- <pre className="!m-0">{children}</pre>
- </div>
- );
-}
-
-// Named component so it can call useWorkspaceSlug() — arrow function inlined
-// inside `components` below would still work, but extracting it keeps the
-// hook usage explicit and avoids hook-in-object-literal surprises.
-function ReadonlyLink({
- href,
- children,
-}: {
- href?: string;
- children?: React.ReactNode;
-}) {
- const slug = useWorkspaceSlug();
-
- if (href?.startsWith("slash://skill/")) {
- return <span className="slash-command">{children}</span>;
- }
-
- if (isMentionHref(href)) {
- const match = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/);
- if (match?.[1] === "issue" && match[2]) {
- // A bare identifier (from the autolink preprocessor) is carried as the id
- // segment; a real mention carries a UUID. Dispatch on the id shape.
- if (isIssueIdentifier(match[2])) {
- return <AutolinkedIssueMentionLink identifier={match[2]} />;
- }
- const label =
- typeof children === "string"
- ? children
- : Array.isArray(children)
- ? children.join("")
- : undefined;
- return <IssueMentionLink issueId={match[2]} label={label} />;
- }
- if (match?.[1] === "project" && match[2]) {
- const label =
- typeof children === "string"
- ? children
- : Array.isArray(children)
- ? children.join("")
- : undefined;
- return <ProjectMentionLink projectId={match[2]} label={label} />;
- }
- // Member / agent / all mentions
- return <span className="mention">{children}</span>;
- }
-
- // Regular links — open directly on click
- return (
- <a
- href={href}
- onClick={(e) => {
- e.preventDefault();
- if (href) openLink(href, slug);
- }}
- >
- {children}
- </a>
- );
-}
-
-function buildComponents(): Partial<Components> {
- return {
- // Links — route mention:// to mention components, others show preview card
- a: ReadonlyLink,
-
- // Images — unified through <Attachment>. The resolver context provided
- // by AttachmentDownloadProvider (mounted in ReadonlyContent below) turns
- // a CDN URL into a full record when possible; external URLs render as
- // plain images with lightbox-via-preview-modal. forceKind is mandatory
- // here because markdown `![]()` carries no content-type and alt is
- // commonly empty or descriptive — without it images fall through to
- // the file-card chrome.
- img: ({ src, alt }) => (
- <AttachmentRenderer
- attachment={{
- kind: "url",
- url: typeof src === "string" ? src : "",
- filename: alt ?? "",
- forceKind: "image",
- }}
- />
- ),
-
- // FileCard — intercept <div data-type="fileCard"> from preprocessMarkdown
- div: ({ node, children, ...props }) => {
- const dataType = node?.properties?.dataType as string | undefined;
- if (dataType === "fileCard") {
- const rawHref = (node?.properties?.dataHref as string) || "";
- const href = isAllowedFileCardHref(rawHref) ? rawHref : "";
- const filename = (node?.properties?.dataFilename as string) || "";
- return (
- <AttachmentRenderer
- attachment={{ kind: "url", url: href, filename }}
- />
- );
- }
- return <div {...props}>{children}</div>;
- },
-
- // Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)
- table: ({ children }) => (
- <div className="tableWrapper">
- <table>{children}</table>
- </div>
- ),
-
- // Code — lowlight highlighting for blocks, plain render for inline
- code: ({ className, children, node, ...props }) => {
- const lang = /language-(\w+)/.exec(className || "")?.[1];
- const isBlock =
- node?.position &&
- node.position.start.line !== node.position.end.line;
-
- if (isBlock && lang === "mermaid") {
- return <MermaidDiagram chart={String(children).replace(/\n$/, "")} />;
- }
- if (isBlock && lang === "html") {
- // Like Mermaid, return the React element directly here and rely on
- // the `pre` renderer below to unwrap it — react-markdown otherwise
- // wraps `code` children in a `<pre>` whose monospace + overflow
- // styles would clamp the preview iframe.
- return <HtmlBlockPreview html={String(children).replace(/\n$/, "")} />;
- }
-
- if (!isBlock && !lang) {
- // Inline code — CSS handles styling via .rich-text-editor code
- return <code {...props}>{children}</code>;
- }
-
- // Block code — highlight with lowlight, output hljs classes
- const code = String(children).replace(/\n$/, "");
- try {
- const tree = highlightCode(code, lang);
- const html = toHtml(tree);
- if (html) {
- return (
- <code
- className={cn("hljs", lang && `language-${lang}`)}
- dangerouslySetInnerHTML={{ __html: html }}
- />
- );
- }
- } catch {
- // fall through to plain render
- }
- return (
- <code className={cn("hljs", className)} {...props}>
- {children}
- </code>
- );
- },
-
- // Pre — wrap regular code fences with copy chrome.
- // Special-case Mermaid / HtmlBlockPreview returned from the `code`
- // renderer above so the outer `<pre>` does not wrap them — this is the
- // standard two-layer pattern used to escape react-markdown's default
- // `<pre><code>` envelope.
- pre: ({ children }) => {
- // react-markdown calls `pre` BEFORE invoking the `code` renderer —
- // `children` is the unrendered `<code>` element from the AST. So we
- // identify "this block was meant to be unwrapped" by inspecting the
- // child's className (`language-mermaid`, `language-html`), not by
- // checking `children.type === MermaidDiagram`, which never matches.
- //
- // Match by exact class token: a substring `includes("language-html")`
- // would also fire on neighboring languages like `language-htmlbars`
- // and silently strip their <pre> wrapper.
- let language: string | undefined;
- if (isValidElement(children)) {
- const childProps = children.props as { className?: string };
- if (PRE_UNWRAP_RE.test(childProps.className ?? "")) {
- return <>{children}</>;
- }
- language = /language-(\w+)/.exec(childProps.className ?? "")?.[1];
- }
- return <ReadonlyCodeBlock language={language}>{children}</ReadonlyCodeBlock>;
- },
- };
-}
-
-// ---------------------------------------------------------------------------
-// Component
-// ---------------------------------------------------------------------------
+import { RichContent } from "../rich-content";
interface ReadonlyContentProps {
content: string;
className?: string;
/**
- * Attachments associated with the surrounding entity (comment / issue
- * body). When the markdown contains an inline `<img>` or file card whose
- * URL matches one of these attachments, the download button re-signs the
- * URL at click time via `useDownloadAttachment` instead of opening the
- * potentially stale link embedded in the markdown.
- *
- * Callers SHOULD pass a stable reference (e.g. the field on a memoized
- * timeline entry); a fresh array on every parent render busts the memo.
+ * Attachments associated with the surrounding entity (comment / issue body).
+ * Callers SHOULD pass a stable reference; a fresh array on every parent
+ * render busts the memo.
*/
attachments?: Attachment[];
}
-// Memoized so a long timeline of comments (Inbox + IssueDetail) does not
-// re-run the full react-markdown + rehype-* + lowlight pipeline on every
-// parent re-render. Props are `content`/`className`/`attachments`, all
-// shallow-comparable; stability is the caller's responsibility for the
-// array.
export const ReadonlyContent = memo(function ReadonlyContent({
content,
className,
attachments,
}: ReadonlyContentProps) {
- const processed = useMemo(
- () =>
- highlightToHtml(
- preprocessMarkdown(content, { autolinkIssueIdentifiers: true }),
- ),
- [content],
- );
- const wrapperRef = useRef<HTMLDivElement>(null);
- const hover = useLinkHover(wrapperRef);
-
- // Components map is now static — all attachment-aware logic lives in
- // <Attachment>, which reads the surrounding AttachmentDownloadProvider.
- const components = useMemo(() => buildComponents(), []);
-
- // Memoize the whole react-markdown subtree on its only real inputs
- // (`processed` + `components`). Unrelated parent re-renders (e.g. a sibling
- // agent task streaming over WebSocket fires one every ~100ms) would otherwise
- // re-run react-markdown, which hands `<code>` a fresh `dangerouslySetInnerHTML`
- // object each time; React then rewrites the highlighted innerHTML even though
- // the HTML string is byte-identical, tearing down and rebuilding every hljs
- // <span> — which collapses any active text selection inside a code block
- // (MUL-3621). A stable element reference lets React bail out of the subtree.
- const markdown = useMemo(
- () => (
- <ReactMarkdown
- remarkPlugins={[
- [remarkMath, { singleDollarTextMath: false }],
- remarkBreaks,
- [remarkGfm, { singleTilde: false }],
- ]}
- rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]}
- urlTransform={urlTransform}
- components={components}
- >
- {processed}
- </ReactMarkdown>
- ),
- [processed, components],
- );
-
return (
- <AttachmentDownloadProvider attachments={attachments}>
- <div ref={wrapperRef} className={cn("rich-text-editor readonly text-sm", className)}>
- {markdown}
- <LinkHoverCard {...hover} />
- </div>
- </AttachmentDownloadProvider>
+ <RichContent
+ content={content}
+ attachments={attachments}
+ density="document"
+ phase="settled"
+ className={className}
+ />
);
});
diff --git a/packages/views/editor/utils/preprocess.ts b/packages/views/editor/utils/preprocess.ts
index 203aaf0a7e..61f5aefa7e 100644
--- a/packages/views/editor/utils/preprocess.ts
+++ b/packages/views/editor/utils/preprocess.ts
@@ -4,7 +4,6 @@ import {
preprocessFileCards,
preprocessIssueIdentifiers,
} from "@multica/ui/markdown";
-import { configStore } from "@multica/core/config";
/**
* Preprocess a markdown string before loading into Tiptap via contentType: 'markdown'.
@@ -28,13 +27,22 @@ import { configStore } from "@multica/core/config";
* identifier string (not a real UUID) and corrupt the saved markdown. Only the
* readonly renderer (which resolves the identifier to a UUID at render time)
* passes it.
+ *
+ * `cdnDomain` is an explicit parameter rather than an imperative
+ * `configStore.getState()` read inside this function. The CDN config arrives
+ * asynchronously after auth, so a one-shot read made this transform silently
+ * time-dependent: content rendered before the config landed kept its legacy CDN
+ * links as plain anchors forever, because nothing re-ran the transform. Passing
+ * the value in lets a reactive caller (RichContent, which subscribes to the
+ * store) put it in its memo dependencies, while a one-shot caller (the Tiptap
+ * editor, which preprocesses once at load) can still read the store itself.
*/
export function preprocessMarkdown(
markdown: string,
- opts?: { autolinkIssueIdentifiers?: boolean },
+ opts: { cdnDomain: string; autolinkIssueIdentifiers?: boolean },
): string {
if (!markdown) return "";
- const cdnDomain = configStore.getState().cdnDomain;
+ const { cdnDomain } = opts;
const step1 = preprocessMentionShortcodes(markdown);
const step2 = opts?.autolinkIssueIdentifiers
? preprocessIssueIdentifiers(step1)
diff --git a/packages/views/package.json b/packages/views/package.json
index 9855631213..dd63d1649f 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -11,7 +11,6 @@
"exports": {
"./navigation": "./navigation/index.ts",
"./common/actor-avatar": "./common/actor-avatar.tsx",
- "./common/markdown": "./common/markdown.tsx",
"./editor": "./editor/index.ts",
"./issues/components": "./issues/components/index.ts",
"./issues/hooks": "./issues/hooks/index.ts",
@@ -89,6 +88,7 @@
"hast-util-to-html": "^9.0.5",
"katex": "catalog:",
"lowlight": "^3.3.0",
+ "mdast-util-from-markdown": "^2.0.3",
"mermaid": "catalog:",
"motion": "^12.38.0",
"pinyin-pro": "3.26.0",
diff --git a/packages/views/rich-content/cdn-config-reactivity.test.tsx b/packages/views/rich-content/cdn-config-reactivity.test.tsx
new file mode 100644
index 0000000000..e3684a66a0
--- /dev/null
+++ b/packages/views/rich-content/cdn-config-reactivity.test.tsx
@@ -0,0 +1,128 @@
+/**
+ * Late CDN config must reprocess already-rendered content (MUL-4922).
+ *
+ * The CDN domain is fetched asynchronously after auth. File-card detection
+ * happens in the markdown preprocess step, which used to read the domain once,
+ * imperatively, at render time — so content that rendered before the config
+ * landed kept its legacy CDN links as plain anchors permanently. Nothing
+ * re-ran the transform, because the memo only depended on `content`.
+ *
+ * This drives the real store: render with an empty domain, then publish the
+ * config the way AuthInitializer does, and assert the block upgrades.
+ */
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, render } from "@testing-library/react";
+import { configStore } from "@multica/core/config";
+
+vi.mock("../issues/hooks", () => ({
+ useResolveIssueIdentifier: () => null,
+}));
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string) => select(editor),
+ }),
+ useTimeAgo: () => "just now",
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: vi.fn() },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/acme/issues/${id}`,
+ projectDetail: (id: string) => `/acme/projects/${id}`,
+ }),
+ useWorkspaceSlug: () => "acme",
+}));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+vi.mock("../issues/components/issue-mention-card", () => ({
+ IssueMentionCard: ({ issueId }: { issueId: string }) => <span>{issueId}</span>,
+}));
+
+vi.mock("../projects/components/project-chip", () => ({
+ ProjectChip: ({ projectId }: { projectId: string }) => <span>{projectId}</span>,
+}));
+
+vi.mock("../editor/link-hover-card", () => ({
+ useLinkHover: () => ({}),
+ LinkHoverCard: () => null,
+}));
+
+// Surface what the file-card renderer received, so the assertion is about the
+// emitted attachment rather than incidental chrome.
+vi.mock("../editor/attachment", () => ({
+ Attachment: ({ attachment }: { attachment: { url: string; filename: string } }) => (
+ <span data-testid="file-card" data-url={attachment.url}>
+ {attachment.filename}
+ </span>
+ ),
+}));
+
+import { RichContent } from "./rich-content";
+
+const CDN_DOMAIN = "multica-static.example.com";
+const FILE_URL = `https://${CDN_DOMAIN}/workspaces/w1/files/report.pdf`;
+// Legacy file-card syntax is a link ON ITS OWN LINE (FILE_LINK_LINE is
+// anchored); an inline link is deliberately not a card.
+const CONTENT = `Attached:\n\n[report.pdf](${FILE_URL})`;
+
+beforeEach(() => {
+ configStore.setState({ cdnDomain: "", cdnSigned: false });
+});
+
+describe("RichContent CDN config reactivity", () => {
+ it("upgrades a legacy CDN link to a file card when the config arrives late", () => {
+ const { container } = render(<RichContent content={CONTENT} />);
+
+ // Config has not landed: the CDN host is unknown, so this is still a link.
+ expect(container.querySelector("[data-testid='file-card']")).toBeNull();
+ expect(container.querySelector(`a[href="${FILE_URL}"]`)).not.toBeNull();
+
+ // AuthInitializer publishes the config after its background fetch resolves.
+ act(() => {
+ configStore.getState().setCdnConfig({ cdnDomain: CDN_DOMAIN });
+ });
+
+ const card = container.querySelector("[data-testid='file-card']");
+ expect(card).not.toBeNull();
+ expect(card?.getAttribute("data-url")).toBe(FILE_URL);
+ });
+
+ it("renders the file card immediately when the config is already present", () => {
+ configStore.setState({ cdnDomain: CDN_DOMAIN });
+
+ const { container } = render(<RichContent content={CONTENT} />);
+
+ expect(container.querySelector("[data-testid='file-card']")).not.toBeNull();
+ });
+
+ it("leaves non-CDN links alone when the config arrives", () => {
+ // Same shape as CONTENT — only the hostname differs — so the assertion is
+ // about CDN matching, not about link placement.
+ const external = "Attached:\n\n[the spec](https://example.com/spec.pdf)";
+ const { container } = render(<RichContent content={external} />);
+
+ act(() => {
+ configStore.getState().setCdnConfig({ cdnDomain: CDN_DOMAIN });
+ });
+
+ expect(container.querySelector("[data-testid='file-card']")).toBeNull();
+ expect(
+ container.querySelector('a[href="https://example.com/spec.pdf"]'),
+ ).not.toBeNull();
+ });
+});
diff --git a/packages/views/rich-content/index.ts b/packages/views/rich-content/index.ts
new file mode 100644
index 0000000000..b1bbd9eca0
--- /dev/null
+++ b/packages/views/rich-content/index.ts
@@ -0,0 +1,12 @@
+export {
+ RichContent,
+ type RichContentProps,
+ type RichContentDensity,
+ type RichContentPhase,
+} from "./rich-content";
+export {
+ isRichFenceLanguage,
+ shouldUpgradeFence,
+ type RichFenceLanguage,
+} from "./rich-code-block";
+export { computeClosedFenceOffsets } from "./streaming-fence";
diff --git a/packages/views/rich-content/lazy-rich-block.test.tsx b/packages/views/rich-content/lazy-rich-block.test.tsx
new file mode 100644
index 0000000000..6cb6958e12
--- /dev/null
+++ b/packages/views/rich-content/lazy-rich-block.test.tsx
@@ -0,0 +1,395 @@
+/**
+ * Near-viewport lazy shell (MUL-4922 performance contract).
+ *
+ * jsdom has no IntersectionObserver, so these tests install a controllable
+ * fake: it records observed elements and lets a test decide when a block
+ * becomes near-viewport. That makes the deferral, the latch and the size
+ * reservation observable rather than assumed.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, render, screen } from "@testing-library/react";
+import { renderToString } from "react-dom/server";
+import { createRoot, hydrateRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { LazyRichBlock } from "./lazy-rich-block";
+import { RichContentScrollRootProvider } from "./scroll-root";
+import { resetMountedBlocks } from "./mounted-block-registry";
+
+type IOCallback = (entries: { isIntersecting: boolean }[]) => void;
+
+interface FakeObserver {
+ callback: IOCallback;
+ options?: IntersectionObserverInit;
+ observed: Element[];
+ disconnected: boolean;
+}
+
+let observers: FakeObserver[] = [];
+
+beforeEach(() => {
+ observers = [];
+ resetMountedBlocks();
+ class FakeIntersectionObserver {
+ private readonly self: FakeObserver;
+ constructor(callback: IOCallback, options?: IntersectionObserverInit) {
+ this.self = { callback, options, observed: [], disconnected: false };
+ observers.push(this.self);
+ }
+ observe(el: Element) {
+ this.self.observed.push(el);
+ }
+ disconnect() {
+ this.self.disconnected = true;
+ }
+ unobserve() {}
+ takeRecords() {
+ return [];
+ }
+ }
+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+/** Fire the near-viewport signal on every live observer. */
+function enterViewport() {
+ act(() => {
+ for (const o of observers) o.callback([{ isIntersecting: true }]);
+ });
+}
+
+const Expensive = () => <div data-testid="expensive">diagram</div>;
+
+describe("LazyRichBlock", () => {
+ it("does not mount its child until the block is near the viewport", () => {
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(screen.queryByTestId("expensive")).toBeNull();
+ expect(observers).toHaveLength(1);
+ expect(observers[0]?.observed).toHaveLength(1);
+ });
+
+ it("mounts the child once it becomes near-viewport", () => {
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ expect(screen.queryByTestId("expensive")).toBeNull();
+
+ enterViewport();
+
+ expect(screen.getByTestId("expensive")).toBeInTheDocument();
+ });
+
+ // The latch: re-running Mermaid / rebuilding an iframe on every scroll pass
+ // would be worse than mounting eagerly once.
+ it("stops observing after mounting so the block never unmounts", () => {
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ enterViewport();
+
+ expect(observers[0]?.disconnected).toBe(true);
+
+ // A later "left the viewport" signal must not tear the block down.
+ act(() => {
+ observers[0]?.callback([{ isIntersecting: false }]);
+ });
+ expect(screen.getByTestId("expensive")).toBeInTheDocument();
+ });
+
+ // Howard's stated risk: lazy mounting must not disturb Virtuoso's height
+ // measurement. The shell therefore reserves the same space before and after.
+ it("reserves the same height before and after mount", () => {
+ const { container } = render(
+ <LazyRichBlock reservedHeightPx={480}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
+
+ expect(shell.style.minHeight).toBe("480px");
+ expect(shell.hasAttribute("data-mounted")).toBe(false);
+
+ enterViewport();
+
+ expect(shell.style.minHeight).toBe("480px");
+ expect(shell.hasAttribute("data-mounted")).toBe(true);
+ });
+
+ it("watches an area larger than the viewport so blocks are ready on arrival", () => {
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ const margin = observers[0]?.options?.rootMargin ?? "";
+ const topPx = Number.parseInt(margin.split(" ")[0] ?? "0", 10);
+ // Must exceed the chat list's own overscan (600px bottom) or a block would
+ // still be blank when Virtuoso has already rendered its row.
+ expect(topPx).toBeGreaterThan(600);
+ });
+
+ // Chat scrolls inside its own element. With the default (viewport) root,
+ // rootMargin expands the wrong box, so a block only loads once it is already
+ // visible — the preloading is silently dead in the surface that needs it most.
+ it("observes against the surface's scroll root when one is provided", () => {
+ const scrollRoot = document.createElement("div");
+ document.body.appendChild(scrollRoot);
+
+ render(
+ <RichContentScrollRootProvider scrollRoot={scrollRoot}>
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>
+ </RichContentScrollRootProvider>,
+ );
+
+ expect(observers[0]?.options?.root).toBe(scrollRoot);
+ scrollRoot.remove();
+ });
+
+ it("falls back to the viewport root for page-scrolled surfaces", () => {
+ // Issue description / Comment scroll with the page; a null root is correct.
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(observers[0]?.options?.root ?? null).toBeNull();
+ });
+
+ it("mounts via an effect when IntersectionObserver is unavailable", () => {
+ vi.unstubAllGlobals();
+ vi.stubGlobal("IntersectionObserver", undefined);
+
+ render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ // Degrading to eager mount is correct; rendering nothing would not be.
+ // The mount happens in an effect (not in the initial state) so the first
+ // committed frame still matches what a server render would produce — see
+ // the SSR suite below.
+ expect(screen.getByTestId("expensive")).toBeInTheDocument();
+ });
+});
+
+/**
+ * Virtualized-row recycling.
+ *
+ * Chat's list unmounts rows that scroll far enough away. A `mounted` flag held
+ * only in component state disappears with the row, so scrolling back would
+ * re-run Mermaid, rebuild the sandboxed iframe and drop the viewer's pan/zoom —
+ * turning the one-time mount cost into a per-pass cost. The latch therefore
+ * lives outside the component, keyed by content.
+ */
+describe("LazyRichBlock across row recycling", () => {
+ const SOURCE = "flowchart LR\n A --> B";
+
+ beforeEach(() => {
+ resetMountedBlocks();
+ });
+
+ it("re-mounts a recycled block immediately, without waiting to be seen again", () => {
+ const first = render(
+ <LazyRichBlock reservedHeightPx={280} sourceKey={SOURCE}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ enterViewport();
+ expect(first.getByTestId("expensive")).toBeInTheDocument();
+
+ // Virtuoso recycles the row: the whole subtree is unmounted.
+ first.unmount();
+ observers = [];
+
+ // The row comes back. No intersection is reported this time — the block was
+ // already built once, so it must not wait to be observed again.
+ const second = render(
+ <LazyRichBlock reservedHeightPx={280} sourceKey={SOURCE}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(second.getByTestId("expensive")).toBeInTheDocument();
+ });
+
+ it("does not resurrect a different block that was never mounted", () => {
+ const first = render(
+ <LazyRichBlock reservedHeightPx={280} sourceKey={SOURCE}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ enterViewport();
+ first.unmount();
+ observers = [];
+
+ // Different content => different key => still deferred.
+ const other = render(
+ <LazyRichBlock reservedHeightPx={280} sourceKey="graph TD\n X --> Y">
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(other.queryByTestId("expensive")).toBeNull();
+ });
+
+ it("keeps deferring when no sourceKey is supplied", () => {
+ // Without an identity there is nothing to remember; the block must not be
+ // treated as already-mounted.
+ const first = render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ enterViewport();
+ first.unmount();
+ observers = [];
+
+ const second = render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(second.queryByTestId("expensive")).toBeNull();
+ });
+});
+
+/**
+ * Server/client determinism.
+ *
+ * The initial `mounted` state must not be derived from feature detection. If it
+ * were, the server (no `window`) and the browser (has IntersectionObserver)
+ * would disagree on the very first frame: React would find different markup
+ * during hydration, and the server render would silently bypass the lazy gate
+ * it exists to enforce. `"use client"` does not exempt a component from Next's
+ * server render, so this has to hold.
+ */
+describe("LazyRichBlock SSR", () => {
+ /**
+ * Render the way a server would.
+ *
+ * jsdom always provides `window`, so simply calling renderToString here would
+ * take the SAME feature-detection branch as the browser and could not observe
+ * the mismatch at all. Removing IntersectionObserver for the duration
+ * reproduces the real asymmetry: on a server the detection says
+ * "unsupported", in the browser it says "supported". A component whose first
+ * frame depends on that answer renders differently in the two environments —
+ * which is precisely the bug.
+ */
+ function serverRender(ui: Parameters<typeof renderToString>[0]): string {
+ const browserObserver = globalThis.IntersectionObserver;
+ vi.stubGlobal("IntersectionObserver", undefined);
+ try {
+ return renderToString(ui);
+ } finally {
+ vi.stubGlobal("IntersectionObserver", browserObserver);
+ }
+ }
+
+ it("renders the placeholder, not the block, on the server", () => {
+ const html = serverRender(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ expect(html).toContain("data-rich-block-shell");
+ // The expensive subtree must not be in server output: SSR has no viewport,
+ // so nothing is near it.
+ expect(html).not.toContain("expensive");
+ expect(html).not.toContain("data-mounted");
+ });
+
+ it("hydrates the server markup without a mismatch", async () => {
+ const html = serverRender(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ document.body.appendChild(container);
+
+ const errors: string[] = [];
+ const errorSpy = vi.spyOn(console, "error").mockImplementation((...args) => {
+ errors.push(args.map(String).join(" "));
+ });
+
+ let root: ReturnType<typeof hydrateRoot> | undefined;
+ await act(async () => {
+ root = hydrateRoot(
+ container,
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ });
+
+ const hydrationErrors = errors.filter((e) =>
+ /hydrat|did not match|mismatch/i.test(e),
+ );
+ expect(hydrationErrors).toEqual([]);
+
+ errorSpy.mockRestore();
+ await act(async () => {
+ root?.unmount();
+ });
+ container.remove();
+ });
+
+ it("produces the same first frame on server and client", () => {
+ // Same component, both environments, IntersectionObserver present on the
+ // client — the frames must be identical before any effect runs.
+ const serverHtml = serverRender(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ // No act(): flushing effects is exactly what we must NOT do here, because
+ // the comparison is against the first committed frame.
+ flushSync(() => {
+ root.render(
+ <LazyRichBlock reservedHeightPx={280}>
+ <Expensive />
+ </LazyRichBlock>,
+ );
+ });
+ const clientFirstFrame = container.innerHTML;
+
+ // Normalize inline-style serialization only: React's server renderer emits
+ // `min-height:280px` while the browser's CSSOM round-trips it as
+ // `min-height: 280px;`. That difference is cosmetic — React hydration does
+ // not string-compare markup — and the hydration test above is the
+ // authoritative check. Everything else is compared verbatim.
+ const normalize = (html: string) =>
+ html.replace(/style="([^"]*)"/g, (_, css: string) =>
+ `style="${css.replace(/\s*;\s*$/, "").replace(/:\s+/g, ":")}"`,
+ );
+
+ expect(normalize(clientFirstFrame)).toBe(normalize(serverHtml));
+
+ act(() => root.unmount());
+ container.remove();
+ });
+});
diff --git a/packages/views/rich-content/lazy-rich-block.tsx b/packages/views/rich-content/lazy-rich-block.tsx
new file mode 100644
index 0000000000..605aa28c85
--- /dev/null
+++ b/packages/views/rich-content/lazy-rich-block.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+/**
+ * LazyRichBlock — near-viewport, stable-size mount gate for rich blocks
+ * (MUL-4922 performance contract).
+ *
+ * A long chat session or a long comment thread can contain dozens of Mermaid
+ * diagrams and sandboxed HTML iframes. Instantiating them all at once costs a
+ * Mermaid render (async, layout-heavy) and an iframe (its own document +
+ * script execution) per block, whether or not the user ever scrolls to them.
+ * This shell defers each rich leaf until it is near the viewport.
+ *
+ * Two properties make this safe inside Virtuoso's virtualized list:
+ *
+ * 1. STABLE SIZE. The shell reserves the block's expected height BEFORE mounting
+ * and keeps that reservation as a `min-height` afterwards. Without it, a
+ * block would measure 0px while off-screen and jump to its real height on
+ * mount — which is precisely the measurement churn that makes a virtualized
+ * list mis-estimate item sizes and lose scroll position. The reservation is
+ * not a guess local to this file: it comes from the leaf components
+ * themselves (a session-cached real diagram height when available, else their
+ * documented skeleton/iframe height), so a cache hit mounts with zero shift.
+ *
+ * 2. MOUNT-ONCE LATCH. Once mounted the block is never unmounted, even when
+ * scrolled far away. Unmounting would re-run Mermaid and rebuild the iframe
+ * on every pass, and would discard the viewer's pan/zoom state — trading a
+ * one-time cost for a repeated one. Memory is bounded by "blocks the user
+ * actually scrolled past", not by the whole transcript.
+ */
+
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { useRichContentScrollRoot } from "./scroll-root";
+import {
+ hasBlockMounted,
+ markBlockMounted,
+ mountedBlockKey,
+} from "./mounted-block-registry";
+
+// Restoring an already-mounted block must happen before paint, or a recycled
+// Virtuoso row would flash its placeholder on the way back into view.
+// useLayoutEffect does not run on the server (and warns if called there), so the
+// server takes the plain-effect branch — neither runs during SSR, so the first
+// frame is unaffected either way.
+const useIsomorphicLayoutEffect =
+ typeof window !== "undefined" ? useLayoutEffect : useEffect;
+
+/**
+ * How far outside the viewport a block starts mounting. Sized to cover
+ * Virtuoso's own overscan (`increaseViewportBy` is 400px top / 600px bottom in
+ * the chat list) so a block is ready by the time it is scrolled into view,
+ * without eagerly building the whole transcript.
+ */
+const NEAR_VIEWPORT_ROOT_MARGIN = "800px 0px";
+
+function supportsIntersectionObserver(): boolean {
+ return typeof window !== "undefined" && typeof window.IntersectionObserver === "function";
+}
+
+export function LazyRichBlock({
+ reservedHeightPx,
+ sourceKey,
+ children,
+}: {
+ /** Expected height of the mounted block; reserved before and after mount. */
+ reservedHeightPx: number;
+ /**
+ * Stable identity for this block's content. Used to remember that it has
+ * already been mounted, so a virtualized row that gets recycled and later
+ * re-created does not pay the mount cost again.
+ */
+ sourceKey?: string;
+ children: ReactNode;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const scrollRoot = useRichContentScrollRoot();
+ const registryKey = sourceKey == null ? null : mountedBlockKey("rich", sourceKey);
+ // ALWAYS false on the first render, on both server and client.
+ //
+ // Deriving this from feature detection (`typeof window`, IntersectionObserver
+ // presence) would make the first frame environment-dependent: the server, with
+ // no `window`, would render the full Mermaid/HTML subtree while the browser's
+ // hydration pass renders a placeholder — a markup mismatch, and an SSR that
+ // silently bypasses the lazy gate it is supposed to honour. `"use client"`
+ // does not opt a component out of Next's server render, so the only safe
+ // initial state is the one both environments can agree on.
+ //
+ // Everything environment-specific happens in the effect below, which never
+ // runs on the server.
+ const [mounted, setMounted] = useState(false);
+
+ // Restore a block this session has already built. Kept out of the initial
+ // state for the same reason as everything else here: the registry is empty on
+ // the server, so seeding from it would make the first frame differ between
+ // server and client.
+ useIsomorphicLayoutEffect(() => {
+ if (mounted || registryKey == null) return;
+ if (hasBlockMounted(registryKey)) setMounted(true);
+ }, [mounted, registryKey]);
+
+ useEffect(() => {
+ if (mounted) return;
+
+ // No IntersectionObserver (jsdom, older webviews): fall back to mounting
+ // eagerly. This runs in an effect rather than in the initial state so the
+ // first committed frame still matches the server's.
+ if (!supportsIntersectionObserver()) {
+ setMounted(true);
+ return;
+ }
+
+ const el = ref.current;
+ if (!el) return;
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ // Latch: stop observing so the block never unmounts on scroll-away.
+ setMounted(true);
+ observer.disconnect();
+ }
+ },
+ {
+ // Clip against the surface's own scroll container when there is one.
+ // With the default (viewport) root, rootMargin would expand the wrong
+ // box and a Chat block would only load once already visible.
+ root: scrollRoot,
+ rootMargin: NEAR_VIEWPORT_ROOT_MARGIN,
+ },
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [mounted, scrollRoot]);
+
+ // Record the mount so a recycled row can skip straight to the built block.
+ useEffect(() => {
+ if (mounted && registryKey != null) markBlockMounted(registryKey);
+ }, [mounted, registryKey]);
+
+ return (
+ <div
+ ref={ref}
+ data-rich-block-shell=""
+ data-mounted={mounted ? "" : undefined}
+ // The reservation persists after mount so the shell never shrinks back
+ // and re-triggers a measurement pass. Real diagrams and the fixed-height
+ // HTML preview normally exceed it, so it rarely adds visible space.
+ style={{ minHeight: reservedHeightPx }}
+ >
+ {mounted ? children : <RichBlockPlaceholder />}
+ </div>
+ );
+}
+
+/**
+ * Pre-mount placeholder. Deliberately inert and unlabelled-as-loading: it fills
+ * reserved space rather than announcing work, because nothing is loading yet —
+ * the block simply has not been scrolled near.
+ */
+function RichBlockPlaceholder() {
+ return (
+ <div
+ className="my-3 h-full w-full rounded-md border border-border/50 bg-muted/20"
+ aria-hidden="true"
+ />
+ );
+}
diff --git a/packages/views/rich-content/mounted-block-registry.ts b/packages/views/rich-content/mounted-block-registry.ts
new file mode 100644
index 0000000000..51261a24c5
--- /dev/null
+++ b/packages/views/rich-content/mounted-block-registry.ts
@@ -0,0 +1,56 @@
+/**
+ * Records which rich blocks have already been mounted in this page session.
+ *
+ * The "mount once" guarantee cannot live in component state alone. Chat's list
+ * is virtualized: scrolling far enough unmounts a row entirely, taking any
+ * local `mounted` flag with it. Scrolling back would then re-run Mermaid, build
+ * a fresh sandboxed iframe, and discard the viewer's pan/zoom — the repeated
+ * cost the lazy shell exists to avoid, reappearing on every pass.
+ *
+ * Keyed by a hash of language + source, so the same diagram is recognised
+ * wherever it reappears (a recycled Virtuoso row, the live -> persisted handoff,
+ * or the same content quoted in two places).
+ *
+ * Deliberately module-level rather than a store: this is render bookkeeping, not
+ * application state. It is never persisted and never read on the server.
+ */
+
+// Bounded so a very long session cannot grow this without limit. Entries are
+// short hash strings and eviction is oldest-first (Set preserves insertion
+// order); evicting a block only means it pays its mount cost once more.
+const MAX_TRACKED_BLOCKS = 500;
+
+const mountedBlocks = new Set<string>();
+
+// DJB2 — the same cheap, synchronous hash the Mermaid layout cache uses. The
+// source text itself is unsuitable as a key: a transcript full of large
+// diagrams would keep every one of them alive in this Set.
+function hashSource(source: string): string {
+ let hash = 5381;
+ for (let i = 0; i < source.length; i++) {
+ hash = ((hash << 5) + hash) ^ source.charCodeAt(i);
+ }
+ return (hash >>> 0).toString(36);
+}
+
+export function mountedBlockKey(language: string, source: string): string {
+ return `${language}:${hashSource(source)}`;
+}
+
+export function hasBlockMounted(key: string): boolean {
+ return mountedBlocks.has(key);
+}
+
+export function markBlockMounted(key: string): void {
+ if (mountedBlocks.has(key)) return;
+ if (mountedBlocks.size >= MAX_TRACKED_BLOCKS) {
+ const oldest = mountedBlocks.values().next();
+ if (!oldest.done) mountedBlocks.delete(oldest.value);
+ }
+ mountedBlocks.add(key);
+}
+
+/** Test-only: the registry outlives individual renders by design. */
+export function resetMountedBlocks(): void {
+ mountedBlocks.clear();
+}
diff --git a/packages/views/rich-content/package-exports.test.ts b/packages/views/rich-content/package-exports.test.ts
new file mode 100644
index 0000000000..6ab36b6892
--- /dev/null
+++ b/packages/views/rich-content/package-exports.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Package export-target guard.
+ *
+ * Every path in a workspace's `exports` map must point at a file that actually
+ * exists. Deleting or moving a module without updating `exports` leaves a
+ * dangling subpath that still *resolves* for TypeScript (which reads the source
+ * tree) but throws at bundle time in whichever app imports it — so it survives
+ * typecheck and unit tests and only shows up in a consuming app's build.
+ *
+ * This regressed once already in MUL-4922: `./common/markdown` was deleted when
+ * Chat moved onto RichContent, but its export entry stayed behind.
+ *
+ * Scoped to the whole monorepo rather than just `views`: the failure mode is a
+ * property of package.json, not of this package.
+ */
+import { describe, expect, it } from "vitest";
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { dirname, join, relative } from "node:path";
+
+const REPO_ROOT = join(__dirname, "..", "..", "..");
+
+function workspacePackageJsons(): string[] {
+ const out: string[] = [];
+ for (const group of ["packages", "apps"]) {
+ const groupDir = join(REPO_ROOT, group);
+ if (!existsSync(groupDir)) continue;
+ for (const entry of readdirSync(groupDir)) {
+ const pkg = join(groupDir, entry, "package.json");
+ if (existsSync(pkg) && statSync(pkg).isFile()) out.push(pkg);
+ }
+ }
+ return out;
+}
+
+/** Every string target in an exports value (string, or a conditions object). */
+function exportTargets(value: unknown): string[] {
+ if (typeof value === "string") return [value];
+ if (value && typeof value === "object") {
+ return Object.values(value as Record<string, unknown>).flatMap(exportTargets);
+ }
+ return [];
+}
+
+interface Dangling {
+ pkg: string;
+ subpath: string;
+ target: string;
+}
+
+function findDanglingExports(): Dangling[] {
+ const dangling: Dangling[] = [];
+
+ for (const pkgPath of workspacePackageJsons()) {
+ const pkgDir = dirname(pkgPath);
+ let parsed: { exports?: unknown };
+ try {
+ parsed = JSON.parse(readFileSync(pkgPath, "utf8"));
+ } catch {
+ continue;
+ }
+ const exports = parsed.exports;
+ if (!exports || typeof exports !== "object") continue;
+
+ for (const [subpath, value] of Object.entries(exports as Record<string, unknown>)) {
+ for (const target of exportTargets(value)) {
+ if (target.includes("*")) {
+ // Wildcard subpath (e.g. "./locales/*"): the concrete file depends on
+ // the importer, so assert the directory prefix exists instead.
+ const prefix = target.slice(0, target.indexOf("*"));
+ if (!existsSync(join(pkgDir, prefix))) {
+ dangling.push({ pkg: relative(REPO_ROOT, pkgPath), subpath, target });
+ }
+ continue;
+ }
+ if (!existsSync(join(pkgDir, target))) {
+ dangling.push({ pkg: relative(REPO_ROOT, pkgPath), subpath, target });
+ }
+ }
+ }
+ }
+
+ return dangling;
+}
+
+describe("workspace package exports", () => {
+ it("every export target points at a file that exists", () => {
+ const dangling = findDanglingExports();
+ // Surfaced as readable strings so a failure names the offending subpath
+ // instead of printing an object diff.
+ expect(dangling.map((d) => `${d.pkg} :: "${d.subpath}" -> ${d.target}`)).toEqual([]);
+ });
+
+ it("the deleted chat markdown bridge is not exported", () => {
+ const views = JSON.parse(
+ readFileSync(join(REPO_ROOT, "packages/views/package.json"), "utf8"),
+ ) as { exports?: Record<string, unknown> };
+
+ expect(Object.keys(views.exports ?? {})).not.toContain("./common/markdown");
+ });
+
+ it("detects a dangling target when one is introduced", () => {
+ // Guards the guard: if the traversal silently stopped finding anything
+ // (wrong root, changed layout), the first test would pass vacuously.
+ const pkgDir = join(REPO_ROOT, "packages/views");
+ expect(existsSync(join(pkgDir, "./editor/index.ts"))).toBe(true);
+ expect(existsSync(join(pkgDir, "./common/markdown.tsx"))).toBe(false);
+ expect(workspacePackageJsons().length).toBeGreaterThan(3);
+ });
+});
diff --git a/packages/views/rich-content/project-mention-a11y.test.tsx b/packages/views/rich-content/project-mention-a11y.test.tsx
new file mode 100644
index 0000000000..b5d251c44a
--- /dev/null
+++ b/packages/views/rich-content/project-mention-a11y.test.tsx
@@ -0,0 +1,145 @@
+/**
+ * Project mention accessibility (MUL-4922).
+ *
+ * A mention is a link. It must be reachable by Tab, activatable by Enter, and
+ * carry a real URL — not a `<span onClick>` that only answers to a mouse.
+ *
+ * This is a regression fixture, not a hypothetical: Chat previously rendered
+ * project mentions through AppLink, the readonly renderer used a click-handling
+ * span, and unifying the two surfaces silently propagated the span to Chat. A
+ * span and an anchor look identical on screen and behave identically under a
+ * mouse, so only an assertion about the emitted element catches this.
+ *
+ * The real AppLink and NavigationProvider are used deliberately — mocking
+ * AppLink to render an `<a>` would assert the mock, not the component.
+ */
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { NavigationProvider } from "../navigation/context";
+import type { NavigationAdapter } from "../navigation/types";
+
+vi.mock("../issues/hooks", () => ({
+ useResolveIssueIdentifier: () => null,
+}));
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string) => select(editor),
+ }),
+ useTimeAgo: () => "just now",
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: vi.fn() },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/acme/issues/${id}`,
+ projectDetail: (id: string) => `/acme/projects/${id}`,
+ }),
+ useWorkspaceSlug: () => "acme",
+}));
+
+vi.mock("../issues/components/issue-mention-card", () => ({
+ IssueMentionCard: ({ issueId }: { issueId: string }) => <span>{issueId}</span>,
+}));
+
+vi.mock("../projects/components/project-chip", () => ({
+ ProjectChip: ({ projectId, fallbackLabel }: { projectId: string; fallbackLabel?: string }) => (
+ <span data-testid="project-chip">{fallbackLabel ?? projectId}</span>
+ ),
+}));
+
+vi.mock("../editor/link-hover-card", () => ({
+ useLinkHover: () => ({}),
+ LinkHoverCard: () => null,
+}));
+
+import { RichContent } from "./rich-content";
+
+const PROJECT_ID = "8f14e45f-ceea-4d0e-a1a2-9b1c0d3e4f5a";
+const MENTION = `Tracked under [Roadmap](mention://project/${PROJECT_ID}).`;
+
+function makeAdapter(overrides: Partial<NavigationAdapter> = {}): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p) => p,
+ ...overrides,
+ };
+}
+
+function renderMention(adapter: NavigationAdapter = makeAdapter()) {
+ return render(
+ <NavigationProvider value={adapter}>
+ <RichContent content={MENTION} />
+ </NavigationProvider>,
+ );
+}
+
+describe("project mention accessibility", () => {
+ it("renders an anchor with the project href", () => {
+ const { container } = renderMention();
+
+ const anchor = container.querySelector(`a[href="/acme/projects/${PROJECT_ID}"]`);
+ expect(anchor).not.toBeNull();
+ expect(anchor?.tagName).toBe("A");
+ expect(screen.getByTestId("project-chip")).toBeInTheDocument();
+ });
+
+ it("does not render the chip as a click-only span", () => {
+ // The exact regression: a chip whose nearest interactive ancestor is a span
+ // is unreachable by keyboard.
+ const chip = renderMention().getByTestId("project-chip");
+ expect(chip.closest("a")).not.toBeNull();
+ });
+
+ it("is keyboard focusable", async () => {
+ const user = userEvent.setup();
+ const { container } = renderMention();
+ const anchor = container.querySelector("a") as HTMLAnchorElement;
+
+ await user.tab();
+
+ expect(document.activeElement).toBe(anchor);
+ });
+
+ it("activates on Enter", async () => {
+ const push = vi.fn();
+ const user = userEvent.setup();
+ renderMention(makeAdapter({ push }));
+
+ await user.tab();
+ await user.keyboard("{Enter}");
+
+ expect(push).toHaveBeenCalledWith(`/acme/projects/${PROJECT_ID}`);
+ });
+
+ it("navigates on click through the adapter", () => {
+ const push = vi.fn();
+ const { container } = renderMention(makeAdapter({ push }));
+
+ fireEvent.click(container.querySelector("a") as HTMLAnchorElement);
+
+ expect(push).toHaveBeenCalledWith(`/acme/projects/${PROJECT_ID}`);
+ });
+
+ it("opens in a new tab on modifier-click, labelled with the mention text", () => {
+ const openInNewTab = vi.fn();
+ const { container } = renderMention(makeAdapter({ openInNewTab }));
+
+ fireEvent.click(container.querySelector("a") as HTMLAnchorElement, { metaKey: true });
+
+ expect(openInNewTab).toHaveBeenCalledWith(`/acme/projects/${PROJECT_ID}`, "Roadmap");
+ });
+});
diff --git a/packages/views/rich-content/rich-code-block.tsx b/packages/views/rich-content/rich-code-block.tsx
new file mode 100644
index 0000000000..b8db1a8010
--- /dev/null
+++ b/packages/views/rich-content/rich-code-block.tsx
@@ -0,0 +1,224 @@
+"use client";
+
+/**
+ * RichCodeBlock — the ONLY fenced-code dispatcher in the product (MUL-4922).
+ *
+ * Every product surface (Chat, Issue description, Comment) reaches fenced code
+ * through this file. Adding a language branch anywhere else — a per-surface
+ * `if (lang === "…")` in a message list or a comment card — is exactly the
+ * drift this sweep deleted, so new languages get added HERE and nowhere else.
+ *
+ * Dispatch is on a whole language token, never a substring: `language-htmlbars`
+ * and `language-mermaidx` are ordinary code, not an HTML preview / diagram.
+ *
+ * Upgrading to a rich block additionally requires the fence to be CLOSED (see
+ * streaming-fence.ts). A half-streamed fence renders as plain source, so
+ * Mermaid never parses a partial diagram and no iframe is created for HTML that
+ * is still arriving.
+ *
+ * Leaf components (MermaidDiagram / HtmlBlockPreview / lowlight static code)
+ * are surface-agnostic and shared with the Tiptap editor's NodeViews. They are
+ * imported by direct path — never through the `editor` barrel — so this module
+ * does not pull the editor's Tiptap graph into Chat.
+ */
+
+import { memo, useEffect, useMemo, useState, type ReactNode } from "react";
+import { toHtml } from "hast-util-to-html";
+import { Check, Copy } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { useT } from "../i18n";
+import {
+ MermaidDiagram,
+ MERMAID_SKELETON_HEIGHT_PX,
+ reservedMermaidHeightPx,
+} from "../editor/mermaid-diagram";
+import {
+ HtmlBlockPreview,
+ HTML_BLOCK_PREVIEW_HEIGHT_PX,
+} from "../editor/html-block-preview";
+import { highlightCode } from "../editor/syntax-highlight";
+import { LazyRichBlock } from "./lazy-rich-block";
+
+/**
+ * Languages that may become a rich block. Anything else — including unknown
+ * and absent languages — renders as static highlighted code.
+ */
+export type RichFenceLanguage = "mermaid" | "html";
+
+export function isRichFenceLanguage(
+ language: string | undefined,
+): language is RichFenceLanguage {
+ return language === "mermaid" || language === "html";
+}
+
+/**
+ * Whether a fenced block should render as a rich block rather than source.
+ * Both conditions are required: a rich-capable language AND a closed fence.
+ */
+export function shouldUpgradeFence(
+ language: string | undefined,
+ isFenceClosed: boolean,
+): boolean {
+ return isRichFenceLanguage(language) && isFenceClosed;
+}
+
+// Memoized on source so appending text elsewhere in a streaming message does
+// not re-run Mermaid's async render or reload an already-mounted iframe. React
+// reconciliation keeps the instance mounted (same element type, same position);
+// memo additionally keeps it from re-rendering.
+const MemoMermaidDiagram = memo(MermaidDiagram);
+const MemoHtmlBlockPreview = memo(HtmlBlockPreview);
+
+/**
+ * Static lowlight-highlighted `<code>`, matching the editable Tiptap code
+ * block's engine and `.hljs-*` CSS so a fence looks identical in every surface.
+ */
+export function StaticCodeBody({
+ language,
+ body,
+ className,
+}: {
+ language: string | undefined;
+ body: string;
+ className?: string;
+}) {
+ const html = useMemo(() => {
+ const code = body.replace(/\n$/, "");
+ try {
+ const tree = highlightCode(code, language);
+ return toHtml(tree);
+ } catch {
+ return null;
+ }
+ }, [body, language]);
+
+ if (html == null) {
+ // Highlighter failure must not blank the code — render it unhighlighted.
+ return (
+ <code className={cn("hljs", className)}>{body.replace(/\n$/, "")}</code>
+ );
+ }
+
+ return (
+ <code
+ className={cn("hljs", language && `language-${language}`, className)}
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ );
+}
+
+/**
+ * `<pre>` shell with hover copy chrome, matching the editable code block's
+ * header (language label + copy) in code-block-view.tsx.
+ */
+export function CodeBlockShell({
+ language,
+ code,
+ children,
+}: {
+ language?: string;
+ code: string;
+ children: ReactNode;
+}) {
+ const { t } = useT("editor");
+ const [copied, setCopied] = useState(false);
+ const copyLabel = t(($) => $.code_block.copy_code) || "Copy code";
+
+ const handleCopy = async () => {
+ if (!code) return;
+ if (await copyText(code)) {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+
+ return (
+ <div className="code-block-wrapper group/code relative my-3">
+ <div className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100">
+ {language && (
+ <span className="text-xs text-muted-foreground select-none">
+ {language}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={handleCopy}
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title={copyLabel}
+ aria-label={copyLabel}
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </div>
+ {/* No extra right padding: `.rich-text-editor pre` outranks utility
+ padding classes anyway, and the editable NodeView uses the same
+ 1rem — keeping them identical keeps line wrapping identical. */}
+ <pre className="!m-0">{children}</pre>
+ </div>
+ );
+}
+
+/**
+ * The rich leaf for an upgraded fence. Only reached when shouldUpgradeFence()
+ * returned true, so the fence is known-closed here.
+ *
+ * Both leaves are expensive to instantiate (async Mermaid render / sandboxed
+ * iframe), so each is wrapped in the near-viewport lazy shell. The reserved
+ * height comes from the leaf itself, so the shell holds the same space the
+ * mounted block will occupy.
+ */
+export function RichFenceBlock({
+ language,
+ body,
+}: {
+ language: RichFenceLanguage;
+ body: string;
+}) {
+ // Split into two components so the Mermaid-only height hook is never called
+ // conditionally.
+ if (language === "mermaid") return <MermaidFenceBlock chart={body} />;
+ return <HtmlFenceBlock html={body} />;
+}
+
+/**
+ * Reserved height for a diagram: the skeleton default on the first frame, then
+ * the session-cached real height once mounted.
+ *
+ * The cache lives in sessionStorage, which the server does not have. Reading it
+ * during render therefore produces 280px on the server and the cached height in
+ * a browser with a warm cache — different `style="min-height:…"` on the very
+ * frame React hydrates, which React reports as an attribute mismatch and does
+ * NOT repair. Deferring the read to an effect keeps the first frame identical
+ * everywhere and still gets the zero-shift benefit immediately after.
+ */
+function useReservedMermaidHeightPx(chart: string): number {
+ const [height, setHeight] = useState(MERMAID_SKELETON_HEIGHT_PX);
+ useEffect(() => {
+ const cached = reservedMermaidHeightPx(chart);
+ setHeight((current) => (current === cached ? current : cached));
+ }, [chart]);
+ return height;
+}
+
+function MermaidFenceBlock({ chart }: { chart: string }) {
+ return (
+ <LazyRichBlock reservedHeightPx={useReservedMermaidHeightPx(chart)} sourceKey={chart}>
+ <MemoMermaidDiagram chart={chart} />
+ </LazyRichBlock>
+ );
+}
+
+function HtmlFenceBlock({ html }: { html: string }) {
+ // The preview iframe is a fixed height, so this needs no cache and is already
+ // identical on server and client.
+ return (
+ <LazyRichBlock reservedHeightPx={HTML_BLOCK_PREVIEW_HEIGHT_PX} sourceKey={html}>
+ <MemoHtmlBlockPreview html={html} />
+ </LazyRichBlock>
+ );
+}
diff --git a/packages/views/rich-content/rich-content-boundary.test.ts b/packages/views/rich-content/rich-content-boundary.test.ts
new file mode 100644
index 0000000000..4034023c61
--- /dev/null
+++ b/packages/views/rich-content/rich-content-boundary.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Import boundary guard (MUL-4922, Howard's contract #3).
+ *
+ * The point of this sweep is that there is exactly ONE product-level readonly
+ * renderer. That property is not self-enforcing: the cheapest way to add a
+ * feature to Chat will always look like "render this bit with the generic
+ * Markdown component" or "pass a custom code renderer here", and each of those
+ * quietly recreates the second chain we just deleted.
+ *
+ * These tests read the actual source tree, so they fail on the commit that
+ * introduces the fork rather than months later when the surfaces have visibly
+ * diverged again.
+ */
+import { describe, expect, it } from "vitest";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+
+const VIEWS_ROOT = join(__dirname, "..");
+
+// Product surfaces that render user/agent-authored content. Any of these
+// reaching for a generic Markdown renderer is the regression.
+const PRODUCT_SURFACES = ["chat", "issues", "skills", "autopilots", "inbox"];
+
+function walk(dir: string, out: string[] = []): string[] {
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return out;
+ }
+ for (const entry of entries) {
+ if (entry === "node_modules" || entry.startsWith(".")) continue;
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) walk(full, out);
+ else if (/\.tsx?$/.test(full) && !/\.test\.tsx?$/.test(full)) out.push(full);
+ }
+ return out;
+}
+
+/**
+ * Drop comments before matching. These guards look for real imports and real
+ * language branches; prose that merely *mentions* one (a doc comment
+ * explaining which renderer mounts a leaf) is not a violation, and treating it
+ * as one would train the next person to delete the guard.
+ */
+function stripComments(text: string): string {
+ return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
+}
+
+function sourceFiles(subdirs: string[]): { path: string; text: string }[] {
+ return subdirs
+ .flatMap((d) => walk(join(VIEWS_ROOT, d)))
+ .map((path) => ({
+ path: relative(VIEWS_ROOT, path),
+ text: stripComments(readFileSync(path, "utf8")),
+ }));
+}
+
+describe("RichContent import boundary", () => {
+ it("no product surface imports the generic ui Markdown renderer", () => {
+ const offenders = sourceFiles(PRODUCT_SURFACES)
+ .filter(({ text }) =>
+ /from\s+["']@multica\/ui\/markdown["']/.test(text) &&
+ /\bMarkdown\b|\bMemoizedMarkdown\b|\bStreamingMarkdown\b/.test(text),
+ )
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("the deleted chat markdown bridge has not come back", () => {
+ const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
+ .filter(({ text }) => /common\/markdown/.test(text))
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("no product surface builds its own react-markdown pipeline", () => {
+ // react-markdown may be imported only by the canonical renderer. A second
+ // import means a second pipeline with its own sanitize + components map.
+ const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
+ .filter(({ text }) => /from\s+["']react-markdown["']/.test(text))
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("only the canonical renderer configures the sanitize schema", () => {
+ const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
+ .filter(({ text }) => /rehype-sanitize|markdownSanitizeSchema/.test(text))
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("only rich-code-block dispatches on a fence language", () => {
+ // A `lang === "mermaid"` / `"html"` comparison outside the dispatcher is a
+ // per-surface language branch — architecture constraint 2.
+ //
+ // The Tiptap NodeView is the one sanctioned exception (constraint 6): the
+ // EDITABLE code block owns its own preview-toggle lifecycle while the user
+ // types, and reuses the same leaf components rather than the readonly
+ // renderer. Rewriting the editor is explicitly out of scope for MUL-4922.
+ // Narrow, named, and justified — not a general loophole.
+ const TIPTAP_NODEVIEW = "editor/extensions/code-block-view.tsx";
+
+ const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
+ .filter(({ path }) => path !== TIPTAP_NODEVIEW)
+ .filter(({ text }) =>
+ /(?:lang|language)\w*\s*===\s*["'](?:mermaid|html)["']/.test(text),
+ )
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("Tiptap reuses the leaf components but never imports RichContent", () => {
+ // Constraint 6: the editor keeps its own parser/lifecycle. Pulling the
+ // readonly renderer into the editor is the classic way this collapses.
+ const offenders = walk(join(VIEWS_ROOT, "editor"))
+ .filter((p) => !/readonly-content\.tsx$/.test(p))
+ .map((path) => ({
+ path: relative(VIEWS_ROOT, path),
+ // stripComments, consistently with the other checks: an editor file may
+ // *mention* RichContent in a doc comment (explaining why a helper is
+ // shaped the way it is). Only real code references are violations.
+ text: stripComments(readFileSync(path, "utf8")),
+ }))
+ .filter(({ text }) => /\bRichContent\b/.test(text))
+ .map(({ path }) => path);
+
+ expect(offenders).toEqual([]);
+ });
+
+ it("the canonical renderer stays in views, not ui", () => {
+ // Mention/Attachment/navigation are product concerns; moving this into
+ // packages/ui would break the ui -> no-core/views boundary.
+ const uiRoot = join(VIEWS_ROOT, "..", "ui");
+ const offenders = walk(uiRoot)
+ .map((path) => ({ path, text: stripComments(readFileSync(path, "utf8")) }))
+ .filter(({ text }) => /\bRichContent\b|from\s+["']@multica\/views/.test(text))
+ .map(({ path }) => relative(uiRoot, path));
+
+ expect(offenders).toEqual([]);
+ });
+});
+
+describe("chat renders every text entry through RichContent", () => {
+ const chatList = readFileSync(
+ join(VIEWS_ROOT, "chat/components/chat-message-list.tsx"),
+ "utf8",
+ );
+
+ it("uses RichContent and no other markdown renderer", () => {
+ expect(chatList).toMatch(/\bRichContent\b/);
+ expect(chatList).not.toMatch(/MemoizedMarkdown|<Markdown\b/);
+ });
+
+ it("keys the live row and the persisted assistant row on the task", () => {
+ // The identity contract in source form: if someone reverts to `msg.id`,
+ // the parity test's remount assertion and this both fail.
+ expect(chatList).toMatch(/task:\$\{/);
+ expect(chatList).not.toMatch(/computeItemKey=\{\(_, msg\) => msg\.id\}/);
+ });
+});
diff --git a/packages/views/rich-content/rich-content-parity.test.tsx b/packages/views/rich-content/rich-content-parity.test.tsx
new file mode 100644
index 0000000000..deef87cfe5
--- /dev/null
+++ b/packages/views/rich-content/rich-content-parity.test.tsx
@@ -0,0 +1,500 @@
+/**
+ * Five-surface RichContent parity (MUL-4922).
+ *
+ * The acceptance naiyuan set: ONE completed Markdown fixture must produce the
+ * SAME semantic blocks in Chat (user message, live assistant, persisted
+ * assistant), an Issue description and a Comment. Density/CSS may differ;
+ * capability may not. A Mermaid fence must be a diagram in all five, not a code
+ * block in some of them.
+ *
+ * The surfaces are exercised through their real entry points — ReadonlyContent
+ * for Issue/Comment and ChatMessageList for the three Chat rows — so a
+ * regression that reintroduces a Chat-only renderer fails here.
+ */
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { render, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactElement } from "react";
+
+const { resolveIssueIdentifierMock, mermaidRenderMock } = vi.hoisted(() => ({
+ resolveIssueIdentifierMock: vi.fn(),
+ mermaidRenderMock: vi.fn(),
+}));
+
+vi.mock("../issues/hooks", () => ({
+ useResolveIssueIdentifier: (identifier: string) =>
+ resolveIssueIdentifierMock(identifier),
+}));
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ const chat = (await import("../locales/en/chat.json")).default;
+ return {
+ useT: (ns?: string) => ({
+ t: (select: (bundle: Record<string, unknown>) => string) =>
+ select((ns === "chat" ? chat : editor) as Record<string, unknown>),
+ }),
+ useTimeAgo: () => "just now",
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: vi.fn() },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/test/issues/${id}`,
+ projectDetail: (id: string) => `/test/projects/${id}`,
+ }),
+ useWorkspaceSlug: () => "test",
+}));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+vi.mock("../issues/components/issue-mention-card", () => ({
+ IssueMentionCard: ({ issueId, fallbackLabel }: { issueId: string; fallbackLabel?: string }) => (
+ <span data-testid="issue-mention">{fallbackLabel ?? issueId}</span>
+ ),
+}));
+
+vi.mock("../projects/components/project-chip", () => ({
+ ProjectChip: ({ projectId }: { projectId: string }) => (
+ <span data-testid="project-chip">{projectId}</span>
+ ),
+}));
+
+vi.mock("../editor/link-hover-card", () => ({
+ useLinkHover: () => ({}),
+ LinkHoverCard: () => null,
+}));
+
+vi.mock("mermaid", () => ({
+ default: {
+ initialize: vi.fn(),
+ render: mermaidRenderMock,
+ },
+}));
+
+// react-virtuoso does not virtualize under jsdom's zero-height viewport, so
+// render every row directly. computeItemKey is still exercised: it is what
+// gives the live row and the persisted row one identity.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({
+ data,
+ itemContent,
+ computeItemKey,
+ components,
+ context,
+ }: {
+ data: unknown[];
+ itemContent: (i: number, item: unknown) => ReactElement;
+ computeItemKey: (i: number, item: unknown) => string;
+ components?: { Footer?: (p: { context?: unknown }) => ReactElement | null };
+ context?: unknown;
+ }) => {
+ const Footer = components?.Footer;
+ return (
+ <div>
+ {data.map((item, i) => (
+ <div key={computeItemKey(i, item)} data-row-key={computeItemKey(i, item)}>
+ {itemContent(i, item)}
+ </div>
+ ))}
+ {Footer ? <Footer context={context} /> : null}
+ </div>
+ );
+ },
+}));
+
+Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
+ value: () => ({
+ fillStyle: "#000",
+ fillRect: vi.fn(),
+ getImageData: () => ({ data: new Uint8ClampedArray([12, 34, 56, 255]) }),
+ }),
+});
+
+import { ReadonlyContent } from "../editor/readonly-content";
+import { ChatMessageList } from "../chat/components/chat-message-list";
+import { taskMessagesOptions } from "@multica/core/chat/queries";
+
+// naiyuan's fixture, corrected to a single closed fence.
+const MERMAID_FIXTURE = [
+ "```mermaid",
+ "flowchart LR",
+ ' HTML["HTML"] --> WEB["网页"]',
+ ' CSS["CSS"] --> WEB',
+ "```",
+].join("\n");
+
+const TASK_ID = "11111111-1111-4111-8111-111111111111";
+
+function makeClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+}
+
+function withClient(ui: ReactElement, client: QueryClient) {
+ return <QueryClientProvider client={client}>{ui}</QueryClientProvider>;
+}
+
+/** A persisted assistant chat_message carrying `content`. */
+function assistantMessage(content: string) {
+ return {
+ id: "msg-assistant-1",
+ role: "assistant" as const,
+ content,
+ task_id: TASK_ID,
+ attachments: [],
+ elapsed_ms: 1200,
+ };
+}
+
+function userMessage(content: string) {
+ return {
+ id: "msg-user-1",
+ role: "user" as const,
+ content,
+ task_id: null,
+ attachments: [],
+ };
+}
+
+/** Seed the task-messages cache the way useRealtimeSync does during a run. */
+function seedTimeline(client: QueryClient, text: string) {
+ client.setQueryData(taskMessagesOptions(TASK_ID).queryKey, [
+ {
+ task_id: TASK_ID,
+ issue_id: null,
+ seq: 1,
+ type: "text",
+ content: text,
+ },
+ ] as never);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mermaidRenderMock.mockResolvedValue({
+ svg: '<svg viewBox="0 0 123 45"><g><text>diagram</text></g></svg>',
+ });
+ resolveIssueIdentifierMock.mockReturnValue(null);
+});
+
+/**
+ * The Mermaid leaf's own container — NOT a bare `svg` query, which also matches
+ * the lucide icons in code-block chrome.
+ */
+const mermaidLeaf = (container: HTMLElement): Element | null =>
+ container.querySelector(".mermaid-diagram");
+
+/** Every surface must expose the diagram through the same Mermaid leaf. */
+async function expectMermaidRendered(container: HTMLElement) {
+ await waitFor(() => {
+ expect(mermaidLeaf(container)).not.toBeNull();
+ });
+ await waitFor(() => {
+ expect(mermaidLeaf(container)?.querySelector("svg")).not.toBeNull();
+ });
+ // Not a plain code block: the fence was upgraded.
+ expect(container.querySelector("code.hljs")).toBeNull();
+}
+
+describe("Mermaid parity across the five surfaces", () => {
+ it("renders a diagram in an Issue description", async () => {
+ const { container } = render(<ReadonlyContent content={MERMAID_FIXTURE} />);
+ await expectMermaidRendered(container);
+ });
+
+ it("renders a diagram in a Comment", async () => {
+ // Comment and Issue description share ReadonlyContent; asserting both keeps
+ // the acceptance list honest about what was actually exercised.
+ const { container } = render(
+ <ReadonlyContent content={MERMAID_FIXTURE} attachments={[]} />,
+ );
+ await expectMermaidRendered(container);
+ });
+
+ it("renders a diagram in a Chat user message", async () => {
+ const client = makeClient();
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[userMessage(MERMAID_FIXTURE)] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ await expectMermaidRendered(container);
+ });
+
+ it("renders a diagram in a persisted Chat assistant message", async () => {
+ const client = makeClient();
+ seedTimeline(client, MERMAID_FIXTURE);
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[assistantMessage(MERMAID_FIXTURE)] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ await expectMermaidRendered(container);
+ });
+
+ it("renders a diagram in a live (streaming) Chat assistant row", async () => {
+ const client = makeClient();
+ seedTimeline(client, MERMAID_FIXTURE);
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" } as never}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ await expectMermaidRendered(container);
+ });
+});
+
+describe("streaming fence gate in Chat", () => {
+ it("does not instantiate Mermaid while the fence is still open", async () => {
+ const client = makeClient();
+ // Same content, closing fence not yet streamed.
+ seedTimeline(client, "```mermaid\nflowchart LR\n A --> B\n");
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" } as never}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+
+ // Source is shown as ordinary code; Mermaid is never called.
+ await waitFor(() => {
+ expect(container.querySelector("code")).not.toBeNull();
+ });
+ expect(mermaidRenderMock).not.toHaveBeenCalled();
+ expect(mermaidLeaf(container)).toBeNull();
+ });
+
+ it("upgrades in place once the closing fence arrives", async () => {
+ const client = makeClient();
+ seedTimeline(client, "```mermaid\nflowchart LR\n A --> B\n");
+ const { container, rerender } = render(
+ withClient(
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" } as never}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ expect(mermaidRenderMock).not.toHaveBeenCalled();
+
+ // Closing fence streams in.
+ seedTimeline(client, "```mermaid\nflowchart LR\n A --> B\n```");
+ rerender(
+ withClient(
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" } as never}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+
+ await waitFor(() => {
+ expect(mermaidLeaf(container)).not.toBeNull();
+ });
+ });
+
+ it("keeps a settled-but-unclosed fence as source", async () => {
+ // Task finished, fence still malformed: completion must not bypass the gate.
+ const client = makeClient();
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[assistantMessage("```mermaid\nflowchart LR\n A --> B\n")] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ await waitFor(() => {
+ expect(container.querySelector("code")).not.toBeNull();
+ });
+ expect(mermaidRenderMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("live → persisted row identity", () => {
+ // Howard's contract #1: the handoff must be an in-place data swap, not a
+ // remount, or every completed task rebuilds its diagrams and the scroll
+ // position jumps.
+ it("keeps one row key across the handoff and does not re-run Mermaid", async () => {
+ const client = makeClient();
+ seedTimeline(client, MERMAID_FIXTURE);
+
+ const live = (
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" } as never}
+ availability={undefined}
+ />
+ );
+ const { container, rerender } = render(withClient(live, client));
+
+ await waitFor(() => expect(mermaidLeaf(container)).not.toBeNull());
+ const liveKey = container.querySelector("[data-row-key]")?.getAttribute("data-row-key");
+ const rendersWhileLive = mermaidRenderMock.mock.calls.length;
+ expect(liveKey).toBe(`task:${TASK_ID}`);
+
+ // The assistant message persists; the pending task clears.
+ rerender(
+ withClient(
+ <ChatMessageList
+ messages={[assistantMessage(MERMAID_FIXTURE)] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText(/Replied in/i)).toBeInTheDocument();
+ });
+
+ // Same key => React reconciled the row instead of remounting it.
+ const persistedKey = container
+ .querySelector("[data-row-key]")
+ ?.getAttribute("data-row-key");
+ expect(persistedKey).toBe(liveKey);
+
+ // And the diagram was not re-rendered by the handoff.
+ expect(mermaidRenderMock.mock.calls.length).toBe(rendersWhileLive);
+ expect(mermaidLeaf(container)).not.toBeNull();
+ });
+
+ it("gives a persisted assistant message a task-scoped row key", () => {
+ const client = makeClient();
+ const { container } = render(
+ withClient(
+ <ChatMessageList
+ messages={[assistantMessage("hi")] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ );
+ expect(container.querySelector("[data-row-key]")?.getAttribute("data-row-key")).toBe(
+ `task:${TASK_ID}`,
+ );
+ });
+});
+
+describe("semantic parity beyond Mermaid", () => {
+ const FIXTURE = [
+ "A [link](https://example.com) and a mention [MUL-7](mention://issue/MUL-7).",
+ "",
+ "```html",
+ "<b>preview</b>",
+ "```",
+ "",
+ "```ts",
+ "const a = 1;",
+ "```",
+ "",
+ "<mark>highlighted</mark>",
+ ].join("\n");
+
+ function renderReadonly() {
+ return render(<ReadonlyContent content={FIXTURE} />).container;
+ }
+
+ function renderChatUser() {
+ const client = makeClient();
+ return render(
+ withClient(
+ <ChatMessageList
+ messages={[userMessage(FIXTURE)] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ ).container;
+ }
+
+ it("produces the same block set in Issue/Comment and Chat", async () => {
+ resolveIssueIdentifierMock.mockImplementation((id: string) =>
+ id === "MUL-7" ? { id: "issue-7", identifier: "MUL-7" } : null,
+ );
+
+ const readonly = renderReadonly();
+ const chat = renderChatUser();
+
+ for (const container of [readonly, chat]) {
+ // HTML fence -> sandboxed preview iframe (not a code block)
+ await waitFor(() => {
+ expect(container.querySelector("iframe")).not.toBeNull();
+ });
+ expect(container.querySelector("iframe")?.getAttribute("sandbox")).toBe(
+ "allow-scripts",
+ );
+ // Ordinary language -> lowlight static code
+ expect(container.querySelector("code.hljs")).not.toBeNull();
+ // Mention chip
+ expect(within(container).getByTestId("issue-mention")).toBeInTheDocument();
+ // Highlight
+ expect(container.querySelector("mark")?.textContent).toBe("highlighted");
+ // Plain link
+ expect(container.querySelector('a[href="https://example.com"]')).not.toBeNull();
+ }
+ });
+
+ it("does not dispatch htmlbars / mermaidx to rich blocks on either surface", async () => {
+ const near = "```htmlbars\n<b>x</b>\n```\n\n```mermaidx\ngraph TD\n```";
+ const readonly = render(<ReadonlyContent content={near} />).container;
+ const client = makeClient();
+ const chat = render(
+ withClient(
+ <ChatMessageList
+ messages={[userMessage(near)] as never}
+ pendingTask={null}
+ availability={undefined}
+ />,
+ client,
+ ),
+ ).container;
+
+ for (const container of [readonly, chat]) {
+ expect(container.querySelector("iframe")).toBeNull();
+ expect(container.querySelectorAll("code.hljs").length).toBe(2);
+ }
+ expect(mermaidRenderMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/rich-content/rich-content.css b/packages/views/rich-content/rich-content.css
new file mode 100644
index 0000000000..bd7f9ac3ad
--- /dev/null
+++ b/packages/views/rich-content/rich-content.css
@@ -0,0 +1,37 @@
+/*
+ * RichContent density modifier.
+ *
+ * `density` is CSS-only (MUL-4922): compact and document render the SAME
+ * semantic DOM through the same components map, and differ only in spacing.
+ * Nothing here may change which blocks exist — only how tightly they sit.
+ *
+ * Compact is used by Chat, where a message bubble should not carry the
+ * leading/trailing block margins a document body wants, and consecutive
+ * paragraphs sit closer together.
+ */
+
+.rich-text-editor.rich-content-compact > :first-child {
+ margin-top: 0;
+}
+
+.rich-text-editor.rich-content-compact > :last-child {
+ margin-bottom: 0;
+}
+
+.rich-content-compact p {
+ margin-top: 0.375rem;
+ margin-bottom: 0.375rem;
+}
+
+.rich-content-compact ul,
+.rich-content-compact ol {
+ margin-top: 0.375rem;
+ margin-bottom: 0.375rem;
+}
+
+/* Code blocks and rich blocks keep a little more air than prose so a diagram
+ or preview does not collide with the surrounding text. */
+.rich-content-compact .code-block-wrapper {
+ margin-top: 0.5rem;
+ margin-bottom: 0.5rem;
+}
diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsx
new file mode 100644
index 0000000000..f7c60af6e9
--- /dev/null
+++ b/packages/views/rich-content/rich-content.tsx
@@ -0,0 +1,486 @@
+"use client";
+
+/**
+ * RichContent — the ONE product-level readonly content renderer (MUL-4922).
+ *
+ * Chat (user message, live assistant, persisted assistant, timeline text),
+ * Issue descriptions and Comments all render through this component. There is
+ * no second product Markdown renderer: `packages/ui/markdown` stays a generic
+ * primitive for terminal/raw output and must not grow product concerns
+ * (Mention, Attachment, Mermaid, HTML preview) again.
+ *
+ * Surfaces differ only in the shell they wrap around this component:
+ * - Comment / Issue: edit, reply, menu, thread chrome — outside.
+ * - Chat: timeline, thinking, tool, failure, copy chrome — outside.
+ *
+ * The public API is deliberately narrow. There is no `surface` prop, no
+ * `renderMention` override and no custom code-renderer escape hatch: each of
+ * those is a door through which a per-surface fork walks back in. Link,
+ * mention and attachment behaviour is decided here, once.
+ *
+ * density — CSS only. Never switches parser, plugins, components map or the
+ * semantic DOM; `compact` and `document` produce the same blocks.
+ * phase — lifecycle only. Does NOT decide whether a fence upgrades; that is
+ * the fence's real closed state (see streaming-fence.ts), so a
+ * settled-but-malformed fence still renders as source.
+ */
+
+import { createContext, isValidElement, memo, useContext, useMemo, useRef } from "react";
+import ReactMarkdown, {
+ type Components,
+ type ExtraProps,
+ type Options as ReactMarkdownOptions,
+} from "react-markdown";
+import type { ComponentPropsWithoutRef, ReactNode } from "react";
+import rehypeKatex from "rehype-katex";
+import remarkBreaks from "remark-breaks";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeRaw from "rehype-raw";
+import rehypeSanitize from "rehype-sanitize";
+import { cn } from "@multica/ui/lib/utils";
+import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";
+import { useConfigStore } from "@multica/core/config";
+import type { Attachment } from "@multica/core/types";
+import {
+ isAllowedFileCardHref,
+ isIssueIdentifier,
+ markdownSanitizeSchema,
+ markdownUrlTransform,
+} from "@multica/ui/markdown";
+import { AppLink } from "../navigation";
+import { IssueMentionCard } from "../issues/components/issue-mention-card";
+import { useResolveIssueIdentifier } from "../issues/hooks";
+import { ProjectChip } from "../projects/components/project-chip";
+import { useLinkHover, LinkHoverCard } from "../editor/link-hover-card";
+import { openLink, isMentionHref } from "../editor/utils/link-handler";
+import { preprocessMarkdown } from "../editor/utils/preprocess";
+import { highlightToHtml } from "../editor/utils/highlight-markdown";
+import { AttachmentDownloadProvider } from "../editor/attachment-download-context";
+import { Attachment as AttachmentRenderer } from "../editor/attachment";
+import { computeClosedFenceOffsets } from "./streaming-fence";
+import {
+ CodeBlockShell,
+ RichFenceBlock,
+ StaticCodeBody,
+ isRichFenceLanguage,
+ shouldUpgradeFence,
+} from "./rich-code-block";
+import "katex/dist/katex.min.css";
+import "../editor/styles/index.css";
+import "./rich-content.css";
+
+export type RichContentDensity = "compact" | "document";
+export type RichContentPhase = "streaming" | "settled";
+
+// ---------------------------------------------------------------------------
+// Fence gate context
+// ---------------------------------------------------------------------------
+//
+// The closed-fence offsets travel by context rather than by rebuilding the
+// components map. The map must stay referentially stable: react-markdown
+// re-runs the whole subtree when `components` changes identity, which rewrites
+// every highlighted <code>'s innerHTML and collapses an active text selection
+// inside a code block (MUL-3621).
+
+const ClosedFenceContext = createContext<ReadonlySet<number>>(new Set<number>());
+
+function useIsFenceClosed(offset: number | undefined): boolean {
+ const closed = useContext(ClosedFenceContext);
+ // An offset-less node cannot be matched to a source fence; refusing to
+ // upgrade is the safe direction (source instead of a possibly partial block).
+ return offset != null && closed.has(offset);
+}
+
+// ---------------------------------------------------------------------------
+// Mention / link renderers
+// ---------------------------------------------------------------------------
+
+/**
+ * Issue mention chip. Navigation — plain click, modifier click, and the
+ * "open issue links in new tab" preference — is owned by the AppLink inside
+ * IssueMentionCard; the wrapper only shields surrounding click handlers
+ * (e.g. collapsed-comment expanders) from mention clicks.
+ */
+function IssueMentionLink({ issueId, label }: { issueId: string; label?: string }) {
+ return (
+ <span className="inline align-middle" onClick={(e) => e.stopPropagation()}>
+ <IssueMentionCard issueId={issueId} fallbackLabel={label} />
+ </span>
+ );
+}
+
+/**
+ * Autolinked bare identifier (e.g. `MUL-123`) routed through
+ * `mention://issue/<identifier>` by the preprocessor. Resolves to a real issue
+ * in the current workspace; renders a navigable mention on a hit, plain text on
+ * a miss / while loading / cross-workspace.
+ */
+function AutolinkedIssueMentionLink({ identifier }: { identifier: string }) {
+ const issue = useResolveIssueIdentifier(identifier);
+ if (!issue) return <>{identifier}</>;
+ return <IssueMentionLink issueId={issue.id} label={identifier} />;
+}
+
+/**
+ * Project mention chip.
+ *
+ * Rendered as a real anchor via AppLink, matching IssueMentionCard: a mention is
+ * a link, so it must be reachable by Tab and activatable by Enter, and expose a
+ * URL to copy / open in a new tab. A `<span onClick>` looks identical and works
+ * for a mouse, which is exactly why the regression is easy to miss — the readonly
+ * renderer used one, and unifying the surfaces would have propagated it to Chat,
+ * which previously had the accessible version.
+ *
+ * AppLink also owns plain-click, modifier-click and the desktop new-tab adapter,
+ * so none of that is reimplemented here. The wrapper only shields surrounding
+ * click handlers (e.g. collapsed-comment expanders) from mention clicks.
+ */
+function ProjectMentionLink({ projectId, label }: { projectId: string; label?: string }) {
+ const p = useWorkspacePaths();
+ return (
+ <span className="inline align-middle" onClick={(e) => e.stopPropagation()}>
+ <AppLink
+ href={p.projectDetail(projectId)}
+ newTabTitle={label}
+ className="project-mention not-prose inline-flex"
+ >
+ <ProjectChip
+ projectId={projectId}
+ fallbackLabel={label}
+ className="cursor-pointer hover:bg-accent transition-colors"
+ />
+ </AppLink>
+ </span>
+ );
+}
+
+function childrenToLabel(children: ReactNode): string | undefined {
+ if (typeof children === "string") return children;
+ if (Array.isArray(children)) return children.join("");
+ return undefined;
+}
+
+function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
+ const slug = useWorkspaceSlug();
+
+ if (href?.startsWith("slash://skill/")) {
+ return <span className="slash-command">{children}</span>;
+ }
+
+ if (isMentionHref(href)) {
+ const match = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/);
+ if (match?.[1] === "issue" && match[2]) {
+ // A bare identifier (from the autolink preprocessor) is carried as the id
+ // segment; a real mention carries a UUID. Dispatch on the id shape.
+ if (isIssueIdentifier(match[2])) {
+ return <AutolinkedIssueMentionLink identifier={match[2]} />;
+ }
+ return <IssueMentionLink issueId={match[2]} label={childrenToLabel(children)} />;
+ }
+ if (match?.[1] === "project" && match[2]) {
+ return <ProjectMentionLink projectId={match[2]} label={childrenToLabel(children)} />;
+ }
+ // Member / agent / all mentions
+ return <span className="mention">{children}</span>;
+ }
+
+ // Regular links — open directly on click
+ return (
+ <a
+ href={href}
+ onClick={(e) => {
+ e.preventDefault();
+ if (href) openLink(href, slug);
+ }}
+ >
+ {children}
+ </a>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Fenced code
+// ---------------------------------------------------------------------------
+
+function getTextContent(node: ReactNode): string {
+ if (node == null || typeof node === "boolean") return "";
+ if (typeof node === "string" || typeof node === "number") return String(node);
+ if (Array.isArray(node)) return node.map(getTextContent).join("");
+ if (isValidElement<{ children?: ReactNode }>(node)) {
+ return getTextContent(node.props.children);
+ }
+ return "";
+}
+
+// Props react-markdown actually passes to a component override: the intrinsic
+// element's own props plus the source hast node (`ExtraProps`). Deriving them
+// keeps the renderers checked against react-markdown's real contract instead of
+// a hand-written approximation that a cast would have to silence.
+type RichCodeProps = ComponentPropsWithoutRef<"code"> & ExtraProps;
+type RichPreProps = ComponentPropsWithoutRef<"pre"> & ExtraProps;
+
+/**
+ * Source offset of a hast node, narrowed in one place. Offsets are how a
+ * rendered block is matched back to its fence in the processed Markdown (see
+ * streaming-fence.ts); a node without position cannot be matched.
+ */
+function nodeStartOffset(node: ExtraProps["node"]): number | undefined {
+ return node?.position?.start.offset;
+}
+
+/**
+ * Reads a hast element property as a string. hast property values are a union
+ * (string | number | boolean | array | null), so this narrows at runtime rather
+ * than asserting — a `data-*` attribute that is not a string yields "" instead
+ * of a value that lies about its type.
+ */
+function stringProperty(node: ExtraProps["node"], key: string): string {
+ const value = node?.properties?.[key];
+ return typeof value === "string" ? value : "";
+}
+
+function isMultiLineNode(node: ExtraProps["node"]): boolean {
+ const position = node?.position;
+ return position != null && position.start.line !== position.end.line;
+}
+
+/**
+ * `code` renderer. Returns the rich leaf directly for an upgraded fence and
+ * relies on the `pre` renderer below to unwrap it — react-markdown otherwise
+ * wraps `code` children in a `<pre>` whose monospace/overflow styles clamp a
+ * diagram or preview iframe.
+ */
+function RichCode({ className, children, node, ...props }: RichCodeProps) {
+ const language = /language-(\w+)/.exec(className || "")?.[1];
+ const isBlock = isMultiLineNode(node);
+ const isFenceClosed = useIsFenceClosed(nodeStartOffset(node));
+
+ if (isBlock && shouldUpgradeFence(language, isFenceClosed)) {
+ // isRichFenceLanguage is re-checked for the type narrow; shouldUpgradeFence
+ // already required it.
+ if (isRichFenceLanguage(language)) {
+ return <RichFenceBlock language={language} body={String(children).replace(/\n$/, "")} />;
+ }
+ }
+
+ if (!isBlock && !language) {
+ // Inline code — CSS handles styling via .rich-text-editor code
+ return <code {...props}>{children}</code>;
+ }
+
+ return <StaticCodeBody language={language} body={String(children)} />;
+}
+
+/**
+ * Reads the language token and source offset from the `<code>` element that
+ * react-markdown hands to a `pre` override. `isValidElement`'s type parameter
+ * narrows the child's props, so no cast is needed to reach `node`.
+ */
+function readFencedCodeChild(children: ReactNode): {
+ language?: string;
+ offset?: number;
+} {
+ const child = Array.isArray(children) ? children[0] : children;
+ if (!isValidElement<{ className?: string } & ExtraProps>(child)) return {};
+ return {
+ // Whole class token only: `language-htmlbars` must not read as `html`.
+ language: /(?:^|\s)language-(\w+)(?:\s|$)/.exec(child.props.className ?? "")?.[1],
+ offset: nodeStartOffset(child.props.node),
+ };
+}
+
+/**
+ * `pre` renderer. react-markdown calls this BEFORE invoking the `code`
+ * renderer, so `children` is the unrendered `<code>` element from the AST: the
+ * decision to unwrap is made from that child's own hast node (class token +
+ * source offset), not by checking `children.type === MermaidDiagram`, which
+ * never matches.
+ */
+function RichPre({ children }: RichPreProps) {
+ const { language, offset } = readFencedCodeChild(children);
+ const isFenceClosed = useIsFenceClosed(offset);
+
+ // Upgraded fences escape the <pre><code> envelope entirely. An OPEN
+ // mermaid/html fence deliberately falls through to the normal code shell, so
+ // a half-streamed diagram reads as ordinary source with copy chrome.
+ if (shouldUpgradeFence(language, isFenceClosed)) {
+ return <>{children}</>;
+ }
+
+ return (
+ <CodeBlockShell
+ language={language}
+ code={getTextContent(children).replace(/\n$/, "")}
+ >
+ {children}
+ </CodeBlockShell>
+ );
+}
+
+// The components map is module-level and static: it never depends on density,
+// phase or the fence gate, so its identity is stable for the lifetime of the
+// app and react-markdown can bail out of unchanged subtrees.
+const COMPONENTS: Partial<Components> = {
+ a: RichLink,
+
+ // Images — unified through <Attachment>. The resolver context provided by
+ // AttachmentDownloadProvider turns a CDN URL into a full record when
+ // possible; external URLs render as plain images with lightbox-via-preview
+ // -modal. forceKind is mandatory: markdown `![]()` carries no content-type
+ // and alt is commonly empty, so without it images fall through to file-card
+ // chrome.
+ img: ({ src, alt }) => (
+ <AttachmentRenderer
+ attachment={{
+ kind: "url",
+ url: typeof src === "string" ? src : "",
+ filename: alt ?? "",
+ forceKind: "image",
+ }}
+ />
+ ),
+
+ // FileCard — intercept <div data-type="fileCard"> from preprocessMarkdown
+ div: ({ node, children, ...props }) => {
+ if (stringProperty(node, "dataType") === "fileCard") {
+ const rawHref = stringProperty(node, "dataHref");
+ const href = isAllowedFileCardHref(rawHref) ? rawHref : "";
+ return (
+ <AttachmentRenderer
+ attachment={{
+ kind: "url",
+ url: href,
+ filename: stringProperty(node, "dataFilename"),
+ }}
+ />
+ );
+ }
+ return <div {...props}>{children}</div>;
+ },
+
+ // Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)
+ table: ({ children }) => (
+ <div className="tableWrapper">
+ <table>{children}</table>
+ </div>
+ ),
+
+ code: RichCode,
+ pre: RichPre,
+};
+
+// `satisfies` rather than a cast: the plugin lists are still checked against
+// react-markdown's own option types, so a bad plugin tuple fails here instead of
+// being silenced.
+const REMARK_PLUGINS = [
+ [remarkMath, { singleDollarTextMath: false }],
+ remarkBreaks,
+ [remarkGfm, { singleTilde: false }],
+] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
+
+const REHYPE_PLUGINS = [
+ rehypeRaw,
+ [rehypeSanitize, markdownSanitizeSchema],
+ rehypeKatex,
+] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+export interface RichContentProps {
+ content: string;
+ /**
+ * Attachments associated with the surrounding entity (comment / issue body /
+ * chat message). Inline `<img>` and file-card URLs matching one of these get
+ * their download URL re-signed at click time instead of using the possibly
+ * stale link embedded in the markdown.
+ *
+ * Callers SHOULD pass a stable reference; a fresh array on every parent
+ * render busts the memo.
+ */
+ attachments?: Attachment[];
+ /** CSS density only — never changes the semantic DOM. */
+ density?: RichContentDensity;
+ /**
+ * Streaming lifecycle. Does not gate fence upgrades (closedness does); it
+ * exists so surfaces can express that content is still arriving.
+ */
+ phase?: RichContentPhase;
+ className?: string;
+}
+
+export const RichContent = memo(function RichContent({
+ content,
+ attachments,
+ density = "document",
+ phase = "settled",
+ className,
+}: RichContentProps) {
+ // Subscribed, not read once. The CDN config is fetched asynchronously after
+ // auth, so content that renders first would otherwise keep its legacy CDN
+ // links as plain anchors permanently — the preprocess step that turns them
+ // into file cards had already run against an empty domain and nothing would
+ // re-run it. Subscribing puts the value in the memo dependencies below, so a
+ // late config arrival reprocesses exactly once.
+ const cdnDomain = useConfigStore((s) => s.cdnDomain);
+
+ const processed = useMemo(
+ () =>
+ highlightToHtml(
+ preprocessMarkdown(content, { cdnDomain, autolinkIssueIdentifiers: true }),
+ ),
+ [content, cdnDomain],
+ );
+
+ // Derived from the SAME string handed to ReactMarkdown, so offsets line up
+ // with the hast node positions the `code`/`pre` renderers observe. Computing
+ // it from the raw pre-preprocess text would mis-match every rewritten node.
+ const closedFences = useMemo(() => computeClosedFenceOffsets(processed), [processed]);
+
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const hover = useLinkHover(wrapperRef);
+
+ // Memoize the react-markdown subtree on its only real inputs. Unrelated
+ // parent re-renders (a sibling agent task streaming over WebSocket fires one
+ // every ~100ms) would otherwise re-run react-markdown, which hands `<code>` a
+ // fresh `dangerouslySetInnerHTML` object each time; React then rewrites the
+ // highlighted innerHTML even though the string is byte-identical, tearing
+ // down every hljs <span> and collapsing any active text selection inside a
+ // code block (MUL-3621). A stable element reference lets React bail out.
+ const markdown = useMemo(
+ () => (
+ <ClosedFenceContext.Provider value={closedFences}>
+ <ReactMarkdown
+ remarkPlugins={REMARK_PLUGINS}
+ rehypePlugins={REHYPE_PLUGINS}
+ urlTransform={markdownUrlTransform}
+ components={COMPONENTS}
+ >
+ {processed}
+ </ReactMarkdown>
+ </ClosedFenceContext.Provider>
+ ),
+ [processed, closedFences],
+ );
+
+ return (
+ <AttachmentDownloadProvider attachments={attachments}>
+ <div
+ ref={wrapperRef}
+ data-rich-content=""
+ data-density={density}
+ data-phase={phase}
+ className={cn(
+ "rich-text-editor readonly text-sm",
+ density === "compact" && "rich-content-compact",
+ className,
+ )}
+ >
+ {markdown}
+ <LinkHoverCard {...hover} />
+ </div>
+ </AttachmentDownloadProvider>
+ );
+});
diff --git a/packages/views/rich-content/rich-fence-block-ssr.test.tsx b/packages/views/rich-content/rich-fence-block-ssr.test.tsx
new file mode 100644
index 0000000000..6e863c22fe
--- /dev/null
+++ b/packages/views/rich-content/rich-fence-block-ssr.test.tsx
@@ -0,0 +1,172 @@
+/**
+ * Cached reserved height must not reach the first frame (MUL-4922).
+ *
+ * The Mermaid layout cache lives in sessionStorage, which a server does not
+ * have. Reading it during render yields the skeleton default on the server and
+ * the cached real height in a browser whose cache is warm — a different
+ * `style="min-height:…"` on the exact frame React hydrates. React reports that
+ * as an attribute mismatch and does NOT repair it.
+ *
+ * These tests drive the REAL RichFenceBlock with a REAL prefilled
+ * sessionStorage entry. An earlier version of the SSR suite passed a fixed
+ * `reservedHeightPx` straight to the lazy shell, which bypassed this path
+ * entirely and passed against the buggy code.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act } from "@testing-library/react";
+import { renderToString } from "react-dom/server";
+import { createRoot, hydrateRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string) => select(editor),
+ }),
+ useTimeAgo: () => "just now",
+ };
+});
+
+vi.mock("mermaid", () => ({
+ default: {
+ initialize: vi.fn(),
+ render: vi.fn().mockResolvedValue({
+ svg: '<svg viewBox="0 0 800 412"><g><text>diagram</text></g></svg>',
+ }),
+ },
+}));
+
+import { RichFenceBlock } from "./rich-code-block";
+import { resetMountedBlocks } from "./mounted-block-registry";
+
+const CHART = "flowchart LR\n A --> B";
+const CACHED_HEIGHT = 412;
+const SKELETON_HEIGHT = 280;
+
+/** Mirrors the DJB2 key derivation in editor/mermaid-diagram.tsx. */
+function cacheKey(chart: string): string {
+ let hash = 5381;
+ for (let i = 0; i < chart.length; i++) {
+ hash = ((hash << 5) + hash) ^ chart.charCodeAt(i);
+ }
+ return `multica:mermaid:layout:${(hash >>> 0).toString(36)}`;
+}
+
+beforeEach(() => {
+ resetMountedBlocks();
+ window.sessionStorage.clear();
+ // A warm cache: this exact chart already rendered earlier in the session.
+ window.sessionStorage.setItem(
+ cacheKey(CHART),
+ JSON.stringify({ width: 800, height: CACHED_HEIGHT }),
+ );
+ vi.stubGlobal("IntersectionObserver", undefined);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ window.sessionStorage.clear();
+});
+
+/**
+ * Render the way a server does: no sessionStorage (and no IntersectionObserver).
+ * jsdom provides both, so without removing them the "server" render would take
+ * the browser's branch and the mismatch would be invisible.
+ */
+function serverRender(ui: Parameters<typeof renderToString>[0]): string {
+ const storage = window.sessionStorage;
+ vi.stubGlobal("sessionStorage", undefined);
+ try {
+ return renderToString(ui);
+ } finally {
+ vi.stubGlobal("sessionStorage", storage);
+ }
+}
+
+const block = () => <RichFenceBlock language="mermaid" body={CHART} />;
+
+describe("RichFenceBlock reserved height", () => {
+ it("reserves the skeleton height on the server, not the cached height", () => {
+ const html = serverRender(block());
+
+ expect(html).toContain(`min-height:${SKELETON_HEIGHT}px`);
+ expect(html).not.toContain(`min-height:${CACHED_HEIGHT}px`);
+ });
+
+ it("uses the skeleton height on the client's first frame despite a warm cache", () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ // No act(): the first committed frame is exactly what must be compared,
+ // before any effect reads the cache.
+ flushSync(() => root.render(block()));
+
+ const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
+ expect(shell.style.minHeight).toBe(`${SKELETON_HEIGHT}px`);
+
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ it("hydrates a warm-cache client against server markup without a mismatch", async () => {
+ const html = serverRender(block());
+
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ document.body.appendChild(container);
+
+ const errors: string[] = [];
+ const errorSpy = vi.spyOn(console, "error").mockImplementation((...args) => {
+ errors.push(args.map(String).join(" "));
+ });
+
+ let root: ReturnType<typeof hydrateRoot> | undefined;
+ await act(async () => {
+ root = hydrateRoot(container, block());
+ });
+
+ expect(errors.filter((e) => /hydrat|did not match|mismatch/i.test(e))).toEqual([]);
+
+ errorSpy.mockRestore();
+ await act(async () => root?.unmount());
+ container.remove();
+ });
+
+ it("adopts the cached height after mount, so the zero-shift benefit survives", async () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(block());
+ });
+
+ const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
+ // The point of the cache is preserved: after hydration the block reserves
+ // the real height rather than a generic skeleton.
+ expect(shell.style.minHeight).toBe(`${CACHED_HEIGHT}px`);
+
+ await act(async () => root.unmount());
+ container.remove();
+ });
+
+ it("falls back to the skeleton height when the cache is cold", async () => {
+ window.sessionStorage.clear();
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(block());
+ });
+
+ const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
+ expect(shell.style.minHeight).toBe(`${SKELETON_HEIGHT}px`);
+
+ await act(async () => root.unmount());
+ container.remove();
+ });
+});
diff --git a/packages/views/rich-content/scroll-root.tsx b/packages/views/rich-content/scroll-root.tsx
new file mode 100644
index 0000000000..28e4e9e339
--- /dev/null
+++ b/packages/views/rich-content/scroll-root.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+/**
+ * Scroll root for near-viewport rich-block mounting (MUL-4922).
+ *
+ * IntersectionObserver clips against its `root`. Left unset it uses the browser
+ * viewport, and `rootMargin` then expands the *viewport* box — which says
+ * nothing useful about a block sitting inside a nested scroll container. Chat's
+ * list scrolls in its own element (`Virtuoso customScrollParent`), so with the
+ * default root a message only counts as "near" once it is already visible, and
+ * the whole point of preloading is lost.
+ *
+ * Surfaces that scroll inside their own element publish it here. Surfaces that
+ * scroll with the page (Issue description, Comment) publish nothing and keep the
+ * viewport root, which is correct for them.
+ */
+
+import { createContext, useContext, type ReactNode } from "react";
+
+const RichContentScrollRootContext = createContext<HTMLElement | null>(null);
+
+export function RichContentScrollRootProvider({
+ scrollRoot,
+ children,
+}: {
+ scrollRoot: HTMLElement | null;
+ children: ReactNode;
+}) {
+ return (
+ <RichContentScrollRootContext.Provider value={scrollRoot}>
+ {children}
+ </RichContentScrollRootContext.Provider>
+ );
+}
+
+/**
+ * The element rich blocks should measure "near-viewport" against, or null to
+ * use the browser viewport.
+ */
+export function useRichContentScrollRoot(): HTMLElement | null {
+ return useContext(RichContentScrollRootContext);
+}
diff --git a/packages/views/rich-content/streaming-fence.test.ts b/packages/views/rich-content/streaming-fence.test.ts
new file mode 100644
index 0000000000..fc0747af5d
--- /dev/null
+++ b/packages/views/rich-content/streaming-fence.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { computeClosedFenceOffsets } from "./streaming-fence";
+
+const isClosed = (src: string, offset = 0): boolean =>
+ computeClosedFenceOffsets(src).has(offset);
+
+describe("computeClosedFenceOffsets", () => {
+ it("treats a closed backtick fence as closed", () => {
+ expect(isClosed("```mermaid\ngraph TD\n```\n")).toBe(true);
+ });
+
+ it("treats an unterminated fence as open", () => {
+ expect(isClosed("```mermaid\ngraph TD\n")).toBe(false);
+ });
+
+ it("treats a bare opener with no content as open", () => {
+ expect(isClosed("```mermaid\n")).toBe(false);
+ });
+
+ // The streaming case that matters: text keeps arriving after the opener but
+ // the closer has not landed yet.
+ it("stays open while content accumulates", () => {
+ expect(isClosed("```mermaid\nflowchart LR\n A --> B\n B --> C\n")).toBe(false);
+ });
+
+ it("handles tilde fences", () => {
+ expect(isClosed("~~~mermaid\ngraph TD\n~~~\n")).toBe(true);
+ expect(isClosed("~~~mermaid\ngraph TD\n")).toBe(false);
+ });
+
+ // CommonMark: a closer must use the same character as the opener.
+ it("does not accept a tilde closer for a backtick opener", () => {
+ expect(isClosed("```mermaid\ngraph TD\n~~~\n")).toBe(false);
+ });
+
+ // CommonMark: a closer must be at least as long as the opener. This is the
+ // case a naive "line of >=3 markers" check reports closed, which would hand
+ // Mermaid a half-written diagram.
+ it("does not accept a shorter closer than the opener", () => {
+ expect(isClosed("````mermaid\ngraph TD\n```\n")).toBe(false);
+ });
+
+ it("accepts a longer closer than the opener", () => {
+ expect(isClosed("```mermaid\ngraph TD\n`````\n")).toBe(true);
+ });
+
+ it("handles an indented fence", () => {
+ expect(isClosed(" ```mermaid\n graph TD\n ```\n", 2)).toBe(true);
+ });
+
+ it("handles a fence inside a list item", () => {
+ const src = "- item\n\n ```mermaid\n graph TD\n ```\n";
+ expect(computeClosedFenceOffsets(src).size).toBe(1);
+ expect(isClosed(src, src.indexOf("```"))).toBe(true);
+ });
+
+ // A ```` md block whose *content* contains a ``` mermaid fence is one code
+ // node, not two — the inner fence must not register as its own block.
+ it("does not report an inner fence of a nested block", () => {
+ const src = "````md\n```mermaid\ngraph TD\n```\n````\n";
+ const offsets = computeClosedFenceOffsets(src);
+ expect(offsets.size).toBe(1);
+ expect(offsets.has(0)).toBe(true);
+ });
+
+ it("reports each block independently when several are present", () => {
+ const src = "```mermaid\ngraph TD\n```\n\ntext\n\n```html\n<b>x</b>\n";
+ const offsets = computeClosedFenceOffsets(src);
+ expect(offsets.has(0)).toBe(true);
+ expect(offsets.has(src.lastIndexOf("```html"))).toBe(false);
+ });
+
+ // The realistic streaming progression: one source, growing one chunk at a
+ // time. The block must flip to closed exactly once, at the closer.
+ it("flips to closed exactly when the closing fence arrives", () => {
+ const steps = [
+ "```mermaid",
+ "```mermaid\n",
+ "```mermaid\nflowchart LR\n",
+ "```mermaid\nflowchart LR\n A --> B\n",
+ "```mermaid\nflowchart LR\n A --> B\n``",
+ "```mermaid\nflowchart LR\n A --> B\n```",
+ ];
+ const results = steps.map((s) => isClosed(s));
+ expect(results).toEqual([false, false, false, false, false, true]);
+ });
+
+ it("ignores an indented (non-fenced) code block", () => {
+ // Four-space indented code has no fence to dangle; it carries no info
+ // string so it can never dispatch to a rich block.
+ const src = " const a = 1\n";
+ expect(computeClosedFenceOffsets(src).size).toBe(1);
+ });
+
+ it("returns an empty set for empty input", () => {
+ expect(computeClosedFenceOffsets("").size).toBe(0);
+ });
+
+ it("returns an empty set for prose with no code", () => {
+ expect(computeClosedFenceOffsets("just some **text**\n").size).toBe(0);
+ });
+});
diff --git a/packages/views/rich-content/streaming-fence.ts b/packages/views/rich-content/streaming-fence.ts
new file mode 100644
index 0000000000..7c9a71c2f9
--- /dev/null
+++ b/packages/views/rich-content/streaming-fence.ts
@@ -0,0 +1,105 @@
+import { fromMarkdown } from "mdast-util-from-markdown";
+import type { Root, RootContent, Code } from "mdast";
+
+/**
+ * Fenced-code closedness gate for streaming RichContent (MUL-4922).
+ *
+ * A Mermaid diagram or sandboxed HTML iframe must never be instantiated from a
+ * fence the author is still typing: mid-stream the source is syntactically
+ * incomplete, so Mermaid would throw on every keystroke and an iframe would be
+ * created and destroyed dozens of times per second. Only a *closed* fence may
+ * upgrade to a rich block.
+ *
+ * This module answers exactly one question — "which fenced code blocks in this
+ * source are closed?" — and returns offsets. It deliberately does NOT render.
+ * Rendering stays in the single ReactMarkdown pipeline; a gate that rendered
+ * would become the second renderer this sweep exists to delete.
+ *
+ * Closedness is derived from a real CommonMark parse rather than a
+ * `startsWith("```")` scan, so indented fences, tilde fences, longer-than-three
+ * markers, fences inside list items, and nested fences are all judged the way
+ * the actual Markdown parser judges them.
+ */
+
+// Opening fence: up to 3 leading spaces, then >= 3 backticks or tildes.
+const FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})/;
+
+function isCodeNode(node: RootContent | Root): node is Code {
+ return node.type === "code";
+}
+
+function collectCodeNodes(node: Root | RootContent, out: Code[]): void {
+ if (isCodeNode(node)) {
+ out.push(node);
+ return;
+ }
+ const children = (node as { children?: RootContent[] }).children;
+ if (children) {
+ for (const child of children) collectCodeNodes(child, out);
+ }
+}
+
+/**
+ * True when `raw` (the exact source span of one mdast `code` node) ends with a
+ * closing fence valid for its own opener.
+ *
+ * CommonMark requires the closer to use the same character as the opener and be
+ * at least as long, so an opener of ```` closed by ``` is still OPEN — the
+ * shorter run is content, not a terminator. Length is checked explicitly
+ * because a regex that only matched "a line of >=3 markers" reports that case
+ * closed and would let a half-written diagram reach Mermaid.
+ */
+function endsWithClosingFence(raw: string): boolean {
+ const lines = raw.split("\n");
+ const openMatch = FENCE_OPEN_RE.exec(lines[0] ?? "");
+ // No opener means an indented (4-space) code block. It has no fence to leave
+ // dangling, and carries no info string, so it can never dispatch to a rich
+ // block — treat it as settled.
+ if (!openMatch?.[1]) return true;
+
+ const openFence = openMatch[1];
+ const marker = openFence[0] as "`" | "~";
+ // A single line cannot be both opener and closer.
+ if (lines.length < 2) return false;
+
+ // mdast may or may not include the trailing newline in the node span.
+ const lastLine = (lines[lines.length - 1] === "" ? lines[lines.length - 2] : lines[lines.length - 1]) ?? "";
+ const closeMatch = /^ {0,3}([`~]+)[ \t]*$/.exec(lastLine);
+ if (!closeMatch?.[1]) return false;
+
+ const closeFence = closeMatch[1];
+ return closeFence[0] === marker && closeFence.length >= openFence.length;
+}
+
+/**
+ * Start offsets of every fenced code block that is closed in `source`.
+ *
+ * `source` MUST be the final processed Markdown handed to ReactMarkdown — the
+ * same string preprocess/highlight already rewrote. Offsets computed against
+ * the raw pre-preprocess text would drift and mis-match the wrong node.
+ */
+export function computeClosedFenceOffsets(source: string): Set<number> {
+ const closed = new Set<number>();
+ if (!source) return closed;
+
+ let tree: Root;
+ try {
+ tree = fromMarkdown(source);
+ } catch {
+ // A parse failure must not upgrade anything: fall back to "nothing is
+ // closed", which shows source instead of running Mermaid on bad input.
+ return closed;
+ }
+
+ const codes: Code[] = [];
+ collectCodeNodes(tree, codes);
+
+ for (const node of codes) {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start == null || end == null) continue;
+ if (endsWithClosingFence(source.slice(start, end))) closed.add(start);
+ }
+
+ return closed;
+}
diff --git a/packages/views/skills/components/file-viewer.tsx b/packages/views/skills/components/file-viewer.tsx
index 9457bfc5df..38fa639fcd 100644
--- a/packages/views/skills/components/file-viewer.tsx
+++ b/packages/views/skills/components/file-viewer.tsx
@@ -9,7 +9,7 @@ import {
parseFrontmatter,
type SkillFrontmatter,
} from "@multica/core/skills/frontmatter";
-import { Markdown } from "../../common/markdown";
+import { RichContent } from "../../rich-content";
import { useT } from "../../i18n";
function isMarkdown(path: string) {
@@ -102,9 +102,11 @@ export function FileViewer({
{isMd && !editing ? (
<div className="p-4 sm:p-6">
{frontmatter && <FrontmatterCard data={frontmatter} />}
- <Markdown mode="full">
- {body || t(($) => $.file_viewer.no_content)}
- </Markdown>
+ <RichContent
+ content={body || t(($) => $.file_viewer.no_content)}
+ density="document"
+ phase="settled"
+ />
</div>
) : (
<Textarea
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a6d2c011fe..a908a936ac 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -632,10 +632,10 @@ importers:
version: 5.6.0
fumadocs-core:
specifier: ^15.5.2
fumadocs-mdx:
specifier: ^12.0.3
input-otp:
specifier: ^1.4.2
@@ -650,7 +650,7 @@ importers:
version: 1.0.1([email protected])
next:
specifier: ^16.2.5
next-themes:
specifier: ^0.4.6
@@ -1073,6 +1073,9 @@ importers:
lucide-react:
specifier: 'catalog:'
version: 1.0.1([email protected])
+ mdast-util-from-markdown:
+ specifier: ^2.0.3
+ version: 2.0.3
mermaid:
specifier: 'catalog:'
version: 11.14.0
@@ -17503,7 +17506,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@formatjs/intl-localematcher': 0.6.2
'@orama/orama': 3.1.18
@@ -17526,7 +17529,7 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
lucide-react: 1.0.1([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
@@ -17559,14 +17562,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@mdx-js/mdx': 3.1.1
'@standard-schema/spec': 1.1.0
chokidar: 4.0.3
esbuild: 0.25.12
estree-util-value-to-estree: 3.5.0
js-yaml: 4.1.1
lru-cache: 11.2.7
mdast-util-to-markdown: 2.1.2
@@ -17579,7 +17582,7 @@ snapshots:
unist-util-visit: 5.1.0
zod: 4.3.6
optionalDependencies:
react: 19.2.3
transitivePeerDependencies:
- supports-color
@@ -19611,7 +19614,7 @@ snapshots:
postcss: 8.5.10
react: 19.2.3
react-dom: 19.2.3([email protected])
- styled-jsx: 5.1.6(@babel/[email protected])([email protected])
+ styled-jsx: 5.1.6([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 15.5.18
'@next/swc-darwin-x64': 15.5.18
@@ -19629,7 +19632,7 @@ snapshots:
- '@babel/core'
- babel-plugin-macros
dependencies:
'@next/env': 16.2.6
'@swc/helpers': 0.5.15
@@ -19638,7 +19641,7 @@ snapshots:
postcss: 8.5.10
react: 19.2.3
react-dom: 19.2.3([email protected])
- styled-jsx: 5.1.6(@babel/[email protected])([email protected])
+ styled-jsx: 5.1.6([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 16.2.6
'@next/swc-darwin-x64': 16.2.6
@@ -21580,12 +21583,10 @@ snapshots:
dependencies:
inline-style-parser: 0.2.7
dependencies:
client-only: 0.0.1
react: 19.2.3
- optionalDependencies:
- '@babel/core': 7.29.0