Skip to content

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

Go

MUL-7649: issue deliverables and dynamic blocks — sidebar section, overview grid, viewer info panel, html/mermaid block frame (#8779)

Jiayuan Zhang7dac88a6a8c5
diff --git a/apps/docs/content/docs/comments.fr.mdx b/apps/docs/content/docs/comments.fr.mdx
index 61a1aaa931..1af010d846 100644
--- a/apps/docs/content/docs/comments.fr.mdx
+++ b/apps/docs/content/docs/comments.fr.mdx
@@ -11,6 +11,8 @@ Les commentaires sont le lieu de la collaboration continue sur une [tâche](/iss
Saisissez votre texte dans la zone Activité de la tâche et envoyez-le pour créer un commentaire. Les commentaires prennent en charge la mise en forme, les blocs de code, les liens et les pièces jointes.
+Un bloc de code `html` ou `mermaid` s’affiche directement sous forme de graphique ou de diagramme, avec un bouton pour voir sa source. Les pièces jointes s’affichent sous forme de cartes qui s’ouvrent dans la visionneuse, y compris les fichiers HTML.
+
Répondre à un commentaire crée un fil de discussion. Les réponses peuvent s'imbriquer davantage, mais elles restent toutes sous la même discussion de premier niveau.
## Annoter des commentaires et des descriptions
diff --git a/apps/docs/content/docs/comments.ja.mdx b/apps/docs/content/docs/comments.ja.mdx
index 9ac92f12c4..2ae7463b54 100644
--- a/apps/docs/content/docs/comments.ja.mdx
+++ b/apps/docs/content/docs/comments.ja.mdx
@@ -11,6 +11,8 @@ import { Callout } from "fumadocs-ui/components/callout";
タスクのアクティビティ欄に入力して送信すると、コメントが作成されます。コメントは書式、コードブロック、リンク、添付ファイルに対応しています。
+`html` または `mermaid` のコードブロックは、その場でグラフや図として表示され、ソース表示に切り替えられます。添付ファイルはカードとして表示され、ビューアーで開きます。HTML ファイルも同様です。
+
コメントに返信するとスレッドになります。返信はさらにネストできますが、すべて同じトップレベルのスレッドの下にまとまります。
## コメントと説明に注釈を付ける
diff --git a/apps/docs/content/docs/comments.ko.mdx b/apps/docs/content/docs/comments.ko.mdx
index 7fb9896a89..74e42ac43e 100644
--- a/apps/docs/content/docs/comments.ko.mdx
+++ b/apps/docs/content/docs/comments.ko.mdx
@@ -11,6 +11,8 @@ import { Callout } from "fumadocs-ui/components/callout";
태스크의 활동 영역에 내용을 입력하고 보내면 댓글이 만들어집니다. 댓글에는 서식, 코드 블록, 링크, 첨부 파일을 사용할 수 있습니다.
+`html` 또는 `mermaid` 코드 블록은 댓글 안에서 바로 차트나 다이어그램으로 표시되며, 소스 보기로 전환할 수 있습니다. 첨부 파일은 카드로 표시되고 뷰어에서 열리며, HTML 파일도 마찬가지입니다.
+
댓글에 답글을 달면 논의 스레드가 만들어집니다. 답글은 계속 중첩할 수 있지만 모두 같은 최상위 논의 아래에 속합니다.
## 댓글과 설명에 주석 달기
diff --git a/apps/docs/content/docs/comments.mdx b/apps/docs/content/docs/comments.mdx
index 1037ba3492..3a9fc3a76c 100644
--- a/apps/docs/content/docs/comments.mdx
+++ b/apps/docs/content/docs/comments.mdx
@@ -11,6 +11,8 @@ Comments are where ongoing collaboration on an [issue](/issues) happens. Members
Type into the issue's activity area and send to create a comment. Comments support formatting, code blocks, links, and attachments.
+An `html` or `mermaid` code block renders in place as a chart or diagram, with a switch to its source. Attached files show as cards that open in the viewer; that includes HTML files.
+
Replying to a comment forms a discussion thread. Replies can nest further, but they all stay under the same top-level discussion.
## Annotate comments and descriptions
diff --git a/apps/docs/content/docs/comments.zh.mdx b/apps/docs/content/docs/comments.zh.mdx
index 5de638ee65..1dff9f18df 100644
--- a/apps/docs/content/docs/comments.zh.mdx
+++ b/apps/docs/content/docs/comments.zh.mdx
@@ -11,6 +11,8 @@ import { Callout } from "fumadocs-ui/components/callout";
在任务的动态区输入内容并发送,即可创建一条评论。评论支持格式、代码块、链接和附件。
+`html` 或 `mermaid` 代码块会直接在评论里渲染成图表或图示,可以切换查看源码。附件以卡片显示,点击在查看器中打开,HTML 文件也是如此。
+
回复某条评论会形成一条讨论线程。回复可以继续嵌套,但都归在同一条顶层讨论下。
## 批注评论与任务描述
diff --git a/packages/core/attachments/deliverables.test.ts b/packages/core/attachments/deliverables.test.ts
new file mode 100644
index 0000000000..e09666fdca
--- /dev/null
+++ b/packages/core/attachments/deliverables.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { Attachment } from "../types/attachment";
+import {
+ collectDeliverableFiles,
+ deliverableKey,
+ findDeliverableVersion,
+} from "./deliverables";
+
+function attachment(over: Partial<Attachment> & { id: string }): Attachment {
+ return {
+ workspace_id: "ws",
+ issue_id: "issue",
+ comment_id: "c1",
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "agent",
+ uploader_id: "agent-1",
+ filename: "report.md",
+ url: `https://cdn.example.com/${over.id}`,
+ download_url: `/api/attachments/${over.id}/download`,
+ markdown_url: `https://api.example.com/api/attachments/${over.id}/download`,
+ content_type: "text/markdown",
+ size_bytes: 100,
+ created_at: "2026-09-20T10:00:00Z",
+ ...over,
+ } as Attachment;
+}
+
+describe("deliverableKey", () => {
+ it("ignores content-type parameters and case", () => {
+ expect(
+ deliverableKey({ filename: "index.html", content_type: "text/html; charset=utf-8" }),
+ ).toBe(deliverableKey({ filename: "index.html", content_type: "TEXT/HTML" }));
+ });
+
+ it("separates same-named files of different types", () => {
+ expect(deliverableKey({ filename: "out", content_type: "image/png" })).not.toBe(
+ deliverableKey({ filename: "out", content_type: "text/plain" }),
+ );
+ });
+});
+
+describe("collectDeliverableFiles", () => {
+ it("merges re-uploads of the same file into versions, oldest first", () => {
+ const v1 = attachment({ id: "a1", comment_id: "c1", created_at: "2026-09-20T10:00:00Z" });
+ const v2 = attachment({ id: "a2", comment_id: "c2", created_at: "2026-09-21T10:00:00Z" });
+ const files = collectDeliverableFiles([
+ { id: "c2", type: "comment", attachments: [v2] },
+ { id: "c1", type: "comment", attachments: [v1] },
+ ]);
+ expect(files).toHaveLength(1);
+ expect(files[0]!.versions.map((a) => a.id)).toEqual(["a1", "a2"]);
+ expect(files[0]!.latest.id).toBe("a2");
+ });
+
+ it("lists files newest first by their latest version", () => {
+ const shot = attachment({
+ id: "s1",
+ filename: "shot.png",
+ content_type: "image/png",
+ created_at: "2026-09-20T09:00:00Z",
+ });
+ const reportV1 = attachment({ id: "r1", created_at: "2026-09-20T08:00:00Z" });
+ const reportV2 = attachment({ id: "r2", created_at: "2026-09-22T08:00:00Z" });
+ const files = collectDeliverableFiles([
+ { id: "c1", type: "comment", attachments: [reportV1, shot] },
+ { id: "c2", type: "comment", attachments: [reportV2] },
+ ]);
+ expect(files.map((f) => f.latest.id)).toEqual(["r2", "s1"]);
+ });
+
+ it("breaks a created_at tie by upload order (UUIDv7 ids)", () => {
+ const first = attachment({ id: "01a0-0001" });
+ const second = attachment({ id: "01a0-0002" });
+ const [file] = collectDeliverableFiles([
+ { id: "c1", attachments: [second, first] },
+ ]);
+ expect(file!.versions.map((a) => a.id)).toEqual(["01a0-0001", "01a0-0002"]);
+ });
+
+ it("skips activities, tombstoned comments and repeated ids", () => {
+ const a = attachment({ id: "a1" });
+ const files = collectDeliverableFiles([
+ { id: "act", type: "activity", attachments: [attachment({ id: "x" })] },
+ {
+ id: "gone",
+ type: "comment",
+ deleted_at: "2026-09-21T00:00:00Z",
+ attachments: [attachment({ id: "y", filename: "y.md" })],
+ },
+ { id: "c1", type: "comment", attachments: [a] },
+ { id: "c1-copy", type: "comment", attachments: [a] },
+ null,
+ ]);
+ expect(files).toHaveLength(1);
+ expect(files[0]!.versions.map((v) => v.id)).toEqual(["a1"]);
+ });
+});
+
+describe("findDeliverableVersion", () => {
+ const v1 = attachment({ id: "a1", created_at: "2026-09-20T10:00:00Z" });
+ const v2 = attachment({ id: "a2", created_at: "2026-09-21T10:00:00Z" });
+ const files = collectDeliverableFiles([{ id: "c1", attachments: [v1, v2] }]);
+
+ it("returns the file and the 1-based version", () => {
+ expect(findDeliverableVersion(files, "a1")?.version).toBe(1);
+ expect(findDeliverableVersion(files, "a2")?.version).toBe(2);
+ });
+
+ it("returns undefined for files that are not deliverables", () => {
+ expect(findDeliverableVersion(files, "description-file")).toBeUndefined();
+ expect(findDeliverableVersion(files, "")).toBeUndefined();
+ });
+});
diff --git a/packages/core/attachments/deliverables.ts b/packages/core/attachments/deliverables.ts
new file mode 100644
index 0000000000..af4a90e7c8
--- /dev/null
+++ b/packages/core/attachments/deliverables.ts
@@ -0,0 +1,113 @@
+/**
+ * Issue deliverables — the files an issue as a whole has produced (MUL-7649).
+ *
+ * A deliverable file is something uploaded in a comment. Attachments on the
+ * issue description are inputs (the brief, reference material), not output,
+ * so they never count.
+ *
+ * Re-uploading a file under the same name and type is a new VERSION of that
+ * file, not another deliverable: agents iterate on a report or a screenshot
+ * across runs, and the reader wants the latest one with its history behind
+ * it, not five near-identical rows.
+ *
+ * Built from comment entries rather than the issue-wide attachment list: the
+ * list is fetched before the upload is bound to its comment and is not
+ * refreshed when that bind lands, while the timeline is patched live and
+ * already carries each comment's attachments.
+ *
+ * Pure — no React, no DOM, no platform APIs.
+ */
+
+import type { Attachment } from "../types/attachment";
+
+/** The part of a timeline comment this module reads. */
+export interface DeliverableSourceComment {
+ id: string;
+ type?: string;
+ attachments?: ReadonlyArray<Attachment> | null;
+ /** Tombstoned comments render no files, so they contribute none. */
+ deleted_at?: string | null;
+}
+
+export interface DeliverableFile {
+ /** Identity shared by every version: normalized content type + filename. */
+ key: string;
+ /** Every upload of this file, oldest first. Never empty. */
+ versions: Attachment[];
+ /** The newest upload — what lists show and open. */
+ latest: Attachment;
+}
+
+function normalizeContentType(contentType: string): string {
+ const ct = (contentType ?? "").toLowerCase().trim();
+ const semi = ct.indexOf(";");
+ return (semi >= 0 ? ct.slice(0, semi) : ct).trim();
+}
+
+/**
+ * Two uploads are versions of one file when their name and type match. The
+ * type is compared without parameters so `text/html; charset=utf-8` from one
+ * client and `text/html` from another still line up.
+ */
+export function deliverableKey(
+ attachment: Pick<Attachment, "filename" | "content_type">,
+): string {
+ return `${normalizeContentType(attachment.content_type)}\u0000${(attachment.filename ?? "").trim()}`;
+}
+
+// Oldest first. Attachment ids are UUIDv7, so the id breaks a created_at tie
+// in upload order.
+function compareUploadOrder(a: Attachment, b: Attachment): number {
+ const at = Date.parse(a.created_at);
+ const bt = Date.parse(b.created_at);
+ if (at !== bt) return (Number.isNaN(at) ? 0 : at) - (Number.isNaN(bt) ? 0 : bt);
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+}
+
+/**
+ * Group every file uploaded in `comments` into deliverables, newest first
+ * (by each file's latest version).
+ */
+export function collectDeliverableFiles(
+ comments: ReadonlyArray<DeliverableSourceComment | null | undefined>,
+): DeliverableFile[] {
+ const byKey = new Map<string, Attachment[]>();
+ const seen = new Set<string>();
+
+ for (const comment of comments) {
+ if (!comment || comment.deleted_at) continue;
+ if (comment.type !== undefined && comment.type !== "comment") continue;
+ for (const attachment of comment.attachments ?? []) {
+ if (!attachment?.id || seen.has(attachment.id)) continue;
+ seen.add(attachment.id);
+ const key = deliverableKey(attachment);
+ const versions = byKey.get(key);
+ if (versions) versions.push(attachment);
+ else byKey.set(key, [attachment]);
+ }
+ }
+
+ const files: DeliverableFile[] = [];
+ for (const [key, versions] of byKey) {
+ versions.sort(compareUploadOrder);
+ files.push({ key, versions, latest: versions[versions.length - 1]! });
+ }
+ return files.sort((a, b) => compareUploadOrder(b.latest, a.latest));
+}
+
+/**
+ * The deliverable an attachment belongs to and its 1-based version number, or
+ * undefined when the attachment is not a deliverable (a description file, a
+ * file from another surface).
+ */
+export function findDeliverableVersion(
+ files: ReadonlyArray<DeliverableFile>,
+ attachmentId: string,
+): { file: DeliverableFile; version: number } | undefined {
+ if (!attachmentId) return undefined;
+ for (const file of files) {
+ const index = file.versions.findIndex((v) => v.id === attachmentId);
+ if (index >= 0) return { file, version: index + 1 };
+ }
+ return undefined;
+}
diff --git a/packages/core/attachments/image-sequence.test.ts b/packages/core/attachments/image-sequence.test.ts
index f13732f2f5..88bb483c67 100644
--- a/packages/core/attachments/image-sequence.test.ts
+++ b/packages/core/attachments/image-sequence.test.ts
@@ -6,6 +6,7 @@ import {
indexOfImageKey,
isImageAttachment,
matchAttachmentByURL,
+ orderStandaloneAttachments,
selectStandaloneAttachments,
} from "./image-sequence";
@@ -292,6 +293,29 @@ describe("collectAttachmentSequence", () => {
]);
});
+ it("tags each item with the block it first appeared in", () => {
+ const shared = attachment({ id: UUID_A });
+ const own = attachment({ id: UUID_B, filename: "own.png" });
+ const sequence = collectAttachmentSequence(
+ [
+ {
+ id: "description",
+ content: `![](/api/attachments/${UUID_A}/download)`,
+ attachments: [shared],
+ standalone: false,
+ },
+ { id: "comment-1", content: `![](/api/attachments/${UUID_A}/download)`, attachments: [shared, own] },
+ { content: "![untagged](https://cdn/x.png)" },
+ ],
+ previewable,
+ );
+ expect(sequence.map((i) => [i.key, i.blockId])).toEqual([
+ [UUID_A, "description"],
+ [UUID_B, "comment-1"],
+ ["https://cdn/x.png", undefined],
+ ]);
+ });
+
it("keeps markdown images even when the rule would reject their caption", () => {
const sequence = collectAttachmentSequence(
[{ content: "![报告图表](https://cdn/chart)" }],
@@ -301,6 +325,26 @@ describe("collectAttachmentSequence", () => {
});
});
+describe("orderStandaloneAttachments", () => {
+ it("puts images first, then every other file — HTML included — keeping order within each", () => {
+ const md = attachment({ id: "md", filename: "notes.md", content_type: "text/markdown" });
+ const shot1 = attachment({ id: "s1", filename: "a.png" });
+ const page = attachment({ id: "h", filename: "report.html", content_type: "text/html; charset=utf-8" });
+ const csv = attachment({ id: "csv", filename: "data.csv", content_type: "text/csv" });
+ const shot2 = attachment({ id: "s2", filename: "b.jpg", content_type: "" });
+ expect(orderStandaloneAttachments([md, shot1, page, csv, shot2]).map((a) => a.id)).toEqual([
+ "s1", "s2", "md", "h", "csv",
+ ]);
+ });
+
+ it("is the order the sequence walks a block's standalone files in", () => {
+ const md = attachment({ id: UUID_A, filename: "notes.md", content_type: "text/markdown" });
+ const shot = attachment({ id: UUID_B, filename: "a.png" });
+ const sequence = collectAttachmentSequence([{ attachments: [md, shot] }], () => true);
+ expect(sequence.map((i) => i.key)).toEqual([UUID_B, UUID_A]);
+ });
+});
+
describe("indexOfImageKey", () => {
it("finds a key and reports -1 for anything else", () => {
const items = collectImageSequence([
diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.ts
index 0bacb7c2ed..831bc4db59 100644
--- a/packages/core/attachments/image-sequence.ts
+++ b/packages/core/attachments/image-sequence.ts
@@ -150,6 +150,33 @@ export function selectStandaloneAttachments(
});
}
+/**
+ * How a standalone attachment is laid out under its body (MUL-7649): images
+ * as a row of thumbnails, everything else — HTML included — as file cards.
+ */
+export type StandaloneAttachmentGroup = "image" | "file";
+
+export function standaloneAttachmentGroup(
+ attachment: Pick<Attachment, "content_type" | "filename">,
+): StandaloneAttachmentGroup {
+ return isImageAttachment(attachment.content_type, attachment.filename) ? "image" : "file";
+}
+
+/**
+ * The order a surface renders its standalone attachments in (MUL-7649):
+ * images first (a row of thumbnails), then everything else (a grid of file
+ * cards). Stable within each group. The sequence builder walks standalone
+ * attachments in this same order, so paging through the viewer follows the
+ * screen.
+ */
+export function orderStandaloneAttachments<T extends Pick<Attachment, "content_type" | "filename">>(
+ attachments: ReadonlyArray<T>,
+): T[] {
+ const groups: Record<StandaloneAttachmentGroup, T[]> = { image: [], file: [] };
+ for (const a of attachments) groups[standaloneAttachmentGroup(a)].push(a);
+ return [...groups.image, ...groups.file];
+}
+
// ---------------------------------------------------------------------------
// Inline image references
// ---------------------------------------------------------------------------
@@ -295,10 +322,17 @@ export interface ImageSequenceItem {
* markdown caption, which is prose with no extension to read (MUL-7518).
*/
imageByConstruction: boolean;
+ /**
+ * `id` of the block the item first appeared in, when the caller named its
+ * blocks — lets a viewer say where a file came from (MUL-7649).
+ */
+ blockId?: string;
}
/** One renderable unit: an issue description, a comment, a chat message. */
export interface ImageSequenceBlock {
+ /** Caller-chosen identity, copied onto each item as `blockId`. */
+ id?: string;
content?: string | null;
attachments?: ReadonlyArray<Attachment> | null;
/**
@@ -322,7 +356,8 @@ export interface SequenceCandidate {
* Flatten blocks into the ordered sequence a viewer walks.
*
* Order is render order: for each block, references inline in the body in
- * text order, then the standalone attachment cards rendered under it. Repeats
+ * text order, then the standalone attachments rendered under it, grouped as
+ * `orderStandaloneAttachments` lays them out. Repeats
* of the same attachment collapse to their first position, so the counter
* matches the number of distinct files rather than the number of references.
*
@@ -370,11 +405,14 @@ export function collectAttachmentSequence(
filename: attachment?.filename || ref.filename,
attachment,
imageByConstruction: !ref.isFileCard,
+ blockId: block.id,
});
}
if (block.standalone === false) continue;
- for (const attachment of selectStandaloneAttachments(content, attachments)) {
+ for (const attachment of orderStandaloneAttachments(
+ selectStandaloneAttachments(content, attachments),
+ )) {
if (
!include({
contentType: attachment.content_type,
@@ -391,6 +429,7 @@ export function collectAttachmentSequence(
filename: attachment.filename,
attachment,
imageByConstruction: false,
+ blockId: block.id,
});
}
}
diff --git a/packages/core/attachments/index.ts b/packages/core/attachments/index.ts
index 4bfb6600a8..80ae55681c 100644
--- a/packages/core/attachments/index.ts
+++ b/packages/core/attachments/index.ts
@@ -1,11 +1,21 @@
+export {
+ collectDeliverableFiles,
+ deliverableKey,
+ findDeliverableVersion,
+ type DeliverableFile,
+ type DeliverableSourceComment,
+} from "./deliverables";
export {
collectAttachmentSequence,
collectImageSequence,
indexOfImageKey,
isImageAttachment,
matchAttachmentByURL,
+ orderStandaloneAttachments,
selectStandaloneAttachments,
+ standaloneAttachmentGroup,
type ImageSequenceBlock,
type ImageSequenceItem,
type SequenceCandidate,
+ type StandaloneAttachmentGroup,
} from "./image-sequence";
diff --git a/packages/core/package.json b/packages/core/package.json
index 856ba91028..85e0de7761 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -14,6 +14,7 @@
"./types": "./types/index.ts",
"./types/*": "./types/*.ts",
"./attachments": "./attachments/index.ts",
+ "./attachments/deliverables": "./attachments/deliverables.ts",
"./attachments/image-sequence": "./attachments/image-sequence.ts",
"./api": "./api/index.ts",
"./api/client": "./api/client.ts",
diff --git a/packages/views/attachments/attachment-preview-page.tsx b/packages/views/attachments/attachment-preview-page.tsx
index aea928637e..6a950eeb9d 100644
--- a/packages/views/attachments/attachment-preview-page.tsx
+++ b/packages/views/attachments/attachment-preview-page.tsx
@@ -3,12 +3,12 @@
/**
* AttachmentPreviewPage — full-page HTML attachment viewer.
*
- * Destination for `openInNewTab` from HtmlAttachmentPreview's toolbar. The
- * inline preview (HtmlAttachmentPreview) renders the same content in a 480px
- * card with a hover toolbar; this is the same content edge-to-edge so the
- * user can resize / interact with the document at full size.
+ * Destination for "Open in new tab" in the attachment viewer's html kind. The
+ * viewer shows the same content inside its stage; this is the same content
+ * edge-to-edge so the user can resize / interact with the document at full
+ * size.
*
- * Same security posture as the inline preview: iframe sandbox is
+ * Same security posture as the viewer: iframe sandbox is
* "allow-scripts" only — no allow-same-origin, no allow-top-navigation. The
* iframe runs in an opaque origin and cannot reach cookies, localStorage,
* parent, or top-level navigation.
diff --git a/packages/views/attachments/use-html-preview-scroll-restore.ts b/packages/views/attachments/use-html-preview-scroll-restore.ts
index 601d8a4f07..a3aeb25650 100644
--- a/packages/views/attachments/use-html-preview-scroll-restore.ts
+++ b/packages/views/attachments/use-html-preview-scroll-restore.ts
@@ -26,8 +26,8 @@
* reports, so a content change followed by an immediate tab switch can
* never resurrect the old position.
*
- * Scope: only the full-page `AttachmentPreviewPage` calls this. The inline
- * 480px card / modal path renders via a separate component
+ * Scope: only the full-page `AttachmentPreviewPage` calls this. The viewer
+ * modal renders via a separate component
* (`HtmlPreviewBody` → `CodeBlockIframe`) and never touches this hook, so it
* cannot register an external source against the current tab. On web
* (no provider / adapter without `registerExternalSource`) `restoreActive`
diff --git a/packages/views/editor/attachment-card.test.tsx b/packages/views/editor/attachment-card.test.tsx
index 396a1612a5..c659e49fd7 100644
--- a/packages/views/editor/attachment-card.test.tsx
+++ b/packages/views/editor/attachment-card.test.tsx
@@ -9,19 +9,20 @@ vi.mock("../i18n", () => ({
attachment: {
preview: "Preview",
preview_loading: "Loading preview…",
+ remove: "Remove attachment",
},
file_card: { uploading: "Uploading {{filename}}" },
}),
}),
}));
-import { AttachmentCard } from "./attachment-card";
+import { AttachmentCard, AttachmentFileCard } from "./attachment-card";
beforeEach(() => vi.clearAllMocks());
afterEach(() => vi.restoreAllMocks());
describe("AttachmentCard — chrome row", () => {
- it("renders chrome only and never an inline iframe (HTML rich preview lives in HtmlAttachmentPreview)", () => {
+ it("renders chrome only and never an inline iframe", () => {
render(
<AttachmentCard
filename="report.html"
@@ -139,3 +140,79 @@ describe("AttachmentCard — Eye / Download buttons", () => {
expect(screen.getByText("Uploading {{filename}}")).toBeTruthy();
});
});
+
+describe("AttachmentFileCard — a file in a grid of cards (MUL-7649)", () => {
+ it("shows the name, its badge and TYPE · size", () => {
+ render(
+ <AttachmentFileCard
+ filename="实现说明.md"
+ contentType="text/markdown"
+ sizeBytes={6 * 1024}
+ canPreview
+ canDownload
+ badge={<span>v2</span>}
+ onPreview={() => {}}
+ onDownload={() => {}}
+ />,
+ );
+ expect(screen.getByText("实现说明.md")).toBeTruthy();
+ expect(screen.getByText("v2")).toBeTruthy();
+ expect(screen.getByText("MD · 6 KB")).toBeTruthy();
+ });
+
+ it("opens the file when the card is clicked, and downloads from its own button", () => {
+ const onPreview = vi.fn();
+ const onDownload = vi.fn();
+ render(
+ <AttachmentFileCard
+ filename="spec.pdf"
+ canPreview
+ canDownload
+ onPreview={onPreview}
+ onDownload={onDownload}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "spec.pdf" }));
+ expect(onPreview).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole("button", { name: "Download" }));
+ expect(onDownload).toHaveBeenCalledTimes(1);
+ expect(onPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("downloads on click when the viewer cannot show the file", () => {
+ const onPreview = vi.fn();
+ const onDownload = vi.fn();
+ render(
+ <AttachmentFileCard
+ filename="bundle.zip"
+ canPreview={false}
+ canDownload
+ onPreview={onPreview}
+ onDownload={onDownload}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "bundle.zip" }));
+ expect(onDownload).toHaveBeenCalledTimes(1);
+ expect(onPreview).not.toHaveBeenCalled();
+ });
+
+ it("offers remove only when the surface is editable", () => {
+ const onDelete = vi.fn();
+ const { rerender } = render(
+ <AttachmentFileCard filename="a.csv" canPreview canDownload onPreview={() => {}} onDownload={() => {}} />,
+ );
+ expect(screen.queryByRole("button", { name: "Remove attachment" })).toBeNull();
+ rerender(
+ <AttachmentFileCard
+ filename="a.csv"
+ canPreview
+ canDownload
+ onPreview={() => {}}
+ onDownload={() => {}}
+ onDelete={onDelete}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Remove attachment" }));
+ expect(onDelete).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsx
index 4da1a0acd6..a721256943 100644
--- a/packages/views/editor/attachment-card.tsx
+++ b/packages/views/editor/attachment-card.tsx
@@ -1,17 +1,22 @@
"use client";
/**
- * AttachmentCard — shared file-card row UI (icon + filename + Eye + Download).
+ * AttachmentCard — shared file-card row UI (icon + filename + Eye + Download),
+ * and AttachmentFileCard — the compact card a list of standalone attachments
+ * lays out in a grid (MUL-7649).
*
- * Subcomponent of the unified `<Attachment>` dispatcher (see attachment.tsx).
- * Rendered for every attachment kind that does not have a richer inline
- * renderer (image / html). Kind-aware routing lives in `<Attachment>` — keep
- * that decision out of this file so this stays a single-purpose row UI.
+ * Subcomponents of the unified `<Attachment>` dispatcher (see attachment.tsx).
+ * Rendered for every attachment kind except images, which render inline.
+ * Kind-aware routing lives in `<Attachment>` — keep that decision out of this
+ * file so these stay single-purpose UI.
*/
+import type { ReactNode } from "react";
import { Download, Eye, FileText, Loader2, Trash2 } from "lucide-react";
import { useT } from "../i18n";
-import { canOpenPreview, getPreviewKind } from "./utils/preview";
+import { formatBytes } from "../common/format-bytes";
+import { fileIcon } from "./utils/file-icon";
+import { canOpenPreview, fileTypeLabel, getPreviewKind } from "./utils/preview";
interface AttachmentCardChromeProps {
filename: string;
@@ -154,3 +159,106 @@ export function AttachmentCard({
</div>
);
}
+
+export interface AttachmentFileCardProps {
+ filename: string;
+ contentType?: string;
+ /** 0 or absent hides the size. */
+ sizeBytes?: number;
+ canPreview: boolean;
+ canDownload: boolean;
+ uploading?: boolean;
+ /** Rendered after the filename, e.g. a version badge. */
+ badge?: ReactNode;
+ onPreview: () => void;
+ onDownload: () => void;
+ onDelete?: () => void;
+}
+
+/**
+ * A file as a card: type glyph, name, "TYPE · size". The whole card opens the
+ * file — the viewer when it can show it, a download otherwise — and download /
+ * remove wait on hover so a grid of cards stays quiet.
+ */
+export function AttachmentFileCard({
+ filename,
+ contentType = "",
+ sizeBytes = 0,
+ canPreview,
+ canDownload,
+ uploading,
+ badge,
+ onPreview,
+ onDownload,
+ onDelete,
+}: AttachmentFileCardProps) {
+ const { t } = useT("editor");
+ const Icon = fileIcon(contentType, filename);
+ const meta = [fileTypeLabel(filename), sizeBytes > 0 ? formatBytes(sizeBytes) : ""]
+ .filter(Boolean)
+ .join(" · ");
+ const open = canPreview ? onPreview : canDownload ? onDownload : undefined;
+
+ return (
+ <div className="group/file-card relative flex min-w-0 items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors hover:bg-muted/50">
+ {/* The card's click target, under the content so text stays
+ selectable-looking but every click lands here; the action buttons
+ sit above it. */}
+ {open && !uploading && (
+ <button
+ type="button"
+ className="absolute inset-0 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ title={filename}
+ aria-label={filename}
+ onClick={open}
+ />
+ )}
+ <span className="pointer-events-none flex size-10 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ {uploading ? (
+ <Loader2 className="size-5 animate-spin" />
+ ) : (
+ <Icon className="size-5" />
+ )}
+ </span>
+ <span className="pointer-events-none min-w-0 flex-1">
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-body font-medium">
+ {uploading ? t(($) => $.file_card.uploading, { filename }) : filename}
+ </span>
+ {badge}
+ </span>
+ {meta && (
+ <span className="block truncate text-caption text-muted-foreground tabular-nums">
+ {meta}
+ </span>
+ )}
+ </span>
+ {!uploading && (canDownload || onDelete) && (
+ <span className="relative flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover/file-card:opacity-100 group-focus-within/file-card:opacity-100 [@media(hover:none)]:opacity-100">
+ {canDownload && (
+ <button
+ type="button"
+ className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ title={t(($) => $.image.download)}
+ aria-label={t(($) => $.image.download)}
+ onClick={onDownload}
+ >
+ <Download className="size-4" />
+ </button>
+ )}
+ {onDelete && (
+ <button
+ type="button"
+ className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
+ title={t(($) => $.attachment.remove)}
+ aria-label={t(($) => $.attachment.remove)}
+ onClick={onDelete}
+ >
+ <Trash2 className="size-4" />
+ </button>
+ )}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 21fee817ab..3a60864f93 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -65,7 +65,10 @@ import {
FileText,
FileVideo,
ImageIcon,
+ LayoutGrid,
Loader2,
+ MessageSquareText,
+ PanelRight,
X,
type LucideIcon,
} from "lucide-react";
@@ -209,6 +212,19 @@ export interface PreviewSequence {
onNext?: () => void;
}
+/** "Show where this was posted" — labelled by the host, which knows where. */
+export interface PreviewLocateAction {
+ label: string;
+ onSelect: () => void;
+}
+
+/** The info panel beside the stage (MUL-7649). Its open state outlives the file. */
+export interface PreviewInfoPanel {
+ content: ReactNode;
+ open: boolean;
+ onToggle: () => void;
+}
+
interface AttachmentPreviewModalProps {
source: PreviewSource;
open: boolean;
@@ -216,6 +232,14 @@ interface AttachmentPreviewModalProps {
sequence?: PreviewSequence;
/** Fired when the image kind fails to load — lets a gallery skip the frame. */
onImageError?: () => void;
+ /** Rendered after the file name, e.g. a version switcher. */
+ titleAccessory?: ReactNode;
+ /** Adds the info button and `I`. */
+ info?: PreviewInfoPanel;
+ /** Adds "show where this was posted": the caller closes the viewer and scrolls. */
+ locate?: PreviewLocateAction;
+ /** Adds the overview button and `G`. */
+ onOpenOverview?: () => void;
}
// ---------------------------------------------------------------------------
@@ -379,6 +403,13 @@ function ownsArrowKeys(target: EventTarget | null): boolean {
return target.closest("input, textarea, select, video, audio") !== null;
}
+// Letter shortcuts stand down only where the reader could be typing.
+function isTypingTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ if (target.isContentEditable) return true;
+ return target.closest("input, textarea, select") !== null;
+}
+
export function AttachmentPreviewModal({
source,
open,
@@ -386,6 +417,10 @@ export function AttachmentPreviewModal({
onExitComplete,
sequence,
onImageError,
+ titleAccessory,
+ info,
+ locate,
+ onOpenOverview,
}: AttachmentPreviewModalProps & { onExitComplete?: () => void }) {
const download = useDownloadAttachment();
const shouldReduceMotion = useReducedMotion() ?? false;
@@ -397,6 +432,7 @@ export function AttachmentPreviewModal({
const onPrev = sequence?.onPrev;
const onNext = sequence?.onNext;
+ const onToggleInfo = info?.onToggle;
// macOS desktop: hide the traffic lights while the viewer is up — its top
// bar starts at the window's top-left corner, where they would sit on the
@@ -406,6 +442,9 @@ export function AttachmentPreviewModal({
useEffect(() => {
if (!open) return;
const handler = (e: KeyboardEvent) => {
+ // A menu opened from the chrome (the version switcher) owns its keys:
+ // Escape closes the menu, not the viewer, and arrows move its focus.
+ if (e.target instanceof Element && e.target.closest('[role="menu"]')) return;
if (e.key === "Escape") {
onClose();
return;
@@ -415,6 +454,21 @@ export function AttachmentPreviewModal({
// `horizontalArrowPan` below), so exactly one of the two responds.
// Modified presses stay with the browser / OS.
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (!e.repeat && !isTypingTarget(e.target)) {
+ // Claimed with preventDefault so the app's own single-key shortcuts
+ // (which skip handled events) don't also fire behind the viewer.
+ const letter = e.key.toLowerCase();
+ if (letter === "g" && onOpenOverview) {
+ e.preventDefault();
+ onOpenOverview();
+ return;
+ }
+ if (letter === "i" && onToggleInfo) {
+ e.preventDefault();
+ onToggleInfo();
+ return;
+ }
+ }
if (ownsArrowKeys(e.target)) return;
if (e.key === "ArrowLeft" && onPrev) {
e.preventDefault();
@@ -426,7 +480,7 @@ export function AttachmentPreviewModal({
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
- }, [open, onClose, onPrev, onNext]);
+ }, [open, onClose, onPrev, onNext, onOpenOverview, onToggleInfo]);
const kind = state.kind;
@@ -441,8 +495,8 @@ export function AttachmentPreviewModal({
}
};
- // Open-in-new-tab mirrors HtmlAttachmentPreview's inline toolbar: only the
- // `html` kind has a dedicated full-page route (/attachments/{id}/preview).
+ // Open-in-new-tab: only the `html` kind has a dedicated full-page route
+ // (/attachments/{id}/preview).
// Gated on slug + attachmentId for the same reason — URL-only sources
// can't address the /content proxy the page relies on.
const canOpenInNewTab = kind === "html" && !!slug && !!state.attachmentId;
@@ -518,6 +572,10 @@ export function AttachmentPreviewModal({
sequence={sequence}
onImageError={onImageError}
reduceMotion={shouldReduceMotion}
+ titleAccessory={titleAccessory}
+ info={info}
+ locate={locate}
+ onOpenOverview={onOpenOverview}
/>
</motion.div>
)}
@@ -553,6 +611,10 @@ function PreviewPanel({
sequence,
onImageError,
reduceMotion,
+ titleAccessory,
+ info,
+ locate,
+ onOpenOverview,
}: {
kind: PreviewKind | null;
source: PreviewSource;
@@ -563,6 +625,10 @@ function PreviewPanel({
sequence?: PreviewSequence;
onImageError?: () => void;
reduceMotion: boolean;
+ titleAccessory?: ReactNode;
+ info?: PreviewInfoPanel;
+ locate?: PreviewLocateAction;
+ onOpenOverview?: () => void;
}) {
const { t } = useT("editor");
@@ -647,7 +713,10 @@ function PreviewPanel({
<KindIcon className="size-4" />
</span>
<div className="min-w-0">
- <p className="truncate text-body font-medium">{state.filename}</p>
+ <div className="flex min-w-0 items-center gap-2" style={titleAccessory ? NO_DRAG : undefined}>
+ <p className="truncate text-body font-medium">{state.filename}</p>
+ {titleAccessory}
+ </div>
{meta.length > 0 && (
<p className="truncate text-caption text-muted-foreground tabular-nums">
{meta.join(" · ")}
@@ -682,6 +751,11 @@ function PreviewPanel({
<ChromeDivider />
</>
)}
+ {locate && (
+ <ChromeButton label={locate.label} onClick={locate.onSelect}>
+ <MessageSquareText className="size-4" />
+ </ChromeButton>
+ )}
{onOpenInNewTab && (
<ChromeButton
label={t(($) => $.attachment.open_in_new_tab)}
@@ -693,63 +767,95 @@ function PreviewPanel({
<ChromeButton label={t(($) => $.image.download)} onClick={onDownload}>
<Download className="size-4" />
</ChromeButton>
+ {(onOpenOverview || info) && <ChromeDivider />}
+ {onOpenOverview && (
+ <ChromeButton
+ label={t(($) => $.attachment.overview)}
+ shortcut="G"
+ onClick={onOpenOverview}
+ >
+ <LayoutGrid className="size-4" />
+ </ChromeButton>
+ )}
+ {info && (
+ <ChromeButton
+ label={t(($) => $.attachment.info)}
+ shortcut="I"
+ pressed={info.open}
+ onClick={info.onToggle}
+ >
+ <PanelRight className="size-4" />
+ </ChromeButton>
+ )}
<ChromeDivider />
<ChromeButton label={t(($) => $.attachment.close)} onClick={onClose}>
<X className="size-4" />
</ChromeButton>
</div>
</header>
- {/* The stage. In a sequence its sides are 64px gutters holding the
- prev / next buttons, so a fitted image or a page never runs under
- them. */}
- <motion.div
- className={cn(
- "relative min-h-0 flex-1",
- sequence ? "px-16" : "px-4",
- )}
- onClick={closeOnBackdrop}
- initial={{ transform: reduceMotion ? "scale(1)" : "scale(0.97)" }}
- animate={{
- transform: "scale(1)",
- transition: {
- duration: UI_MOTION_DURATION.standard,
- ease: UI_EASE_OUT,
- },
- }}
- >
- {kind === "image" ? (
- <ImagePreview
- state={state}
- mediaUrl={mediaUrl}
- canvas={canvas}
- natural={natural}
- onNaturalSize={handleNaturalSize}
- onError={imageLoadError}
- />
- ) : (
- <PreviewContent
- kind={kind}
- source={source}
- state={state}
- onDownload={onDownload}
- onBackdropClick={closeOnBackdrop}
- />
- )}
- {sequence && (
- <>
- <SequenceButton
- side="prev"
- label={t(($) => $.attachment.previous)}
- onClick={sequence.onPrev}
+ <div className="flex min-h-0 flex-1">
+ {/* The stage. In a sequence its sides are 64px gutters holding the
+ prev / next buttons, so a fitted image or a page never runs under
+ them. */}
+ <motion.div
+ className={cn(
+ "relative min-h-0 min-w-0 flex-1",
+ sequence ? "px-16" : "px-4",
+ )}
+ onClick={closeOnBackdrop}
+ initial={{ transform: reduceMotion ? "scale(1)" : "scale(0.97)" }}
+ animate={{
+ transform: "scale(1)",
+ transition: {
+ duration: UI_MOTION_DURATION.standard,
+ ease: UI_EASE_OUT,
+ },
+ }}
+ >
+ {kind === "image" ? (
+ <ImagePreview
+ state={state}
+ mediaUrl={mediaUrl}
+ canvas={canvas}
+ natural={natural}
+ onNaturalSize={handleNaturalSize}
+ onError={imageLoadError}
/>
- <SequenceButton
- side="next"
- label={t(($) => $.attachment.next)}
- onClick={sequence.onNext}
+ ) : (
+ <PreviewContent
+ kind={kind}
+ source={source}
+ state={state}
+ onDownload={onDownload}
+ onBackdropClick={closeOnBackdrop}
/>
- </>
+ )}
+ {sequence && (
+ <>
+ <SequenceButton
+ side="prev"
+ label={t(($) => $.attachment.previous)}
+ onClick={sequence.onPrev}
+ />
+ <SequenceButton
+ side="next"
+ label={t(($) => $.attachment.next)}
+ onClick={sequence.onNext}
+ />
+ </>
+ )}
+ </motion.div>
+ {info?.open && (
+ // A column beside the stage rather than a layer over it: the file
+ // re-fits into what is left instead of hiding under the panel.
+ <aside
+ className="dark w-80 max-w-[45vw] shrink-0 overflow-y-auto border-l border-border bg-background/40 text-foreground"
+ aria-label={t(($) => $.attachment.info)}
+ >
+ {info.content}
+ </aside>
)}
- </motion.div>
+ </div>
</>
);
}
@@ -762,19 +868,30 @@ function PreviewPanel({
// resolve to the dark set whatever the app theme is.
function ChromeButton({
label,
+ shortcut,
+ pressed,
onClick,
children,
}: {
label: string;
+ /** Single-key shortcut, shown in the tooltip and announced to AT. */
+ shortcut?: string;
+ /** Toggle buttons pass their state; plain actions leave it unset. */
+ pressed?: boolean;
onClick: () => void;
children: ReactNode;
}) {
return (
<button
type="button"
- className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={label}
+ className={cn(
+ "flex size-8 items-center justify-center rounded-md transition-colors hover:bg-secondary hover:text-foreground",
+ pressed ? "bg-secondary text-foreground" : "text-muted-foreground",
+ )}
+ title={shortcut ? `${label} (${shortcut})` : label}
aria-label={label}
+ aria-keyshortcuts={shortcut}
+ aria-pressed={pressed}
onClick={onClick}
>
{children}
@@ -1002,7 +1119,7 @@ function PreviewContent({
render={(text) => (
<div className="h-full pb-4">
<HtmlPreviewBody
- source={{ kind: "inline", html: text }}
+ html={text}
title={state.filename}
className="h-full w-full"
iframeClassName="rounded-lg border-0"
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
index 512e2d29d9..d1e4dfd1c6 100644
--- a/packages/views/editor/attachment.test.tsx
+++ b/packages/views/editor/attachment.test.tsx
@@ -789,21 +789,20 @@ describe("Attachment — image dispatch", () => {
});
describe("Attachment — html dispatch", () => {
- it("record html with attachmentId renders HtmlAttachmentPreview (no file-card chrome)", () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart</p>",
- originalContentType: "text/html",
- });
+ // An HTML file is a file (MUL-7649): the row opens it in the viewer, and
+ // nothing is fetched to embed it inline.
+ it("record html renders the file-card row, not an embedded preview", () => {
const att = makeRecord({
filename: "report.html",
content_type: "text/html",
url: "https://cdn.example.test/report.html",
});
renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
- // HtmlAttachmentPreview hides the filename row.
- expect(screen.queryByText("report.html")).toBeNull();
+ expect(screen.getByText("report.html")).toBeTruthy();
expect(screen.getByTitle("Preview")).toBeTruthy();
expect(screen.getByTitle("Download")).toBeTruthy();
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(getAttachmentTextContentMock).not.toHaveBeenCalled();
});
it("url-only html (no resolver match) falls back to AttachmentCard chrome", () => {
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index ce3f174879..c91fd84256 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -8,8 +8,12 @@
*
* - image → ImageAttachmentView (figure + hover toolbar + lightbox via
* the shared AttachmentPreviewModal)
- * - html → HtmlAttachmentPreview (inline iframe + hover toolbar)
- * - others → AttachmentCard (icon + filename + Eye/Download row)
+ * - others → AttachmentCard (icon + filename + Eye/Download row), or
+ * AttachmentFileCard in the card layout
+ *
+ * An HTML file is a file like any other (MUL-7649): it shows as a card and
+ * opens in the viewer. HTML meant to be read in place is written as a
+ * ```html block in the body, which renders as a dynamic block.
*
* Call sites:
* - extensions/file-card.tsx FileCardView (Tiptap NodeView)
@@ -29,6 +33,7 @@ import {
Maximize2,
Trash2,
} from "lucide-react";
+import type { ReactNode } from "react";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
@@ -44,9 +49,8 @@ import {
useResignedInlineMedia,
} from "./hooks/use-inline-media-url";
import { useDownloadAttachment } from "./use-download-attachment";
-import { AttachmentCard } from "./attachment-card";
-import { HtmlAttachmentPreview } from "./html-attachment-preview";
-import { getPreviewKind, type PreviewKind } from "./utils/preview";
+import { AttachmentCard, AttachmentFileCard } from "./attachment-card";
+import { canOpenPreview, getPreviewKind, type PreviewKind } from "./utils/preview";
import "./styles/attachment.css";
// ---------------------------------------------------------------------------
@@ -95,6 +99,15 @@ export interface AttachmentProps {
selected?: boolean;
/** Editor hint — wired to Tiptap deleteNode(). */
onDelete?: () => void;
+ /**
+ * "block" (default) renders each kind at full width, as a body renders it.
+ * "card" is the compact form a list of standalone attachments lays out: an
+ * image becomes a fixed-height tile, any other file a card. HTML keeps its
+ * embedded preview in both — the preview is the point of attaching it.
+ */
+ layout?: "block" | "card";
+ /** Card layout only — rendered after the file name, e.g. a version badge. */
+ badge?: ReactNode;
className?: string;
}
@@ -316,6 +329,8 @@ export function Attachment({
editable,
selected,
onDelete,
+ layout = "block",
+ badge,
className,
}: AttachmentProps) {
const { resolveAttachment, openByUrl } = useAttachmentDownloadResolver();
@@ -408,19 +423,25 @@ export function Attachment({
onView={openPreview}
onDownload={handleDownload}
onDelete={onDelete}
- className={className}
+ className={cn(layout === "card" && "image-tile", className)}
/>
{preview.modal}
</>
);
}
- if (kind === "html" && state.attachmentId && !state.uploading) {
+ if (layout === "card") {
return (
<>
- <HtmlAttachmentPreview
- attachmentId={state.attachmentId}
+ <AttachmentFileCard
filename={state.filename}
+ contentType={state.contentType}
+ sizeBytes={state.record?.size_bytes}
+ // Same gate as the row's Eye button: text kinds need the record.
+ canPreview={!!shareUrl && canOpenPreview(kind, !!state.attachmentId)}
+ canDownload={!!shareUrl || !!state.attachmentId}
+ uploading={state.uploading}
+ badge={badge}
onPreview={openPreview}
onDownload={handleDownload}
onDelete={editable ? onDelete : undefined}
diff --git a/packages/views/editor/code-block-iframe.tsx b/packages/views/editor/code-block-iframe.tsx
index 28d8e848e8..259ba13e1c 100644
--- a/packages/views/editor/code-block-iframe.tsx
+++ b/packages/views/editor/code-block-iframe.tsx
@@ -4,10 +4,10 @@
* Shared HTML preview iframe.
*
* Used by:
- * - InlineHtmlIframe inside AttachmentCard (HTML attachments inline preview)
+ * - HtmlPreviewBody (the attachment viewer's html kind)
* - CodeBlockView for fenced ```html blocks (editable Tiptap NodeView)
- * - HtmlBlockPreview for fenced ```html blocks (ReadonlyContent)
- * - AttachmentPreviewModal's full-screen HTML kind
+ * - HtmlBlockPreview for fenced ```html blocks (RichContent), which also
+ * listens to the size/error bridge in utils/html-block-document.ts
*
* Sandbox semantics:
* sandbox="allow-scripts" (NOT "allow-same-origin")
@@ -21,6 +21,7 @@
* the text body we fetched, never point iframe.src at the proxy URL.
*/
+import type { CSSProperties, Ref } from "react";
import { cn } from "@multica/ui/lib/utils";
interface CodeBlockIframeProps {
@@ -31,6 +32,9 @@ interface CodeBlockIframeProps {
className?: string;
/** Tailwind height token; defaults to h-[480px]. */
heightClassName?: string;
+ style?: CSSProperties;
+ ref?: Ref<HTMLIFrameElement>;
+ onLoad?: () => void;
}
export function CodeBlockIframe({
@@ -38,9 +42,13 @@ export function CodeBlockIframe({
title,
className,
heightClassName = "h-[480px]",
+ style,
+ ref,
+ onLoad,
}: CodeBlockIframeProps) {
return (
<iframe
+ ref={ref}
// srcDoc keeps the body in the parent's process but isolated to an
// opaque origin via sandbox. Critical that we never combine
// `allow-scripts` with `allow-same-origin` — that pairing defeats the
@@ -53,6 +61,8 @@ export function CodeBlockIframe({
heightClassName,
className,
)}
+ style={style}
+ onLoad={onLoad}
/>
);
}
diff --git a/packages/views/editor/dynamic-block.test.tsx b/packages/views/editor/dynamic-block.test.tsx
new file mode 100644
index 0000000000..38ca8f9b6c
--- /dev/null
+++ b/packages/views/editor/dynamic-block.test.tsx
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({ t: (select: (bundle: typeof editor) => string) => select(editor) }),
+ };
+});
+
+vi.mock("./code-block-static", () => ({
+ CodeBlockStatic: ({ body }: { body: string }) => <pre>{body}</pre>,
+}));
+
+const { copyTextMock } = vi.hoisted(() => ({ copyTextMock: vi.fn() }));
+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: copyTextMock }));
+
+import { DynamicBlock } from "./dynamic-block";
+
+afterEach(() => vi.restoreAllMocks());
+
+function renderBlock() {
+ return render(
+ <DynamicBlock
+ kind="html"
+ title="Latency"
+ source="<p>chart</p>"
+ preview={() => <div data-testid="content">chart</div>}
+ />,
+ );
+}
+
+describe("DynamicBlock", () => {
+ it("collapses content taller than 480px behind Show all", () => {
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(900);
+ const { container } = renderBlock();
+
+ const body = container.querySelector<HTMLElement>("[data-collapsed]");
+ expect(body).not.toBeNull();
+ expect(body!.style.maxHeight).toBe("480px");
+
+ fireEvent.click(screen.getByRole("button", { name: "Show all" }));
+ expect(container.querySelector("[data-collapsed]")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Show all" })).toBeNull();
+ });
+
+ it("leaves content that fits alone", () => {
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(300);
+ const { container } = renderBlock();
+ expect(container.querySelector("[data-collapsed]")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Show all" })).toBeNull();
+ });
+
+ it("copies the fence source", async () => {
+ copyTextMock.mockResolvedValue(true);
+ renderBlock();
+ fireEvent.click(screen.getByRole("button", { name: "Copy source" }));
+ await waitFor(() => expect(copyTextMock).toHaveBeenCalledWith("<p>chart</p>"));
+ });
+
+ it("has no fullscreen button unless the kind offers one", () => {
+ renderBlock();
+ expect(screen.queryByRole("button", { name: "Fullscreen" })).toBeNull();
+ });
+});
diff --git a/packages/views/editor/dynamic-block.tsx b/packages/views/editor/dynamic-block.tsx
new file mode 100644
index 0000000000..00df818214
--- /dev/null
+++ b/packages/views/editor/dynamic-block.tsx
@@ -0,0 +1,335 @@
+"use client";
+
+/**
+ * DynamicBlock — the frame shared by every fence that renders in place
+ * (MUL-7649): ```html previews and ```mermaid diagrams.
+ *
+ * A dynamic block is part of the message body. That is what separates it from
+ * an attachment, which is a file and shows as a card that opens the viewer. So
+ * the frame reads as content, not as a file: an always-visible title bar (kind
+ * icon, title, kind chip, Preview | Source, fullscreen, copy) over a body that
+ * takes its content's height, collapsed past DYNAMIC_BLOCK_COLLAPSE_AT_PX
+ * behind a fade and "Show all". Loading and error states live inside the same
+ * frame, so a block that fails never breaks the comment around it.
+ *
+ * The kinds supply only the preview; the frame owns the chrome, the source
+ * view and the error panel.
+ */
+
+import {
+ useCallback,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+ type Ref,
+} from "react";
+import {
+ AppWindow,
+ Check,
+ ChevronDown,
+ CodeXml,
+ Copy,
+ Maximize2,
+ TriangleAlert,
+ Workflow,
+} from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";
+import { Spinner } from "@multica/ui/components/ui/spinner";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+import { CodeBlockStatic } from "./code-block-static";
+
+export type DynamicBlockKind = "html" | "mermaid";
+
+/** Content taller than this is collapsed until the reader asks for all of it. */
+export const DYNAMIC_BLOCK_COLLAPSE_AT_PX = 480;
+/** Floor for a preview body, so a loading or near-empty block keeps a shape. */
+export const DYNAMIC_BLOCK_MIN_BODY_PX = 120;
+/** Title bar (36px) plus the frame's top and bottom borders. */
+export const DYNAMIC_BLOCK_CHROME_PX = 38;
+
+// Kind names are identifiers (the fence language), not translatable copy.
+const KIND_LABEL: Record<DynamicBlockKind, string> = {
+ html: "HTML",
+ mermaid: "Mermaid",
+};
+
+const KIND_ICON: Record<DynamicBlockKind, typeof AppWindow> = {
+ html: AppWindow,
+ mermaid: Workflow,
+};
+
+// Highlighting language for the source view. Mermaid has no lowlight grammar.
+const SOURCE_LANGUAGE: Record<DynamicBlockKind, string | undefined> = {
+ html: "xml",
+ mermaid: undefined,
+};
+
+export interface DynamicBlockError {
+ message: string;
+ /** 1-based source line, when the error carries one. */
+ line?: number;
+}
+
+type DynamicBlockView = "preview" | "source";
+
+interface DynamicBlockProps {
+ kind: DynamicBlockKind;
+ /** From the fence info string (```html title="…"). Falls back to the kind name. */
+ title?: string | null;
+ /** The fence body: shown in the source view and copied by the copy button. */
+ source: string;
+ error?: DynamicBlockError | null;
+ /** Shows the fullscreen button when set. */
+ onFullscreen?: () => void;
+ /** Focus returns here when the kind's fullscreen surface closes. */
+ fullscreenButtonRef?: Ref<HTMLButtonElement>;
+ /**
+ * The rendered content. It stays mounted while the source view is showing,
+ * so switching back is instant; `active` says whether it is on screen.
+ */
+ preview: (options: { active: boolean }) => ReactNode;
+ className?: string;
+}
+
+export function DynamicBlock({
+ kind,
+ title,
+ source,
+ error,
+ onFullscreen,
+ fullscreenButtonRef,
+ preview,
+ className,
+}: DynamicBlockProps) {
+ const { t } = useT("editor");
+ const [view, setView] = useState<DynamicBlockView>("preview");
+ const [copied, setCopied] = useState(false);
+ const Icon = KIND_ICON[kind];
+ const kindLabel = KIND_LABEL[kind];
+ const trimmedTitle = title?.trim();
+
+ const handleCopy = async () => {
+ if (await copyText(source)) {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+
+ return (
+ <Tabs
+ value={view}
+ onValueChange={(value) => setView(value as DynamicBlockView)}
+ data-dynamic-block={kind}
+ className={cn(
+ "my-3 gap-0 overflow-hidden rounded-lg border bg-surface shadow-[var(--surface-shadow)]",
+ error && view === "preview" && "border-destructive/35",
+ className,
+ )}
+ >
+ <div className="flex h-9 items-center gap-2 border-b pr-1.5 pl-3">
+ <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ {/* With no title, the kind name stands in and the chip would repeat it. */}
+ <span
+ className={cn(
+ "min-w-0 truncate text-label font-medium",
+ !trimmedTitle && "text-muted-foreground",
+ )}
+ >
+ {trimmedTitle || kindLabel}
+ </span>
+ {trimmedTitle && (
+ <span className="inline-flex h-[18px] shrink-0 items-center rounded-sm bg-secondary px-1.5 text-micro text-muted-foreground">
+ {kindLabel}
+ </span>
+ )}
+ <span className="flex-1" />
+ <TabsList
+ aria-label={t(($) => $.dynamic_block.view)}
+ className="mr-1 shrink-0 gap-0.5 rounded-md p-0.5 group-data-horizontal/tabs:h-[26px]"
+ >
+ <TabsTrigger value="preview" className="rounded-sm px-2 text-caption">
+ {t(($) => $.dynamic_block.preview)}
+ </TabsTrigger>
+ <TabsTrigger value="source" className="rounded-sm px-2 text-caption">
+ {t(($) => $.dynamic_block.source)}
+ </TabsTrigger>
+ </TabsList>
+ {onFullscreen && (
+ <Button
+ ref={fullscreenButtonRef}
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-muted-foreground"
+ onClick={onFullscreen}
+ title={t(($) => $.code_block.fullscreen)}
+ aria-label={t(($) => $.code_block.fullscreen)}
+ >
+ <Maximize2 />
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-muted-foreground"
+ onClick={handleCopy}
+ title={t(($) => $.dynamic_block.copy_source)}
+ aria-label={t(($) => $.dynamic_block.copy_source)}
+ >
+ {copied ? <Check /> : <Copy />}
+ </Button>
+ </div>
+ <TabsContent value="preview" keepMounted>
+ {error && (
+ <DynamicBlockErrorPanel
+ kind={kind}
+ error={error}
+ onViewSource={() => setView("source")}
+ />
+ )}
+ <div hidden={!!error}>
+ <CollapsibleBody>{preview({ active: view === "preview" && !error })}</CollapsibleBody>
+ </div>
+ </TabsContent>
+ <TabsContent value="source">
+ <CollapsibleBody>
+ <CodeBlockStatic
+ language={SOURCE_LANGUAGE[kind]}
+ body={source}
+ className="!m-0 !rounded-none !bg-muted"
+ />
+ </CollapsibleBody>
+ </TabsContent>
+ </Tabs>
+ );
+}
+
+/**
+ * Takes its content's height, collapsed past DYNAMIC_BLOCK_COLLAPSE_AT_PX
+ * with a fade and "Show all". The content keeps laying out at full height
+ * underneath, so expanding only lifts the clip — an HTML preview or diagram
+ * is not rebuilt.
+ */
+function CollapsibleBody({ children }: { children: ReactNode }) {
+ const { t } = useT("editor");
+ const contentRef = useRef<HTMLDivElement>(null);
+ const [contentHeight, setContentHeight] = useState(0);
+ const [expanded, setExpanded] = useState(false);
+
+ const measure = useCallback(() => {
+ const el = contentRef.current;
+ if (el) setContentHeight(el.offsetHeight);
+ }, []);
+
+ useLayoutEffect(() => {
+ const el = contentRef.current;
+ if (!el) return;
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [measure]);
+
+ const collapsed = !expanded && contentHeight > DYNAMIC_BLOCK_COLLAPSE_AT_PX;
+
+ return (
+ <div
+ className="relative overflow-hidden"
+ data-collapsed={collapsed ? "" : undefined}
+ style={collapsed ? { maxHeight: DYNAMIC_BLOCK_COLLAPSE_AT_PX } : undefined}
+ >
+ <div ref={contentRef}>{children}</div>
+ {collapsed && (
+ <>
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-24 bg-gradient-to-b from-transparent to-surface" />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full bg-surface shadow-[var(--surface-shadow)]"
+ onClick={() => setExpanded(true)}
+ >
+ <ChevronDown />
+ {t(($) => $.dynamic_block.show_all)}
+ </Button>
+ </>
+ )}
+ </div>
+ );
+}
+
+function DynamicBlockErrorPanel({
+ kind,
+ error,
+ onViewSource,
+}: {
+ kind: DynamicBlockKind;
+ error: DynamicBlockError;
+ onViewSource: () => void;
+}) {
+ const { t } = useT("editor");
+ const [copied, setCopied] = useState(false);
+ const detail = error.line
+ ? t(($) => $.dynamic_block.error_at_line, { message: error.message, line: error.line })
+ : error.message;
+
+ const handleCopyError = async () => {
+ if (await copyText(detail)) {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+
+ return (
+ <div role="alert" className="flex gap-3 p-5 text-label">
+ <TriangleAlert aria-hidden className="mt-0.5 size-4 shrink-0 text-destructive" />
+ <div className="min-w-0 flex-1">
+ <div className="font-semibold">
+ {kind === "html"
+ ? t(($) => $.dynamic_block.error_html)
+ : t(($) => $.dynamic_block.error_mermaid)}
+ </div>
+ {/* The parser or script message is the only clue about what to fix. */}
+ {detail && (
+ <div className="mt-0.5 font-mono text-caption break-words whitespace-pre-wrap text-muted-foreground">
+ {detail}
+ </div>
+ )}
+ <div className="mt-2.5 flex flex-wrap gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={onViewSource}>
+ <CodeXml />
+ {t(($) => $.dynamic_block.view_source)}
+ </Button>
+ <Button type="button" variant="outline" size="sm" onClick={handleCopyError}>
+ {copied ? <Check /> : <Copy />}
+ {t(($) => $.dynamic_block.copy_error)}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Loading state for a preview body: a quiet page outline at the height the
+ * block will most likely take, so the finished render does not move the page.
+ */
+export function DynamicBlockSkeleton({ className }: { className?: string }) {
+ const { t } = useT("editor");
+ return (
+ <div className={cn("flex h-full flex-col gap-3 px-5 py-[18px]", className)}>
+ <div className="h-3 w-[38%] rounded-sm bg-muted" />
+ <div className="min-h-3 flex-1 rounded-sm bg-muted" />
+ <div className="flex items-center gap-1.5 text-caption text-muted-foreground">
+ <Spinner aria-hidden className="size-3.5" />
+ {t(($) => $.dynamic_block.rendering)}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/editor/extensions/file-card.test.tsx b/packages/views/editor/extensions/file-card.test.tsx
index 232c16d372..aea4034e84 100644
--- a/packages/views/editor/extensions/file-card.test.tsx
+++ b/packages/views/editor/extensions/file-card.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import type { ReactElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -35,9 +35,9 @@ vi.mock("../attachment-preview-modal", () => ({
useAttachmentPreview: () => ({ tryOpen: tryOpenMock, open: vi.fn(), modal: null }),
}));
-// HtmlAttachmentPreview (the kind="html" route through AttachmentBlock) now
-// reads useNavigation() + useWorkspaceSlug() for its Open-in-new-tab button.
-// Provide minimal mocks so the component renders without a real provider.
+// The attachment renderer reads useNavigation() + useWorkspaceSlug() on some
+// paths. Provide minimal mocks so the component renders without a real
+// provider.
vi.mock("../../navigation", () => ({
useNavigation: () => ({
push: vi.fn(),
@@ -88,23 +88,17 @@ function renderWithQuery(ui: ReactElement) {
beforeEach(() => vi.clearAllMocks());
afterEach(() => vi.restoreAllMocks());
-describe("FileCardView — HTML attachment routes through AttachmentBlock to iframe", () => {
- // Regression pin for file-card.tsx:59. The NodeView must render through
- // <AttachmentBlock>, not the older <AttachmentCard>. If someone reverts that
- // line, the dispatcher's html+attachmentId branch is bypassed and the user
- // is left with the file-card chrome — exactly the bug MUL-2330 surfaced.
- it("renders an iframe (no file-card chrome) when the node resolves to an HTML attachment", async () => {
+describe("FileCardView — HTML attachment", () => {
+ // Reverses the MUL-2330 pin: an HTML file is a file (MUL-7649), shown as the
+ // file-card row that opens the viewer. HTML meant to be read in place is a
+ // ```html block.
+ it("renders the file-card row, not an embedded preview, for an HTML attachment", () => {
resolveAttachmentMock.mockReturnValue({
id: "att-1",
content_type: "text/html",
url: "/uploads/report.html",
filename: "report.html",
});
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart</p>",
- originalContentType: "text/html",
- });
-
const node = {
attrs: {
href: "/uploads/report.html",
@@ -115,16 +109,8 @@ describe("FileCardView — HTML attachment routes through AttachmentBlock to ifr
renderWithQuery(<FileCardView node={node} {...({} as any)} />);
- const frame = await waitFor(() => {
- const f = document.querySelector("iframe") as HTMLIFrameElement | null;
- expect(f).toBeTruthy();
- return f!;
- });
- expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
- expect(frame.getAttribute("srcdoc")).toContain("<p>chart</p>");
- // The AttachmentCard chrome surfaces the filename as text inside its row.
- // HtmlAttachmentPreview replaces the chrome entirely, so the filename
- // must not appear as visible text.
- expect(screen.queryByText("report.html")).toBeNull();
+ expect(screen.getByText("report.html")).toBeTruthy();
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(getAttachmentTextContentMock).not.toHaveBeenCalled();
});
});
diff --git a/packages/views/editor/hooks/use-theme-version.ts b/packages/views/editor/hooks/use-theme-version.ts
new file mode 100644
index 0000000000..406af699b6
--- /dev/null
+++ b/packages/views/editor/hooks/use-theme-version.ts
@@ -0,0 +1,37 @@
+import { useEffect, useState } from "react";
+
+/**
+ * A counter that bumps whenever the app theme may have changed: a class,
+ * style or data-theme change on <html>/<body>, or the OS color scheme.
+ *
+ * Sandboxed blocks copy resolved theme colors into their iframe document, so
+ * they cannot follow a theme switch through CSS; they rebuild when this bumps.
+ */
+export function useThemeVersion(): number {
+ const [themeVersion, setThemeVersion] = useState(0);
+
+ useEffect(() => {
+ const bumpThemeVersion = () => setThemeVersion((version) => version + 1);
+ const observer = new MutationObserver(bumpThemeVersion);
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ["class", "style", "data-theme"],
+ });
+ if (document.body) {
+ observer.observe(document.body, {
+ attributes: true,
+ attributeFilter: ["class", "style", "data-theme"],
+ });
+ }
+
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
+ mediaQuery.addEventListener("change", bumpThemeVersion);
+
+ return () => {
+ observer.disconnect();
+ mediaQuery.removeEventListener("change", bumpThemeVersion);
+ };
+ }, []);
+
+ return themeVersion;
+}
diff --git a/packages/views/editor/hooks/use-zoom-canvas.ts b/packages/views/editor/hooks/use-zoom-canvas.ts
index 4212a84950..298fdf43cc 100644
--- a/packages/views/editor/hooks/use-zoom-canvas.ts
+++ b/packages/views/editor/hooks/use-zoom-canvas.ts
@@ -36,6 +36,7 @@ import {
distanceBetween,
midpointOf,
panBy,
+ resizeTransform,
wheelZoomFactor,
zoomByAtCenter,
zoomToAt,
@@ -154,9 +155,9 @@ export function useZoomCanvas({
}, [viewportNode]);
// Fit once, on first open — a layout effect, so the first painted frame is
- // already fitted. Deliberately not re-fitting on later viewport changes: a
- // theme switch re-renders the content at the same size, and silently
- // snapping the user's zoom back to fit would lose their place.
+ // already fitted. Later viewport changes never snap a zoom the user chose
+ // back to fit (that would lose their place); only a view still at fit
+ // follows a resize, below.
useLayoutEffect(() => {
if (!ready || hasFittedRef.current) return;
hasFittedRef.current = true;
@@ -179,10 +180,16 @@ export function useZoomCanvas({
setTransform(computeFitTransform(contentSize, viewport));
}, [contentKey, ready, contentSize, viewport]);
- // Keep the content in view when the window/pane is resized under it.
+ // Keep the content in view when the window/pane is resized under it — and
+ // keep a still-fitted image fitted (see `resizeTransform`).
+ const previousViewportRef = useRef(viewport);
useEffect(() => {
+ const previous = previousViewportRef.current;
+ previousViewportRef.current = viewport;
if (!ready) return;
- setTransform((current) => clampTransform(current, contentSize, viewport));
+ setTransform((current) =>
+ resizeTransform(current, contentSize, previous, viewport),
+ );
}, [ready, contentSize, viewport]);
const fit = useCallback(() => {
diff --git a/packages/views/editor/html-attachment-preview.test.tsx b/packages/views/editor/html-attachment-preview.test.tsx
deleted file mode 100644
index 1df4ac629d..0000000000
--- a/packages/views/editor/html-attachment-preview.test.tsx
+++ /dev/null
@@ -1,278 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import type { ReactElement } from "react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
-const { getAttachmentTextContentMock } = vi.hoisted(() => ({
- getAttachmentTextContentMock: vi.fn(),
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: { getAttachmentTextContent: getAttachmentTextContentMock },
- PreviewTooLargeError: class extends Error {},
- PreviewUnsupportedError: class extends Error {},
-}));
-
-vi.mock("../i18n", () => ({
- useT: () => ({
- t: (sel: (s: Record<string, Record<string, string>>) => string) =>
- sel({
- image: { download: "Download" },
- attachment: {
- preview: "Preview",
- preview_loading: "Loading preview…",
- preview_failed: "Couldn't load preview",
- open_in_new_tab: "Open in new tab",
- },
- }),
- }),
-}));
-
-// Module-level flag toggled per-test to simulate desktop (openInNewTab
-// present) vs web (omitted) adapters. vi.hoisted so the mock factory can
-// close over it.
-const { openInNewTabMock, getShareableUrlMock, navState } = vi.hoisted(() => ({
- openInNewTabMock: vi.fn(),
- getShareableUrlMock: vi.fn((p: string) => `https://app.example${p}`),
- navState: { hasOpenInNewTab: true },
-}));
-
-vi.mock("../navigation", () => ({
- useNavigation: () => ({
- push: vi.fn(),
- replace: vi.fn(),
- back: vi.fn(),
- pathname: "/acme/issues",
- searchParams: new URLSearchParams(),
- hash: "",
- ...(navState.hasOpenInNewTab ? { openInNewTab: openInNewTabMock } : {}),
- getShareableUrl: getShareableUrlMock,
- }),
-}));
-
-// Slug is required for the new-tab path to be built. The component reads
-// it from useWorkspaceSlug() on @multica/core/paths — stub to return a
-// fixed slug so the tests do not need a WorkspaceSlugProvider tree.
-vi.mock("@multica/core/paths", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@multica/core/paths")>();
- return {
- ...actual,
- useWorkspaceSlug: () => "acme",
- useWorkspacePaths: () => actual.paths.workspace("acme"),
- };
-});
-
-import { HtmlAttachmentPreview } from "./html-attachment-preview";
-
-function renderWithQuery(ui: ReactElement) {
- const qc = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
- return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- navState.hasOpenInNewTab = true;
-});
-afterEach(() => vi.restoreAllMocks());
-
-describe("HtmlAttachmentPreview — visual shell (does not use file-card chrome)", () => {
- it("does not render the filename row that AttachmentCard chrome would render", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- await waitFor(() => {
- expect(document.querySelector("iframe")).toBeTruthy();
- });
- // The chrome row would surface the filename as text; we replace that
- // entirely with an iframe + floating toolbar.
- expect(screen.queryByText("report.html")).toBeNull();
- });
-
- it("renders iframe with sandbox='allow-scripts' and srcdoc when text loads", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart goes here</p>",
- originalContentType: "text/html",
- });
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- await waitFor(() => {
- const frame = document.querySelector("iframe") as HTMLIFrameElement | null;
- expect(frame).toBeTruthy();
- // Critical: sandbox must not include allow-same-origin, otherwise the
- // sandbox is defeated per the HTML spec.
- expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
- // srcdoc carries the original HTML plus the fragment-nav shim
- // appended at the end (see utils/iframe-fragment-nav.ts).
- const srcdoc = frame?.getAttribute("srcdoc") ?? "";
- expect(srcdoc.startsWith("<p>chart goes here</p>")).toBe(true);
- expect(srcdoc).toContain("scrollIntoView");
- });
- });
-});
-
-describe("HtmlAttachmentPreview — toolbar actions", () => {
- it("invokes onPreview when Maximize is clicked", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- const onPreview = vi.fn();
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={onPreview}
- onDownload={() => {}}
- />,
- );
- await waitFor(() => expect(screen.getByTitle("Preview")).toBeTruthy());
- fireEvent.mouseDown(screen.getByTitle("Preview"));
- expect(onPreview).toHaveBeenCalled();
- });
-
- it("invokes onDownload when Download is clicked", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- const onDownload = vi.fn();
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={onDownload}
- />,
- );
- await waitFor(() => expect(screen.getByTitle("Download")).toBeTruthy());
- fireEvent.mouseDown(screen.getByTitle("Download"));
- expect(onDownload).toHaveBeenCalled();
- });
-
- it("does not render a Copy code button — attachments are files, not source snippets", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- await waitFor(() => expect(document.querySelector("iframe")).toBeTruthy());
- expect(screen.queryByTitle("Copy code")).toBeNull();
- });
-
- it("invokes navigation.openInNewTab with the preview path when available (desktop)", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- await waitFor(() =>
- expect(screen.getByTitle("Open in new tab")).toBeTruthy(),
- );
- fireEvent.mouseDown(screen.getByTitle("Open in new tab"));
- expect(openInNewTabMock).toHaveBeenCalledWith(
- "/acme/attachments/att-1/preview?name=report.html",
- "report.html",
- { activate: true },
- );
- });
-
- it("falls back to window.open against the shareable URL when openInNewTab is absent (web)", async () => {
- navState.hasOpenInNewTab = false;
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>ok</p>",
- originalContentType: "text/html",
- });
- const windowOpenSpy = vi
- .spyOn(window, "open")
- .mockImplementation(() => null);
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- await waitFor(() =>
- expect(screen.getByTitle("Open in new tab")).toBeTruthy(),
- );
- fireEvent.mouseDown(screen.getByTitle("Open in new tab"));
- expect(openInNewTabMock).not.toHaveBeenCalled();
- expect(windowOpenSpy).toHaveBeenCalledWith(
- "https://app.example/acme/attachments/att-1/preview?name=report.html",
- "_blank",
- "noopener,noreferrer",
- );
- });
-});
-
-describe("HtmlAttachmentPreview — failure mode does not unmount the toolbar", () => {
- it("keeps Preview and Download enabled when fetch errors", async () => {
- getAttachmentTextContentMock.mockRejectedValueOnce(new Error("nope"));
- const onPreview = vi.fn();
- const onDownload = vi.fn();
- renderWithQuery(
- <HtmlAttachmentPreview
- attachmentId="att-1"
- filename="report.html"
- onPreview={onPreview}
- onDownload={onDownload}
- />,
- );
- // Wait for the error placeholder — guarantees the query has settled.
- await waitFor(() => {
- expect(
- screen.getByTestId("html-attachment-preview-error"),
- ).toBeTruthy();
- });
- // Critical: the figure does NOT collapse, and the chrome row is NOT
- // rendered as a fallback. Preview and Download stay reachable.
- expect(document.querySelector("iframe")).toBeNull();
- expect(screen.queryByText("report.html")).toBeNull();
-
- const previewBtn = screen.getByTitle("Preview") as HTMLButtonElement;
- const downloadBtn = screen.getByTitle("Download") as HTMLButtonElement;
- const openInNewTabBtn = screen.getByTitle(
- "Open in new tab",
- ) as HTMLButtonElement;
- expect(previewBtn.disabled).toBe(false);
- expect(downloadBtn.disabled).toBe(false);
- expect(openInNewTabBtn.disabled).toBe(false);
-
- fireEvent.mouseDown(previewBtn);
- expect(onPreview).toHaveBeenCalled();
- fireEvent.mouseDown(downloadBtn);
- expect(onDownload).toHaveBeenCalled();
- });
-});
diff --git a/packages/views/editor/html-attachment-preview.tsx b/packages/views/editor/html-attachment-preview.tsx
deleted file mode 100644
index 1cada423c6..0000000000
--- a/packages/views/editor/html-attachment-preview.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-"use client";
-
-/**
- * HtmlAttachmentPreview — inline HTML attachment renderer.
- *
- * Visual model mirrors the image renderer: the iframe body is the card, and a
- * floating right-top toolbar reveals on hover with Preview (full-screen modal)
- * / Open-in-new-tab / Download. No file-card chrome (icon + filename row).
- *
- * No "Copy code" button: this is a FILE, not an inline source snippet. The
- * inline ```html``` fenced block (HtmlBlockPreview) is the surface for reading
- * / copying HTML source; an attachment's contract is view + download.
- *
- * Open-in-new-tab routes to `/{slug}/attachments/{id}/preview` — desktop uses
- * `openInNewTab` to add an app tab; web falls back to `window.open` against
- * the shareable URL.
- *
- * Mounted by the unified `<Attachment>` dispatcher when the attachment is
- * HTML and an `attachmentId` is resolvable (the /content proxy is ID-keyed).
- * For other kinds, `<Attachment>` falls back to the shared AttachmentCard.
- *
- * Failure mode (413 / 415 / transport): we do not unmount the figure or fall
- * back to AttachmentCard chrome — standalone attachment lists filter URLs
- * already inlined in the markdown body, so a silent unmount would remove the
- * user's only Preview/Download entry point. Instead the body collapses to an
- * 80px placeholder and the toolbar pins itself open with all actions enabled.
- */
-
-import { Download, ExternalLink, Maximize2, Trash2 } from "lucide-react";
-import { cn } from "@multica/ui/lib/utils";
-import { paths, useWorkspaceSlug } from "@multica/core/paths";
-import { useT } from "../i18n";
-import { useNavigation } from "../navigation";
-import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";
-import { HtmlPreviewBody } from "./html-preview-body";
-
-const PREVIEW_HEIGHT = "h-[480px]";
-const ERROR_PLACEHOLDER_HEIGHT = "h-20";
-
-interface HtmlAttachmentPreviewProps {
- attachmentId: string;
- filename: string;
- onPreview: () => void;
- onDownload: () => void;
- onDelete?: () => void;
-}
-
-export function HtmlAttachmentPreview({
- attachmentId,
- filename,
- onPreview,
- onDownload,
- onDelete,
-}: HtmlAttachmentPreviewProps) {
- const { t } = useT("editor");
- // Subscribe to the same React Query cache key the body consumes so the
- // toolbar can pin itself open during error. Re-subscribing is free — the
- // useQuery dedupe means no extra fetch.
- const query = useAttachmentHtmlText(attachmentId);
- const isError = !query.isLoading && (!!query.error || !query.data?.text);
- // useWorkspaceSlug — NOT useWorkspacePaths. The Paths-bound variant throws
- // when there's no slug; we want to render gracefully (just hide the
- // new-tab button) when the component is somehow mounted outside a
- // workspace route.
- const slug = useWorkspaceSlug();
- const navigation = useNavigation();
-
- // Only enable the new-tab button when the workspace slug is resolvable —
- // outside a workspace context the path is meaningless. Prefer desktop's
- // tab system; on web fall back to window.open against the public shareable
- // URL (auth is handled by the cookie session on the new page).
- const canOpenInNewTab = !!slug && !!attachmentId;
- const handleOpenInNewTab = () => {
- if (!slug) return;
- const nameQuery = filename ? `?name=${encodeURIComponent(filename)}` : "";
- const path = `${paths.workspace(slug).attachmentPreview(attachmentId)}${nameQuery}`;
- if (navigation.openInNewTab) {
- navigation.openInNewTab(path, filename, { activate: true });
- return;
- }
- const url = navigation.getShareableUrl(path);
- window.open(url, "_blank", "noopener,noreferrer");
- };
-
- return (
- <div
- className="group/html-preview relative my-1"
- onMouseDown={(e) => e.stopPropagation()}
- >
- <HtmlPreviewBody
- source={{ kind: "attachment", attachmentId }}
- title={filename}
- className={PREVIEW_HEIGHT}
- placeholderClassName={isError ? ERROR_PLACEHOLDER_HEIGHT : PREVIEW_HEIGHT}
- errorTestId="html-attachment-preview-error"
- />
- <div
- className={cn(
- "absolute right-2 top-2 flex items-center gap-0.5 rounded-md border border-border bg-background/95 p-0.5 shadow-sm transition-opacity",
- // Error state pins the toolbar open — Preview / Download are the
- // only user-reachable escape hatches when inline render fails.
- isError
- ? "opacity-100"
- : "opacity-0 group-hover/html-preview:opacity-100",
- )}
- >
- <button
- type="button"
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- title={t(($) => $.attachment.preview)}
- aria-label={t(($) => $.attachment.preview)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onPreview();
- }}
- >
- <Maximize2 className="h-3.5 w-3.5" />
- </button>
- {canOpenInNewTab && (
- <button
- type="button"
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- title={t(($) => $.attachment.open_in_new_tab)}
- aria-label={t(($) => $.attachment.open_in_new_tab)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- handleOpenInNewTab();
- }}
- >
- <ExternalLink className="h-3.5 w-3.5" />
- </button>
- )}
- <button
- type="button"
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- title={t(($) => $.image.download)}
- aria-label={t(($) => $.image.download)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onDownload();
- }}
- >
- <Download className="h-3.5 w-3.5" />
- </button>
- {onDelete && (
- <button
- type="button"
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
- title={t(($) => $.attachment.remove)}
- aria-label={t(($) => $.attachment.remove)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onDelete();
- }}
- >
- <Trash2 className="h-3.5 w-3.5" />
- </button>
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/views/editor/html-block-preview.test.tsx b/packages/views/editor/html-block-preview.test.tsx
index 3ba772de97..e72b4b77e0 100644
--- a/packages/views/editor/html-block-preview.test.tsx
+++ b/packages/views/editor/html-block-preview.test.tsx
@@ -1,20 +1,15 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
-
-vi.mock("../i18n", () => ({
- useT: () => ({
- t: (sel: (s: Record<string, Record<string, string>>) => string) =>
- sel({
- code_block: {
- html_preview: "Localized HTML preview",
- copy_code: "Copy code",
- show_preview: "Show preview",
- show_source: "Show source",
- fullscreen: "Fullscreen",
- },
- }),
- }),
-}));
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+
+vi.mock("../i18n", async () => {
+ const editor = (await import("../locales/en/editor.json")).default;
+ return {
+ useT: () => ({
+ t: (select: (bundle: typeof editor) => string, values?: Record<string, unknown>) =>
+ select(editor).replace(/\{\{(\w+)\}\}/g, (_, key: string) => String(values?.[key] ?? "")),
+ }),
+ };
+});
// CodeBlockStatic depends on lowlight which has a heavy import surface and a
// jsdom-incompatible code path. Stub to keep the source-view test focused on
@@ -26,66 +21,142 @@ vi.mock("./code-block-static", () => ({
}));
import { HtmlBlockPreview } from "./html-block-preview";
+import { HTML_BLOCK_MESSAGE_KEY } from "./utils/html-block-document";
+beforeEach(() => window.sessionStorage.clear());
afterEach(() => vi.restoreAllMocks());
-describe("HtmlBlockPreview — preview / source toggle", () => {
- it("renders the iframe with sandbox and the fragment-nav shim in srcdoc", () => {
+function inlineFrame(): HTMLIFrameElement {
+ const frame = document.querySelector<HTMLIFrameElement>('[data-dynamic-block="html"] iframe');
+ expect(frame).not.toBeNull();
+ return frame!;
+}
+
+/** What the bridge inside the sandbox posts to the page. */
+function post(frame: HTMLIFrameElement, data: Record<string, unknown>) {
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { [HTML_BLOCK_MESSAGE_KEY]: 1, ...data },
+ source: frame.contentWindow,
+ }),
+ );
+ });
+}
+
+describe("HtmlBlockPreview — frame", () => {
+ it("shows an always-visible title bar with the fence title and kind", () => {
+ render(<HtmlBlockPreview html="<p>hi</p>" title="Weekly p95" />);
+ expect(screen.getByText("Weekly p95")).toBeTruthy();
+ expect(screen.getByText("HTML")).toBeTruthy();
+ expect(screen.getByRole("tab", { name: "Preview" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Fullscreen" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Copy source" })).toBeTruthy();
+ });
+
+ it("names the block after its kind when the fence has no title", () => {
render(<HtmlBlockPreview html="<p>hi</p>" />);
- // Two iframes exist after mount — the inline 480px one and the
- // (hidden) Dialog one. Both carry the same srcdoc.
- const frames = document.querySelectorAll("iframe");
- expect(frames.length).toBeGreaterThanOrEqual(1);
- const frame = frames[0]!;
- expect(frame.getAttribute("title")).toBe("Localized HTML preview");
+ expect(screen.getAllByText("HTML")).toHaveLength(1);
+ });
+
+ it("renders the HTML in a scripts-only sandbox with the theme, bridge and fragment shim", () => {
+ render(<HtmlBlockPreview html="<p>hi</p>" />);
+ const frame = inlineFrame();
+ expect(frame.getAttribute("title")).toBe("HTML preview");
expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
const srcdoc = frame.getAttribute("srcdoc") ?? "";
- expect(srcdoc.startsWith("<p>hi</p>")).toBe(true);
+ expect(srcdoc.startsWith("<style>:root{")).toBe(true);
+ expect(srcdoc).toContain(HTML_BLOCK_MESSAGE_KEY);
+ expect(srcdoc).toContain("<p>hi</p>");
expect(srcdoc).toContain("scrollIntoView");
});
- it("switches to source view and back when the toggle is clicked", () => {
+ it("switches to source in the same frame and keeps the preview mounted", () => {
render(<HtmlBlockPreview html="<p>hi</p>" />);
- // Preview mode: iframe present, code-block-static absent.
- expect(document.querySelector("iframe")).toBeTruthy();
- expect(screen.queryByTestId("code-block-static")).toBeNull();
+ const frame = inlineFrame();
- fireEvent.click(screen.getByTitle("Show source"));
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
expect(screen.getByTestId("code-block-static").textContent).toBe("<p>hi</p>");
- // The inline iframe is gone in source mode; the Dialog's iframe stays
- // unmounted because the Dialog is closed.
- expect(document.querySelector("iframe")).toBeNull();
+ // Hidden, not torn down: going back must not rerun the document.
+ expect(frame.isConnected).toBe(true);
- fireEvent.click(screen.getByTitle("Show preview"));
- expect(document.querySelector("iframe")).toBeTruthy();
+ fireEvent.click(screen.getByRole("tab", { name: "Preview" }));
+ expect(inlineFrame()).toBe(frame);
expect(screen.queryByTestId("code-block-static")).toBeNull();
});
});
-describe("HtmlBlockPreview — Maximize → Dialog", () => {
- it("does not render the Fullscreen button in source view (only when iframe is visible)", () => {
+describe("HtmlBlockPreview — height", () => {
+ const body = (frame: HTMLIFrameElement) => frame.parentElement as HTMLElement;
+
+ it("shows a loading skeleton until the document reports, then takes its height", () => {
render(<HtmlBlockPreview html="<p>hi</p>" />);
- expect(screen.getByTitle("Fullscreen")).toBeTruthy();
- fireEvent.click(screen.getByTitle("Show source"));
- expect(screen.queryByTitle("Fullscreen")).toBeNull();
+ const frame = inlineFrame();
+ expect(screen.getByText("Rendering...")).toBeTruthy();
+ expect(frame.className).toContain("invisible");
+
+ post(frame, { type: "height", height: 264 });
+ expect(body(frame).style.height).toBe("264px");
+ expect(screen.queryByText("Rendering...")).toBeNull();
+ expect(frame.className).not.toContain("invisible");
+ });
+
+ it("never goes below the minimum body height", () => {
+ render(<HtmlBlockPreview html="<p>hi</p>" />);
+ const frame = inlineFrame();
+ post(frame, { type: "height", height: 30 });
+ expect(body(frame).style.height).toBe("120px");
+ });
+
+ it("ignores messages that do not come from its own frame", () => {
+ render(<HtmlBlockPreview html="<p>hi</p>" />);
+ const frame = inlineFrame();
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { [HTML_BLOCK_MESSAGE_KEY]: 1, type: "height", height: 400 },
+ source: window,
+ }),
+ );
+ });
+ expect(screen.getByText("Rendering...")).toBeTruthy();
+ expect(body(frame).style.height).toBe("120px");
+ });
+
+ it("starts from the height this HTML had earlier in the session", () => {
+ const first = render(<HtmlBlockPreview html="<p>chart</p>" />);
+ post(inlineFrame(), { type: "height", height: 300 });
+ first.unmount();
+
+ render(<HtmlBlockPreview html="<p>chart</p>" />);
+ expect(body(inlineFrame()).style.height).toBe("300px");
+ });
+});
+
+describe("HtmlBlockPreview — errors", () => {
+ it("explains a script error in place and offers the source", () => {
+ render(<HtmlBlockPreview html="<script>boom()</script>" />);
+ post(inlineFrame(), { type: "error", message: "ReferenceError: boom is not defined", line: 1 });
+
+ const alert = screen.getByRole("alert");
+ expect(alert.textContent).toContain("The preview hit a script error");
+ expect(alert.textContent).toContain("ReferenceError: boom is not defined (line 1)");
+
+ fireEvent.click(screen.getByRole("button", { name: "View source" }));
+ expect(screen.getByTestId("code-block-static").textContent).toBe("<script>boom()</script>");
});
+});
- it("opens the fullscreen Dialog with a second iframe carrying the same srcdoc", () => {
+describe("HtmlBlockPreview — fullscreen", () => {
+ it("opens the same document in a dialog", () => {
render(<HtmlBlockPreview html="<p>hi</p>" />);
- // Before clicking Fullscreen, the Dialog has not mounted its content
- // (base-ui dialog renders Popup lazily).
- expect(document.querySelectorAll("iframe").length).toBe(1);
+ expect(document.querySelectorAll("iframe")).toHaveLength(1);
- fireEvent.click(screen.getByTitle("Fullscreen"));
+ fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
const frames = document.querySelectorAll("iframe");
- expect(frames.length).toBe(2);
- // Both iframes wrap the same body via the fragment-nav shim.
- for (const f of frames) {
- const srcdoc = f.getAttribute("srcdoc") ?? "";
- expect(srcdoc.startsWith("<p>hi</p>")).toBe(true);
- expect(srcdoc).toContain("scrollIntoView");
- expect(f.getAttribute("sandbox")).toBe("allow-scripts");
- }
+ expect(frames).toHaveLength(2);
+ expect(frames[1]!.getAttribute("srcdoc")).toBe(frames[0]!.getAttribute("srcdoc"));
+ expect(frames[1]!.getAttribute("sandbox")).toBe("allow-scripts");
});
});
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index 4726fbfd39..05120f7ad7 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -1,149 +1,245 @@
"use client";
/**
- * HtmlBlockPreview — readonly rendering of fenced ```html code blocks.
+ * HtmlBlockPreview — a fenced ```html block rendered in place (MUL-7649).
*
- * Default view is "preview" (iframe) per the V2 plan; user can flip to
- * "source" to see the highlighted markup and Copy it. Maximize opens the
- * same iframe in a full-screen Dialog.
+ * The HTML runs in a sandboxed iframe inside the shared DynamicBlock frame and
+ * takes its own content's height, reported by the bridge in
+ * utils/html-block-document.ts, instead of a fixed 480px that left short
+ * charts floating in blank space. An uncaught script error replaces the
+ * preview with an explanation; fullscreen still shows whatever did render.
*
- * Mounted by ReadonlyContent's `code` renderer for `lang === "html"`. The
- * `pre` renderer in ReadonlyContent recognizes this component by reference
- * and unwraps it from the default `<pre>` envelope, matching the same
- * two-layer trick already used for MermaidDiagram.
- *
- * NOT used in the editable Tiptap NodeView — that path must keep
+ * Reached through RichFenceBlock (rich-content/rich-code-block.tsx) for closed
+ * fences only. NOT used in the editable Tiptap NodeView — that path must keep
* `<NodeViewContent as="code" />` so the user can continue typing.
*/
-import { useState } from "react";
-import {
- Check,
- Code as CodeIcon,
- Copy,
- Eye,
- Maximize2,
-} from "lucide-react";
+import { useEffect, useReducer, useRef, useState } from "react";
import { cn } from "@multica/ui/lib/utils";
-import { copyText } from "@multica/ui/lib/clipboard";
-import {
- Dialog,
- DialogContent,
-} from "@multica/ui/components/ui/dialog";
+import { Dialog, DialogContent } from "@multica/ui/components/ui/dialog";
import { useT } from "../i18n";
-import { CodeBlockStatic } from "./code-block-static";
-import { HtmlPreviewBody } from "./html-preview-body";
+import { CodeBlockIframe } from "./code-block-iframe";
+import {
+ DYNAMIC_BLOCK_CHROME_PX,
+ DYNAMIC_BLOCK_COLLAPSE_AT_PX,
+ DYNAMIC_BLOCK_MIN_BODY_PX,
+ DynamicBlock,
+ DynamicBlockSkeleton,
+ type DynamicBlockError,
+} from "./dynamic-block";
+import { useThemeVersion } from "./hooks/use-theme-version";
+import {
+ INITIAL_HTML_BLOCK_HEIGHT,
+ buildHtmlBlockDocument,
+ nextHtmlBlockHeight,
+ readHtmlBlockMessage,
+ readHtmlBlockTheme,
+} from "./utils/html-block-document";
+import { hashSource } from "./utils/source-hash";
+
+const HEIGHT_CACHE_PREFIX = "multica:html-block:height:";
-const CODE_BLOCK_IFRAME_HEIGHT = "h-[480px]";
+// A document that never reports (a Content-Security-Policy in the author's
+// HTML can block the bridge) is shown at the old fixed height, scrolling
+// inside, once it has loaded and stayed silent this long.
+const BRIDGE_TIMEOUT_MS = 1000;
+const UNMEASURED_HEIGHT_PX = DYNAMIC_BLOCK_COLLAPSE_AT_PX;
+
+function readCachedHeight(html: string): number | null {
+ if (typeof window === "undefined") return null;
+ try {
+ const raw = window.sessionStorage.getItem(HEIGHT_CACHE_PREFIX + hashSource(html));
+ const height = raw == null ? Number.NaN : Number(raw);
+ return Number.isFinite(height) && height > 0 ? height : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeCachedHeight(html: string, height: number): void {
+ if (typeof window === "undefined") return;
+ try {
+ window.sessionStorage.setItem(HEIGHT_CACHE_PREFIX + hashSource(html), String(height));
+ } catch {
+ // Quota exceeded or storage disabled: the block still renders, it just
+ // reserves the default height next time.
+ }
+}
+
+function bodyHeightPx(contentHeight: number): number {
+ return Math.max(contentHeight, DYNAMIC_BLOCK_MIN_BODY_PX);
+}
+
+/** Reserved height before any render: the title bar plus the minimum body. */
+export const HTML_BLOCK_DEFAULT_RESERVED_PX = DYNAMIC_BLOCK_CHROME_PX + DYNAMIC_BLOCK_MIN_BODY_PX;
/**
- * 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.
+ * Height the near-viewport lazy shell (rich-content/lazy-rich-block.tsx)
+ * reserves: the collapsed height this exact HTML had earlier in the session,
+ * else the minimum. Unknown blocks reserve the minimum rather than a guess,
+ * because the shell keeps its reservation — a guess that is too tall would
+ * leave a permanent gap under a short chart.
+ *
+ * NOT safe to call during render (reads sessionStorage); see
+ * useReservedHeightPx in rich-content/rich-code-block.tsx.
*/
-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";
+export function reservedHtmlBlockHeightPx(html: string): number {
+ const cached = readCachedHeight(html);
+ if (cached == null) return HTML_BLOCK_DEFAULT_RESERVED_PX;
+ return (
+ DYNAMIC_BLOCK_CHROME_PX + Math.min(bodyHeightPx(cached), DYNAMIC_BLOCK_COLLAPSE_AT_PX)
+ );
+}
interface HtmlBlockPreviewProps {
html: string;
- className?: string;
+ /** From the fence info string: ```html title="…". */
+ title?: string | null;
}
-export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {
+export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
const { t } = useT("editor");
- const [view, setView] = useState<"preview" | "source">("preview");
- const [copied, setCopied] = useState(false);
+ const hostRef = useRef<HTMLDivElement>(null);
+ const themeVersion = useThemeVersion();
+ const [srcDoc, setSrcDoc] = useState<string | null>(null);
+ const [error, setError] = useState<DynamicBlockError | null>(null);
const [fullscreen, setFullscreen] = useState(false);
+ const frameTitle = t(($) => $.code_block.html_preview);
- const handleCopy = async () => {
- if (!html) return;
- if (await copyText(html)) {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }
- };
-
- const toggleView = () =>
- setView((v) => (v === "preview" ? "source" : "preview"));
+ // Built after mount: the theme tokens come from the host's computed style.
+ // A theme switch rebuilds the document, which reruns its scripts — a chart
+ // reads its colors when it draws, so this is the only way it can follow.
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ setError(null);
+ setSrcDoc(buildHtmlBlockDocument(html, readHtmlBlockTheme(getComputedStyle(host))));
+ }, [html, themeVersion]);
return (
- <div className={cn("code-block-wrapper group/code relative my-3", className)}>
- <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"
- >
- <span className="text-caption text-muted-foreground select-none">{HTML_LANGUAGE_LABEL}</span>
- <button
- type="button"
- onClick={toggleView}
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title={
- view === "preview"
- ? t(($) => $.code_block.show_source)
- : t(($) => $.code_block.show_preview)
- }
- aria-label={
- view === "preview"
- ? t(($) => $.code_block.show_source)
- : t(($) => $.code_block.show_preview)
- }
- >
- {view === "preview" ? (
- <CodeIcon className="h-3.5 w-3.5" />
- ) : (
- <Eye className="h-3.5 w-3.5" />
- )}
- </button>
- {view === "preview" && (
- <button
- type="button"
- onClick={() => setFullscreen(true)}
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title={t(($) => $.code_block.fullscreen)}
- aria-label={t(($) => $.code_block.fullscreen)}
- >
- <Maximize2 className="h-3.5 w-3.5" />
- </button>
+ <div ref={hostRef} className="contents">
+ <DynamicBlock
+ kind="html"
+ title={title}
+ source={html}
+ error={error}
+ onFullscreen={() => setFullscreen(true)}
+ preview={({ active }) => (
+ <HtmlBlockBody
+ key={html}
+ html={html}
+ srcDoc={srcDoc}
+ title={frameTitle}
+ active={active}
+ onError={setError}
+ />
)}
- <button
- type="button"
- onClick={handleCopy}
- className="flex h-6 w-6 items-center justify-center rounded-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title={t(($) => $.code_block.copy_code)}
- aria-label={t(($) => $.code_block.copy_code)}
- >
- {copied ? (
- <Check className="h-3.5 w-3.5" />
- ) : (
- <Copy className="h-3.5 w-3.5" />
- )}
- </button>
- </div>
- {view === "preview" ? (
- <HtmlPreviewBody
- source={{ kind: "inline", html }}
- title={t(($) => $.code_block.html_preview)}
- className={CODE_BLOCK_IFRAME_HEIGHT}
- />
- ) : (
- <CodeBlockStatic language="xml" body={html} />
- )}
+ />
<Dialog open={fullscreen} onOpenChange={setFullscreen}>
<DialogContent
className="!max-w-6xl !h-[min(90vh,calc(100vh-2rem))] w-full p-0 gap-0 overflow-hidden"
aria-label={t(($) => $.code_block.fullscreen)}
>
- <HtmlPreviewBody
- source={{ kind: "inline", html }}
- title={t(($) => $.code_block.html_preview)}
- className="h-full w-full"
- iframeClassName="rounded-none border-0"
- />
+ {srcDoc != null && (
+ <CodeBlockIframe
+ html={srcDoc}
+ title={frameTitle}
+ heightClassName="h-full"
+ className="rounded-none border-0"
+ />
+ )}
</DialogContent>
</Dialog>
</div>
);
}
+
+function HtmlBlockBody({
+ html,
+ srcDoc,
+ title,
+ active,
+ onError,
+}: {
+ html: string;
+ srcDoc: string | null;
+ title: string;
+ active: boolean;
+ onError: (error: DynamicBlockError) => void;
+}) {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [measured, reportHeight] = useReducer(nextHtmlBlockHeight, INITIAL_HTML_BLOCK_HEIGHT);
+ const [cachedHeight, setCachedHeight] = useState<number | null>(null);
+ const [loaded, setLoaded] = useState(false);
+ const [timedOut, setTimedOut] = useState(false);
+
+ // The listener is registered once; these refs give it the current values.
+ const activeRef = useRef(active);
+ const onErrorRef = useRef(onError);
+ useEffect(() => {
+ activeRef.current = active;
+ onErrorRef.current = onError;
+ });
+
+ useEffect(() => {
+ setCachedHeight(readCachedHeight(html));
+ }, [html]);
+
+ useEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ // Only this block's own frame; every block shares the window.
+ const frame = iframeRef.current;
+ if (!frame || event.source !== frame.contentWindow) return;
+ const message = readHtmlBlockMessage(event.data);
+ if (!message) return;
+ if (message.type === "error") {
+ onErrorRef.current({ message: message.message, line: message.line || undefined });
+ return;
+ }
+ // A hidden frame lays out at zero width; what it reports is not its
+ // height. It reports again once it is shown and resized back.
+ if (activeRef.current) reportHeight(message.height);
+ };
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, []);
+
+ const height = measured.height;
+ useEffect(() => {
+ if (height != null && height > 0) writeCachedHeight(html, height);
+ }, [html, height]);
+
+ useEffect(() => {
+ if (!loaded || height != null) return;
+ const timer = setTimeout(() => setTimedOut(true), BRIDGE_TIMEOUT_MS);
+ return () => clearTimeout(timer);
+ }, [loaded, height]);
+
+ const ready = height != null || timedOut;
+ const bodyHeight = bodyHeightPx(
+ height ?? (timedOut ? UNMEASURED_HEIGHT_PX : (cachedHeight ?? DYNAMIC_BLOCK_MIN_BODY_PX)),
+ );
+
+ return (
+ <div className="relative" style={{ height: bodyHeight }}>
+ {srcDoc != null && (
+ <CodeBlockIframe
+ ref={iframeRef}
+ html={srcDoc}
+ title={title}
+ heightClassName="h-full"
+ // The frame is the block's body, so it draws no border of its own.
+ // Transparent lets a document without a background sit on the
+ // block's surface.
+ className={cn("block rounded-none border-0 bg-transparent", !ready && "invisible")}
+ onLoad={() => setLoaded(true)}
+ />
+ )}
+ {!ready && (
+ <div className="absolute inset-0">
+ <DynamicBlockSkeleton />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/editor/html-preview-body.tsx b/packages/views/editor/html-preview-body.tsx
index 25789646fb..8e4a99cd14 100644
--- a/packages/views/editor/html-preview-body.tsx
+++ b/packages/views/editor/html-preview-body.tsx
@@ -1,138 +1,42 @@
"use client";
/**
- * HtmlPreviewBody — single source of truth for rendering an HTML document
- * inside a sandboxed iframe, regardless of whether the source is an inline
- * string (```html fenced code block) or an attachment id (HTML attachment).
+ * HtmlPreviewBody — an HTML document in the sandboxed preview iframe, for the
+ * attachment viewer's html kind (the caller has already fetched the text).
*
- * The two paths used to duplicate iframe + sandbox + fragment-nav shim logic
- * across html-block-preview.tsx, html-attachment-preview.tsx, and
- * attachment-preview-modal.tsx. This component owns:
+ * Owns the two things every HTML preview needs:
*
* - srcDoc + sandbox="allow-scripts" via CodeBlockIframe
* - withFragmentNavShim() so anchor links inside the iframe scroll instead
* of silently failing in the sandbox's opaque origin
- * - loading / typed-error placeholders for attachment sources
*
- * Callers (the toolbar wrappers) keep their own chrome — Copy / Source
- * toggle for code blocks, Download / Open-in-new-tab for attachments — and
- * just slot HtmlPreviewBody as the body.
+ * A ```html block in a message body is a dynamic block instead
+ * (html-block-preview.tsx): it adds theme tokens and a size/error bridge.
*/
-import { cn } from "@multica/ui/lib/utils";
-import {
- PreviewTooLargeError,
- PreviewUnsupportedError,
-} from "@multica/core/api";
-import { useT } from "../i18n";
import { CodeBlockIframe } from "./code-block-iframe";
import { withFragmentNavShim } from "./utils/iframe-fragment-nav";
-import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";
-
-export type HtmlSource =
- | { kind: "inline"; html: string }
- | { kind: "attachment"; attachmentId: string };
interface HtmlPreviewBodyProps {
- source: HtmlSource;
+ html: string;
/** iframe title attribute (a11y). */
title: string;
- /** Tailwind height/sizing classes for the iframe (e.g. "h-[480px]" or "h-full"). */
+ /** Tailwind height/sizing classes for the iframe (e.g. "h-full"). */
className?: string;
/** Override iframe styling (border / radius). Tailwind-merge resolves
* conflicts so callers can pass "rounded-none border-0" for full-screen. */
iframeClassName?: string;
- /** Sizing for loading / error placeholders. Defaults to className. */
- placeholderClassName?: string;
- /** Optional data-testid on the error placeholder — preserved for
- * html-attachment-preview.test.tsx which asserts the testid is present. */
- errorTestId?: string;
}
export function HtmlPreviewBody({
- source,
+ html,
title,
className,
iframeClassName,
- placeholderClassName,
- errorTestId,
}: HtmlPreviewBodyProps) {
- if (source.kind === "inline") {
- return (
- <CodeBlockIframe
- html={withFragmentNavShim(source.html)}
- title={title}
- heightClassName={className}
- className={iframeClassName}
- />
- );
- }
- return (
- <AttachmentBody
- attachmentId={source.attachmentId}
- title={title}
- className={className}
- iframeClassName={iframeClassName}
- placeholderClassName={placeholderClassName ?? className}
- errorTestId={errorTestId}
- />
- );
-}
-
-function AttachmentBody({
- attachmentId,
- title,
- className,
- iframeClassName,
- placeholderClassName,
- errorTestId,
-}: {
- attachmentId: string;
- title: string;
- className?: string;
- iframeClassName?: string;
- placeholderClassName?: string;
- errorTestId?: string;
-}) {
- const { t } = useT("editor");
- const query = useAttachmentHtmlText(attachmentId);
-
- if (query.isLoading) {
- return (
- <div
- className={cn(
- "flex items-center justify-center rounded-md border border-border bg-muted/30 text-caption text-muted-foreground",
- placeholderClassName,
- )}
- >
- {t(($) => $.attachment.preview_loading)}
- </div>
- );
- }
-
- if (query.error || !query.data) {
- const message =
- query.error instanceof PreviewTooLargeError
- ? t(($) => $.attachment.preview_too_large)
- : query.error instanceof PreviewUnsupportedError
- ? t(($) => $.attachment.preview_unsupported)
- : t(($) => $.attachment.preview_failed);
- return (
- <div
- className={cn(
- "flex items-center rounded-md border border-border bg-muted/30 px-3 text-caption text-muted-foreground",
- placeholderClassName,
- )}
- data-testid={errorTestId}
- >
- <span className="truncate">{message}</span>
- </div>
- );
- }
-
return (
<CodeBlockIframe
- html={withFragmentNavShim(query.data.text)}
+ html={withFragmentNavShim(html)}
title={title}
heightClassName={className}
className={iframeClassName}
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index c97b1daaba..d58afb7f03 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -30,6 +30,7 @@ export {
} from "./attachment-preview-modal";
export type {
AttachmentPreviewHandle,
+ PreviewLocateAction,
PreviewSequence,
} from "./attachment-preview-modal";
export {
@@ -37,6 +38,10 @@ export {
collectPreviewSequence,
usePreviewSequence,
} from "./preview-sequence-context";
+export type {
+ PreviewItemDetails,
+ PreviewSequenceControls,
+} from "./preview-sequence-context";
export { AttachmentCard } from "./attachment-card";
export type { AttachmentCardProps } from "./attachment-card";
export { Attachment } from "./attachment";
diff --git a/packages/views/editor/mermaid-block.tsx b/packages/views/editor/mermaid-block.tsx
new file mode 100644
index 0000000000..b94af064e8
--- /dev/null
+++ b/packages/views/editor/mermaid-block.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+/**
+ * MermaidBlock — a fenced ```mermaid block rendered in place, inside the shared
+ * DynamicBlock frame (MUL-7649). The diagram, its viewer and its layout cache
+ * stay in MermaidDiagram; the frame takes the title bar, source view, copy,
+ * fullscreen and the error panel.
+ */
+
+import { useMemo, useRef, useState } from "react";
+import {
+ DYNAMIC_BLOCK_CHROME_PX,
+ DYNAMIC_BLOCK_COLLAPSE_AT_PX,
+ DynamicBlock,
+} from "./dynamic-block";
+import {
+ MERMAID_SKELETON_HEIGHT_PX,
+ MermaidDiagram,
+ framedMermaidBodyHeightPx,
+ type MermaidFrameBinding,
+} from "./mermaid-diagram";
+
+function blockHeightPx(bodyHeight: number): number {
+ return DYNAMIC_BLOCK_CHROME_PX + Math.min(bodyHeight, DYNAMIC_BLOCK_COLLAPSE_AT_PX);
+}
+
+/** Reserved height before any render: the title bar plus the skeleton body. */
+export const MERMAID_BLOCK_DEFAULT_RESERVED_PX = blockHeightPx(MERMAID_SKELETON_HEIGHT_PX);
+
+/**
+ * Height the near-viewport lazy shell reserves for this chart: its collapsed
+ * block height when it already rendered in this session. NOT safe to call
+ * during render; see framedMermaidBodyHeightPx.
+ */
+export function reservedMermaidBlockHeightPx(chart: string): number {
+ return blockHeightPx(framedMermaidBodyHeightPx(chart));
+}
+
+export function MermaidBlock({ chart, title }: { chart: string; title?: string | null }) {
+ const [viewerOpen, setViewerOpen] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const fullscreenButtonRef = useRef<HTMLButtonElement>(null);
+
+ const frame = useMemo<MermaidFrameBinding>(
+ () => ({
+ viewerOpen,
+ onViewerOpenChange: setViewerOpen,
+ onErrorChange: setError,
+ finalFocusRef: fullscreenButtonRef,
+ }),
+ [viewerOpen],
+ );
+
+ return (
+ <DynamicBlock
+ kind="mermaid"
+ title={title}
+ source={chart}
+ error={error == null ? null : { message: error }}
+ // A diagram that did not draw has nothing to blow up.
+ onFullscreen={error == null ? () => setViewerOpen(true) : undefined}
+ fullscreenButtonRef={fullscreenButtonRef}
+ preview={() => <MermaidDiagram chart={chart} frame={frame} />}
+ />
+ );
+}
diff --git a/packages/views/editor/mermaid-diagram.tsx b/packages/views/editor/mermaid-diagram.tsx
index 46e552eed7..443e500397 100644
--- a/packages/views/editor/mermaid-diagram.tsx
+++ b/packages/views/editor/mermaid-diagram.tsx
@@ -17,6 +17,11 @@
* This component owns the inline presentation; the full-screen experience
* lives in `MermaidViewer`. Both read the same rendered SVG, so what you
* export or blow up is always what you were looking at.
+ *
+ * Standalone (the editable code block's preview) it draws its own box,
+ * toolbar and error state. Inside a DynamicBlock (`frame`, MUL-7649) the frame
+ * owns all of that: this renders only the diagram, and hands the viewer's open
+ * state and any render error up to the frame.
*/
import {
@@ -27,12 +32,16 @@ import {
useRef,
useState,
type CSSProperties,
+ type RefObject,
} from "react";
import { Check, Copy, Maximize2 } from "lucide-react";
import { copyText } from "@multica/ui/lib/clipboard";
import { useT } from "../i18n";
+import { DynamicBlockSkeleton } from "./dynamic-block";
import { useDragToScroll } from "./hooks/use-drag-to-scroll";
+import { useThemeVersion } from "./hooks/use-theme-version";
import { MermaidViewer } from "./mermaid-viewer";
+import { hashSource } from "./utils/source-hash";
import type { Size } from "./utils/zoom-transform";
type MermaidAPI = typeof import("mermaid").default;
@@ -102,9 +111,25 @@ function getMermaidThemeVariables(host: HTMLElement | null) {
function getSandboxCssVariables(host: HTMLElement | null): string {
const styles = host ? getComputedStyle(host) : null;
- return ["--muted", "--primary", "--foreground", "--muted-foreground"]
+ const variables = ["--muted", "--primary", "--foreground", "--muted-foreground"]
.map((name) => `${name}: ${styles?.getPropertyValue(name).trim() || "initial"};`)
.join(" ");
+ // The diagram is drawn in the app's colors, so its document declares the
+ // app's scheme too. Without it a light document inside a dark page is
+ // painted on an opaque white canvas, under a diagram colored for dark.
+ const declared = styles?.colorScheme ?? "";
+ const scheme = /\bdark\b/.test(declared) && !/\blight\b/.test(declared) ? "dark" : "light";
+ return `${variables} color-scheme: ${scheme};`;
+}
+
+/**
+ * The host's font for the sandbox body. Mermaid measures label text in this
+ * page (its font is `inherit`), so the sandbox has to draw with the same font
+ * or the labels no longer fit the boxes laid out for them.
+ */
+function getSandboxFontFamily(host: HTMLElement | null): string {
+ const fontFamily = host ? getComputedStyle(host).fontFamily.trim() : "";
+ return fontFamily && !/[<>{};]/.test(fontFamily) ? fontFamily : "sans-serif";
}
/**
@@ -150,39 +175,32 @@ function getMermaidLayout(svg: string): Size | null {
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
-// text itself is too unwieldy as a key (length, special chars), and a
-// crypto-strength hash would have to be async.
-function hashChart(chart: string): string {
- let hash = 5381;
- for (let i = 0; i < chart.length; i++) {
- hash = ((hash << 5) + hash) ^ chart.charCodeAt(i);
- }
- return (hash >>> 0).toString(36);
-}
+// `.mermaid-diagram` padding, top plus bottom (1rem each).
+const DIAGRAM_PADDING_Y_PX = 32;
/**
- * 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.
+ * Height a framed diagram's body will take: the drawn height of this exact
+ * chart plus the container's padding when it 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).
+ * useReservedHeightPx in rich-content/rich-code-block.tsx).
*/
-export function reservedMermaidHeightPx(chart: string): number {
- return readCachedLayout(chart)?.height ?? MERMAID_SKELETON_HEIGHT_PX;
+export function framedMermaidBodyHeightPx(chart: string): number {
+ const cached = readCachedLayout(chart);
+ return cached ? cached.height + DIAGRAM_PADDING_Y_PX : MERMAID_SKELETON_HEIGHT_PX;
}
function readCachedLayout(chart: string): Size | null {
if (typeof window === "undefined") return null;
try {
const raw = window.sessionStorage.getItem(
- MERMAID_LAYOUT_CACHE_PREFIX + hashChart(chart),
+ MERMAID_LAYOUT_CACHE_PREFIX + hashSource(chart),
);
if (!raw) return null;
const parsed = JSON.parse(raw);
@@ -205,7 +223,7 @@ function writeCachedLayout(chart: string, layout: Size | null): void {
if (!layout) return;
try {
window.sessionStorage.setItem(
- MERMAID_LAYOUT_CACHE_PREFIX + hashChart(chart),
+ MERMAID_LAYOUT_CACHE_PREFIX + hashSource(chart),
JSON.stringify({ width: layout.width, height: layout.height }),
);
} catch {
@@ -217,7 +235,9 @@ function writeCachedLayout(chart: string, layout: Size | null): void {
function buildSandboxedMermaidDocument(svg: string, host: HTMLElement | null): string {
const cssVariables = getSandboxCssVariables(host);
- return `<!doctype html><html><head><style>:root { ${cssVariables} } body { margin: 0; display: flex; justify-content: center; background: transparent; } svg { max-width: 100%; height: auto; }</style></head><body>${svg}</body></html>`;
+ const fontFamily = getSandboxFontFamily(host);
+
+ return `<!doctype html><html><head><style>:root { ${cssVariables} } body { margin: 0; display: flex; justify-content: center; background: transparent; font-family: ${fontFamily}; } svg { max-width: 100%; height: auto; }</style></head><body>${svg}</body></html>`;
}
/**
@@ -233,36 +253,9 @@ function buildViewerMermaidDocument(
): string {
const cssVariables = getSandboxCssVariables(host);
- return `<!doctype html><html><head><style>:root { ${cssVariables} } html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; } svg { display: block; width: ${layout.width}px; height: ${layout.height}px; max-width: none; }</style></head><body>${svg}</body></html>`;
-}
-
-function useThemeVersion() {
- const [themeVersion, setThemeVersion] = useState(0);
+ const fontFamily = getSandboxFontFamily(host);
- useEffect(() => {
- const bumpThemeVersion = () => setThemeVersion((version) => version + 1);
- const observer = new MutationObserver(bumpThemeVersion);
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ["class", "style", "data-theme"],
- });
- if (document.body) {
- observer.observe(document.body, {
- attributes: true,
- attributeFilter: ["class", "style", "data-theme"],
- });
- }
-
- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
- mediaQuery.addEventListener("change", bumpThemeVersion);
-
- return () => {
- observer.disconnect();
- mediaQuery.removeEventListener("change", bumpThemeVersion);
- };
- }, []);
-
- return themeVersion;
+ return `<!doctype html><html><head><style>:root { ${cssVariables} } html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; font-family: ${fontFamily}; } svg { display: block; width: ${layout.width}px; height: ${layout.height}px; max-width: none; }</style></head><body>${svg}</body></html>`;
}
/**
@@ -329,7 +322,22 @@ interface RenderedDiagram {
exportFontFamily: string;
}
-export function MermaidDiagram({ chart }: { chart: string }) {
+/** What a DynamicBlock needs from the diagram it frames. */
+export interface MermaidFrameBinding {
+ viewerOpen: boolean;
+ onViewerOpenChange: (open: boolean) => void;
+ onErrorChange: (error: string | null) => void;
+ /** The frame's fullscreen button; focus returns there when the viewer closes. */
+ finalFocusRef: RefObject<HTMLButtonElement | null>;
+}
+
+export function MermaidDiagram({
+ chart,
+ frame,
+}: {
+ chart: string;
+ frame?: MermaidFrameBinding;
+}) {
const { t } = useT("editor");
const reactId = useId();
const containerRef = useRef<HTMLDivElement>(null);
@@ -351,7 +359,10 @@ export function MermaidDiagram({ chart }: { chart: string }) {
readCachedLayout(chart),
);
const [error, setError] = useState<string | null>(null);
- const [viewerOpen, setViewerOpen] = useState(false);
+ const [ownViewerOpen, setOwnViewerOpen] = useState(false);
+ const viewerOpen = frame ? frame.viewerOpen : ownViewerOpen;
+ const setViewerOpen = frame ? frame.onViewerOpenChange : setOwnViewerOpen;
+ const onErrorChange = frame?.onErrorChange;
const [copied, setCopied] = useState(false);
useEffect(() => {
@@ -422,8 +433,12 @@ export function MermaidDiagram({ chart }: { chart: string }) {
};
}, [chart, diagramId, themeVersion]);
+ useEffect(() => {
+ onErrorChange?.(error);
+ }, [error, onErrorChange]);
+
const overflow = useHorizontalOverflow(scrollRef, [rendered?.inlineDocument]);
- const openViewer = useCallback(() => setViewerOpen(true), []);
+ const openViewer = useCallback(() => setViewerOpen(true), [setViewerOpen]);
const dragToScroll = useDragToScroll({ onTap: openViewer });
const handleCopySource = useCallback(async () => {
@@ -433,6 +448,12 @@ export function MermaidDiagram({ chart }: { chart: string }) {
}
}, [chart]);
+ if (error && frame) {
+ // The frame shows the error panel; keep the host so a theme switch can
+ // still resolve colors for the next attempt.
+ return <div ref={containerRef} className="mermaid-diagram" data-framed="" />;
+ }
+
if (error) {
return (
<div ref={containerRef} className="mermaid-diagram mermaid-diagram-error">
@@ -463,12 +484,17 @@ export function MermaidDiagram({ chart }: { chart: string }) {
// drives layout. If the cache was right, this transition is zero-shift.
const containerStyle: CSSProperties | undefined = rendered
? undefined
- : { minHeight: skeletonLayout?.height ?? MERMAID_SKELETON_HEIGHT_PX };
+ : {
+ minHeight: skeletonLayout
+ ? skeletonLayout.height + (frame ? DIAGRAM_PADDING_Y_PX : 0)
+ : MERMAID_SKELETON_HEIGHT_PX,
+ };
return (
<div
ref={containerRef}
className="mermaid-diagram"
+ data-framed={frame ? "" : undefined}
aria-label={t(($) => $.mermaid.diagram_label)}
style={containerStyle}
data-overflow-start={overflow.start ? "" : undefined}
@@ -499,25 +525,27 @@ export function MermaidDiagram({ chart }: { chart: string }) {
title={t(($) => $.mermaid.diagram_label)}
/>
</div>
- <div className="mermaid-diagram-toolbar">
- <button
- type="button"
- onClick={handleCopySource}
- title={t(($) => $.mermaid.copy_source)}
- aria-label={t(($) => $.mermaid.copy_source)}
- >
- {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
- </button>
- <button
- ref={expandButtonRef}
- type="button"
- onClick={() => setViewerOpen(true)}
- title={t(($) => $.mermaid.open_viewer)}
- aria-label={t(($) => $.mermaid.open_viewer)}
- >
- <Maximize2 className="size-3.5" />
- </button>
- </div>
+ {!frame && (
+ <div className="mermaid-diagram-toolbar">
+ <button
+ type="button"
+ onClick={handleCopySource}
+ title={t(($) => $.mermaid.copy_source)}
+ aria-label={t(($) => $.mermaid.copy_source)}
+ >
+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
+ </button>
+ <button
+ ref={expandButtonRef}
+ type="button"
+ onClick={() => setViewerOpen(true)}
+ title={t(($) => $.mermaid.open_viewer)}
+ aria-label={t(($) => $.mermaid.open_viewer)}
+ >
+ <Maximize2 className="size-3.5" />
+ </button>
+ </div>
+ )}
<MermaidViewer
open={viewerOpen}
onOpenChange={setViewerOpen}
@@ -527,9 +555,11 @@ export function MermaidDiagram({ chart }: { chart: string }) {
layout={rendered.viewerLayout}
exportBackground={rendered.exportBackground}
exportFontFamily={rendered.exportFontFamily}
- finalFocusRef={expandButtonRef}
+ finalFocusRef={frame ? frame.finalFocusRef : expandButtonRef}
/>
</>
+ ) : frame ? (
+ <DynamicBlockSkeleton className="absolute inset-0 p-4" />
) : (
<div className="mermaid-diagram-loading">{t(($) => $.mermaid.rendering)}</div>
)}
diff --git a/packages/views/editor/preview-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsx
index 7f862878b7..e7e09c0028 100644
--- a/packages/views/editor/preview-sequence-context.test.tsx
+++ b/packages/views/editor/preview-sequence-context.test.tsx
@@ -4,6 +4,7 @@ import {
fireEvent,
render as rtlRender,
screen,
+ waitFor,
} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactElement } from "react";
@@ -66,6 +67,8 @@ const STRINGS: Record<string, Record<string, string>> = {
previous: "Previous",
next: "Next",
sequence_position: "{{index}} / {{total}}",
+ overview: "All deliverables",
+ info: "Info",
},
};
@@ -471,6 +474,139 @@ describe("PreviewSequenceProvider", () => {
});
});
+// What the issue page layers on top of the generic viewer (MUL-7649): an
+// info panel, "show in comments", a way to the overview, a version switcher.
+describe("host details", () => {
+ function openFirst() {
+ act(() => {
+ fireEvent.click(screen.getByText("open"));
+ });
+ }
+
+ it("toggles the info panel with I and lets its controls move the viewer", () => {
+ render(
+ <PreviewSequenceProvider
+ items={sequenceOf(THREE)}
+ describeItem={(item, controls) => ({
+ info: (
+ <button type="button" onClick={() => controls.goTo(THREE[2]!.id)}>
+ {`about ${item.filename}`}
+ </button>
+ ),
+ })}
+ >
+ <Opener openKey={THREE[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ openFirst();
+ expect(screen.queryByRole("complementary", { name: "Info" })).toBeNull();
+
+ act(() => {
+ fireEvent.keyDown(document, { key: "i" });
+ });
+ expect(screen.getByRole("complementary", { name: "Info" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Info" })).toHaveAttribute("aria-pressed", "true");
+
+ act(() => {
+ fireEvent.click(screen.getByText("about shot-1.png"));
+ });
+ expectCounter("3 / 3");
+ // The panel follows the file on screen.
+ expect(screen.getByText("about shot-3.png")).toBeInTheDocument();
+
+ act(() => {
+ fireEvent.keyDown(document, { key: "I" });
+ });
+ expect(screen.queryByRole("complementary", { name: "Info" })).toBeNull();
+ });
+
+ it("closes the viewer, then locates", async () => {
+ const onSelect = vi.fn();
+ render(
+ <PreviewSequenceProvider
+ items={sequenceOf(THREE)}
+ describeItem={() => ({ locate: { label: "Show in comments", onSelect } })}
+ >
+ <Opener openKey={THREE[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ openFirst();
+
+ act(() => {
+ fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
+ });
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ });
+
+ it("hands the overview the file on screen when G is pressed", async () => {
+ const onOpenOverview = vi.fn();
+ render(
+ <PreviewSequenceProvider items={sequenceOf(THREE)} onOpenOverview={onOpenOverview}>
+ <Opener openKey={THREE[1]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ openFirst();
+ expect(screen.getByRole("button", { name: "All deliverables" })).toHaveAttribute(
+ "aria-keyshortcuts",
+ "G",
+ );
+
+ act(() => {
+ fireEvent.keyDown(document, { key: "g" });
+ });
+ expect(onOpenOverview).toHaveBeenCalledWith(THREE[1]!.id);
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ });
+
+ it("offers no overview or info controls to a surface without them", () => {
+ render(
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
+ <Opener openKey={THREE[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ openFirst();
+ expect(screen.queryByRole("button", { name: "All deliverables" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Info" })).toBeNull();
+ });
+
+ it("leaves letter keys to a field and every key to an open menu", () => {
+ const onOpenOverview = vi.fn();
+ render(
+ <PreviewSequenceProvider
+ items={sequenceOf(THREE)}
+ onOpenOverview={onOpenOverview}
+ describeItem={() => ({
+ titleAccessory: (
+ <>
+ <input aria-label="field" />
+ <div role="menu">
+ <button type="button">v1</button>
+ </div>
+ </>
+ ),
+ })}
+ >
+ <Opener openKey={THREE[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ openFirst();
+
+ act(() => {
+ fireEvent.keyDown(screen.getByLabelText("field"), { key: "g" });
+ });
+ expect(onOpenOverview).not.toHaveBeenCalled();
+
+ const menuItem = screen.getByRole("button", { name: "v1" });
+ act(() => {
+ fireEvent.keyDown(menuItem, { key: "ArrowRight" });
+ fireEvent.keyDown(menuItem, { key: "Escape" });
+ });
+ expectCounter("1 / 3");
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+});
+
// An agent that rewrites an issue body swaps the markdown image URL but does
// not register the new file as an attachment of that issue, so these images
// reach the viewer with no server metadata at all — the caption is the only
diff --git a/packages/views/editor/preview-sequence-context.tsx b/packages/views/editor/preview-sequence-context.tsx
index 9f4c94dcdc..402d1aaae5 100644
--- a/packages/views/editor/preview-sequence-context.tsx
+++ b/packages/views/editor/preview-sequence-context.tsx
@@ -27,6 +27,11 @@
* Attachments outside the sequence (an in-flight upload in a composer, a file
* in a surface with no provider) are not an error: `openAt` reports false and
* the caller falls back to its own single-file preview.
+ *
+ * A surface that knows more about its files than the sequence does (the issue
+ * page: which comment a file came from, its earlier versions) supplies
+ * `describeItem`, and `onOpenOverview` for a grid of everything (MUL-7649).
+ * The viewer stays generic — it only renders the slots it is handed.
*/
import {
@@ -49,6 +54,7 @@ import { useT } from "../i18n";
import {
AttachmentPreviewModal,
PreviewImagePrefetch,
+ type PreviewLocateAction,
type PreviewSource,
} from "./attachment-preview-modal";
import { canOpenPreview, getPreviewKind } from "./utils/preview";
@@ -65,6 +71,32 @@ export function collectPreviewSequence(
);
}
+/**
+ * What the host surface adds to the viewer for the file on screen. Every
+ * field is optional; the viewer renders the matching control only when set.
+ */
+export interface PreviewItemDetails {
+ /** Rendered after the file name, e.g. a version switcher. */
+ titleAccessory?: ReactNode;
+ /** Body of the info panel, toggled with the top-bar button or `I`. */
+ info?: ReactNode;
+ /** Take the reader to where the file was posted. The viewer closes first. */
+ locate?: PreviewLocateAction;
+}
+
+/** Handed to `describeItem` so its controls can move within the session. */
+export interface PreviewSequenceControls {
+ /** The frozen sequence this session pages through. */
+ items: ReadonlyArray<ImageSequenceItem>;
+ /** Move to `key`; false when it is not part of this session. */
+ goTo: (key: string) => boolean;
+ /**
+ * Close the viewer. For controls in the info panel that take the reader
+ * elsewhere on the page, which the viewer would otherwise cover.
+ */
+ close: () => void;
+}
+
interface PreviewSequenceApi {
/**
* Open the shared viewer at `key` — the attachment id, or the URL as written
@@ -116,9 +148,20 @@ interface Session {
export function PreviewSequenceProvider({
items,
+ describeItem,
+ onOpenOverview,
children,
}: {
items: ReadonlyArray<ImageSequenceItem>;
+ describeItem?: (
+ item: ImageSequenceItem,
+ controls: PreviewSequenceControls,
+ ) => PreviewItemDetails | undefined;
+ /**
+ * Show every file at once. The viewer closes and hands over the key it was
+ * showing, so the overview can offer a way back to it.
+ */
+ onOpenOverview?: (currentKey: string) => void;
children: ReactNode;
}) {
const { t } = useT("editor");
@@ -129,6 +172,9 @@ export function PreviewSequenceProvider({
const [session, setSession] = useState<Session | null>(null);
const [open, setOpen] = useState(false);
+ // Outlives a session: a reader who wants the info panel wants it on the
+ // next file they open too.
+ const [infoOpen, setInfoOpen] = useState(false);
// Images that failed to load this session. Kept out of navigation so a
// deleted image can't trap the reader on a broken frame, and so the
// auto-skip below can't bounce between two dead images forever. The ref is
@@ -204,6 +250,26 @@ export function PreviewSequenceProvider({
const prevIndex = session ? step(session, session.index, -1, broken) : -1;
const nextIndex = session ? step(session, session.index, 1, broken) : -1;
+ const goTo = useCallback(
+ (key: string) => {
+ if (!session) return false;
+ const index = indexOfImageKey(session.items, key);
+ if (index < 0) return false;
+ if (index !== session.index) {
+ directionRef.current = index > session.index ? 1 : -1;
+ setSession({ ...session, index });
+ }
+ return true;
+ },
+ [session],
+ );
+
+ const details =
+ session && current && describeItem
+ ? describeItem(current, { items: session.items, goTo, close: () => setOpen(false) })
+ : undefined;
+ const locate = details?.locate;
+
const modal =
session && current ? (
<AttachmentPreviewModal
@@ -212,6 +278,31 @@ export function PreviewSequenceProvider({
onClose={() => setOpen(false)}
onExitComplete={() => setSession(null)}
onImageError={handleImageError}
+ titleAccessory={details?.titleAccessory}
+ info={
+ details?.info
+ ? { content: details.info, open: infoOpen, onToggle: () => setInfoOpen((v) => !v) }
+ : undefined
+ }
+ locate={
+ locate
+ ? {
+ label: locate.label,
+ onSelect: () => {
+ setOpen(false);
+ locate.onSelect();
+ },
+ }
+ : undefined
+ }
+ onOpenOverview={
+ onOpenOverview
+ ? () => {
+ setOpen(false);
+ onOpenOverview(current.key);
+ }
+ : undefined
+ }
sequence={
session.items.length > 1
? {
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 570bf1354e..b95a3e40e8 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ReactElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -499,20 +499,20 @@ describe("ReadonlyContent Mermaid rendering", () => {
expect(container.querySelector("pre")).toBeNull();
});
- it("opens the fullscreen viewer from the toolbar and closes it with Escape", async () => {
+ it("opens the fullscreen viewer from the block's title bar and closes it with Escape", async () => {
const { container } = render(
<ReadonlyContent
content={["```mermaid", "graph LR", " A[Start] --> B[Done]", "```"].join("\n")}
/>,
);
- const expandButton = await waitFor(() => {
- const found = container.querySelector<HTMLButtonElement>(
- '.mermaid-diagram-toolbar button[aria-label="Open diagram viewer"]',
- );
- expect(found).not.toBeNull();
- return found!;
+ await waitFor(() => {
+ expect(container.querySelector(".mermaid-diagram-frame")).not.toBeNull();
});
+ const expandButton = container.querySelector<HTMLButtonElement>(
+ '[data-dynamic-block="mermaid"] button[aria-label="Fullscreen"]',
+ )!;
+ expect(expandButton).not.toBeNull();
expect(document.querySelector(".zoom-canvas")).toBeNull();
@@ -536,7 +536,7 @@ describe("ReadonlyContent Mermaid rendering", () => {
});
});
- it("keeps the inline toolbar outside the scroll container so wide diagrams stay openable", async () => {
+ it("keeps the controls in the title bar, outside the scroll container, so wide diagrams stay openable", async () => {
const { container } = render(
<ReadonlyContent
content={["```mermaid", "graph LR", " A[Start] --> B[Done]", "```"].join("\n")}
@@ -544,18 +544,20 @@ describe("ReadonlyContent Mermaid rendering", () => {
);
await waitFor(() => {
- expect(container.querySelector(".mermaid-diagram-toolbar")).not.toBeNull();
+ expect(container.querySelector(".mermaid-diagram-scroll")).not.toBeNull();
});
- // Previously the toolbar was an absolutely-positioned child of the
- // horizontally-scrolling element, so on a wide diagram it scrolled out of
- // view along with the content and left no way to open or copy it.
- const scroller = container.querySelector(".mermaid-diagram-scroll");
- expect(scroller).not.toBeNull();
- expect(scroller?.querySelector(".mermaid-diagram-toolbar")).toBeNull();
+ // A control inside the horizontally-scrolling element would scroll out of
+ // view with a wide diagram and leave no way to open or copy it. The frame
+ // owns the controls, so the diagram's own hover toolbar is not drawn.
+ const scroller = container.querySelector(".mermaid-diagram-scroll")!;
+ expect(container.querySelector(".mermaid-diagram-toolbar")).toBeNull();
+ expect(scroller.querySelector("button")).toBeNull();
+ expect(container.querySelector('button[aria-label="Fullscreen"]')).not.toBeNull();
+ expect(container.querySelector('button[aria-label="Copy source"]')).not.toBeNull();
});
- it("shows the compact error state instead of embedding Mermaid's parser error SVG", async () => {
+ it("explains a parse error inside the block instead of embedding Mermaid's error SVG", async () => {
// With suppressErrorRendering enabled, invalid syntax makes render() reject
// instead of emitting Mermaid's built-in error graphic.
vi.mocked(mermaid.render).mockRejectedValueOnce(
@@ -567,14 +569,17 @@ describe("ReadonlyContent Mermaid rendering", () => {
<ReadonlyContent content={["```mermaid", chart, "```"].join("\n")} />,
);
+ const alert = await screen.findByRole("alert");
+ expect(alert.textContent).toContain("Couldn't draw this diagram");
+ expect(alert.textContent).toContain("Parse error on line 3");
+ expect(container.querySelector(".mermaid-diagram-frame")).toBeNull();
+ // Nothing to blow up once the diagram failed.
+ expect(container.querySelector('button[aria-label="Fullscreen"]')).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "View source" }));
await waitFor(() => {
- expect(container.querySelector(".mermaid-diagram-error")).not.toBeNull();
+ expect(container.querySelector("pre code")?.textContent).toBe(chart);
});
-
- expect(container.querySelector(".mermaid-diagram-frame")).toBeNull();
- expect(container.querySelector(".mermaid-diagram-error code")?.textContent).toBe(
- chart,
- );
});
});
@@ -628,12 +633,10 @@ describe("ReadonlyContent HTML block rendering", () => {
});
});
-describe("ReadonlyContent file-card → AttachmentBlock HTML routing", () => {
- // Regression pin for readonly-content.tsx:279. The `div data-type=fileCard`
- // branch must render through <AttachmentBlock>, not the older
- // <AttachmentCard>. Reverting that line would skip the html+attachmentId
- // dispatcher branch and surface the bare file-card chrome (filename row)
- // instead of the rendered iframe — the exact regression MUL-2330 fixed.
+describe("ReadonlyContent file-card routing", () => {
+ // The `div data-type=fileCard` branch renders through the unified
+ // <Attachment> renderer, which shows every non-image file — HTML included
+ // (MUL-7649) — as file-card chrome.
function renderWithQuery(ui: ReactElement) {
const qc = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
@@ -641,11 +644,9 @@ describe("ReadonlyContent file-card → AttachmentBlock HTML routing", () => {
return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
}
- it("renders the !file[](url) HTML attachment as an iframe (no file-card chrome)", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart</p>",
- originalContentType: "text/html",
- });
+ // Reverses the MUL-2330 pin: a file referenced in the body is still a file.
+ // HTML meant to be read in place is written as a ```html block.
+ it("renders a !file[](url) HTML attachment as file-card chrome, not an embedded preview", () => {
const attachment = {
id: "att-1",
url: "/uploads/report.html",
@@ -653,22 +654,15 @@ describe("ReadonlyContent file-card → AttachmentBlock HTML routing", () => {
content_type: "text/html",
size_bytes: 0,
} as any;
- const { container, queryByText } = renderWithQuery(
+ const { container, getByText } = renderWithQuery(
<ReadonlyContent
content="!file[report.html](/uploads/report.html)"
attachments={[attachment]}
/>,
);
- const frame = await waitFor(() => {
- const f = container.querySelector<HTMLIFrameElement>("iframe");
- expect(f).not.toBeNull();
- return f!;
- });
- expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
- expect(frame.getAttribute("srcdoc")).toContain("<p>chart</p>");
- // AttachmentCard chrome surfaces the filename as visible text in a
- // <p class="truncate"> row. HtmlAttachmentPreview replaces it entirely.
- expect(queryByText("report.html")).toBeNull();
+ expect(getByText("report.html")).toBeTruthy();
+ expect(container.querySelector("iframe")).toBeNull();
+ expect(getAttachmentTextContentMock).not.toHaveBeenCalled();
});
it("renders a stable attachment download URL as file-card chrome", () => {
diff --git a/packages/views/editor/styles/attachment.css b/packages/views/editor/styles/attachment.css
index 673730321f..4a2becfee1 100644
--- a/packages/views/editor/styles/attachment.css
+++ b/packages/views/editor/styles/attachment.css
@@ -29,6 +29,24 @@
border-radius: var(--radius);
}
+/* A thumbnail in a row of standalone images (the "card" layout): it fills
+ the box its row gives it — the row sizes each box from the image's own
+ aspect ratio — so a set of screenshots reads as one strip instead of a
+ stack of full-width frames. */
+.image-figure.image-tile {
+ display: block;
+ margin: 0;
+ width: 100%;
+ height: 100%;
+}
+
+.image-figure.image-tile .image-content {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ box-shadow: 0 0 0 1px var(--border);
+}
+
.image-uploading {
opacity: 0.5;
animation: rte-upload-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
diff --git a/packages/views/editor/styles/mermaid.css b/packages/views/editor/styles/mermaid.css
index 92b0b3a3fc..65a824657d 100644
--- a/packages/views/editor/styles/mermaid.css
+++ b/packages/views/editor/styles/mermaid.css
@@ -75,6 +75,23 @@
opacity: 1;
}
+/* Inside a DynamicBlock (MUL-7649) the frame draws the border, background and
+ chrome; the diagram sits directly on the frame's surface. */
+.rich-text-editor .mermaid-diagram[data-framed] {
+ background: transparent;
+ border: 0;
+ border-radius: 0;
+ margin: 0;
+}
+
+.rich-text-editor .mermaid-diagram[data-framed]::before {
+ background: linear-gradient(to right, var(--surface), transparent);
+}
+
+.rich-text-editor .mermaid-diagram[data-framed]::after {
+ background: linear-gradient(to left, var(--surface), transparent);
+}
+
.rich-text-editor .mermaid-diagram-loading,
.rich-text-editor .mermaid-diagram-error p {
color: var(--muted-foreground);
diff --git a/packages/views/editor/utils/file-icon.ts b/packages/views/editor/utils/file-icon.ts
new file mode 100644
index 0000000000..3d1818bcdf
--- /dev/null
+++ b/packages/views/editor/utils/file-icon.ts
@@ -0,0 +1,63 @@
+/**
+ * A file's type glyph — one mapping for every surface that shows a file by
+ * its kind: comment file cards, the issue deliverables list and overview.
+ */
+
+import {
+ File,
+ FileArchive,
+ FileAudio,
+ FileCode,
+ FileSpreadsheet,
+ FileText,
+ FileVideo,
+ ImageIcon,
+ type LucideIcon,
+} from "lucide-react";
+import { getPreviewKind } from "./preview";
+
+function extensionOf(filename: string): string {
+ const base = (filename ?? "").toLowerCase().split(/[\\/]/).pop() ?? "";
+ const dot = base.lastIndexOf(".");
+ return dot <= 0 ? "" : base.slice(dot + 1);
+}
+
+// Files people read as documents. Data (CSV, JSON) and code are not, even
+// though the viewer shows them as text.
+const DOCUMENT_EXTENSIONS = new Set([
+ "pdf", "md", "markdown", "txt", "rtf",
+ "doc", "docx", "odt", "pages",
+ "ppt", "pptx", "odp", "key",
+ "xls", "xlsx", "ods", "numbers",
+]);
+
+const SPREADSHEET_EXTENSIONS = new Set(["csv", "tsv", "xls", "xlsx", "ods", "numbers"]);
+const ARCHIVE_EXTENSIONS = new Set(["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar"]);
+
+export function isDocumentFile(contentType: string, filename: string): boolean {
+ const kind = getPreviewKind(contentType, filename);
+ if (kind === "pdf" || kind === "markdown") return true;
+ return DOCUMENT_EXTENSIONS.has(extensionOf(filename));
+}
+
+export function fileIcon(contentType: string, filename: string): LucideIcon {
+ const ext = extensionOf(filename);
+ if (SPREADSHEET_EXTENSIONS.has(ext)) return FileSpreadsheet;
+ if (ARCHIVE_EXTENSIONS.has(ext)) return FileArchive;
+ switch (getPreviewKind(contentType, filename)) {
+ case "image":
+ return ImageIcon;
+ case "video":
+ return FileVideo;
+ case "audio":
+ return FileAudio;
+ case "pdf":
+ case "markdown":
+ return FileText;
+ case "html":
+ case "text":
+ return FileCode;
+ default:
+ return DOCUMENT_EXTENSIONS.has(ext) ? FileText : File;
+ }
+}
diff --git a/packages/views/editor/utils/html-block-document.test.ts b/packages/views/editor/utils/html-block-document.test.ts
new file mode 100644
index 0000000000..ec71e1125f
--- /dev/null
+++ b/packages/views/editor/utils/html-block-document.test.ts
@@ -0,0 +1,150 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import {
+ HTML_BLOCK_MAX_CONTENT_PX,
+ HTML_BLOCK_MESSAGE_KEY,
+ INITIAL_HTML_BLOCK_HEIGHT,
+ __HTML_BLOCK_BRIDGE__,
+ buildHtmlBlockDocument,
+ nextHtmlBlockHeight,
+ readHtmlBlockMessage,
+ readHtmlBlockTheme,
+ usesThemeTokens,
+} from "./html-block-document";
+import { __FRAGMENT_NAV_SHIM__ } from "./iframe-fragment-nav";
+
+const THEME = { declarations: "--foreground:black;--chart-1:blue", colorScheme: "dark" as const };
+
+describe("buildHtmlBlockDocument", () => {
+ it("puts the theme and bridge in front of the markup and the fragment shim after it", () => {
+ const doc = buildHtmlBlockDocument("<p>hi</p>", THEME);
+ expect(doc.startsWith("<style>:root{--foreground:black;--chart-1:blue}</style><script>")).toBe(true);
+ expect(doc).toContain(__HTML_BLOCK_BRIDGE__);
+ expect(doc).toContain("</script><p>hi</p>");
+ expect(doc.endsWith(__FRAGMENT_NAV_SHIM__)).toBe(true);
+ });
+
+ it("keeps a leading doctype first", () => {
+ const doc = buildHtmlBlockDocument("<!DOCTYPE html>\n<html><body>x</body></html>", THEME);
+ expect(doc.startsWith("<!DOCTYPE html><style>")).toBe(true);
+ expect(doc).toContain("</script>\n<html>");
+ });
+
+ // Error line numbers come from the srcdoc; the prefix must not shift them.
+ it("adds no line breaks in front of the author's markup", () => {
+ expect(__HTML_BLOCK_BRIDGE__).not.toContain("\n");
+ const doc = buildHtmlBlockDocument("line1\nline2", THEME);
+ expect(doc.split("\n")[1]!.startsWith("line2")).toBe(true);
+ });
+
+ it("gives the app's color scheme only to HTML that uses a theme token", () => {
+ expect(buildHtmlBlockDocument('<p style="color:var(--foreground)">x</p>', THEME)).toContain(
+ ";color-scheme:dark}",
+ );
+ expect(buildHtmlBlockDocument('<p style="color:#333">x</p>', THEME)).not.toContain(
+ "color-scheme",
+ );
+ });
+});
+
+describe("usesThemeTokens", () => {
+ it("matches whole token names only", () => {
+ expect(usesThemeTokens("fill: var(--chart-2)")).toBe(true);
+ expect(usesThemeTokens("color: var( --muted-foreground )")).toBe(true);
+ expect(usesThemeTokens("font-family: var(--font-sans)")).toBe(true);
+ expect(usesThemeTokens("border-radius: var(--border-radius)")).toBe(false);
+ expect(usesThemeTokens("--foreground: red")).toBe(false);
+ });
+});
+
+describe("readHtmlBlockTheme", () => {
+ const styles = (values: Record<string, string>, fontFamily = "Inter, sans-serif", colorScheme = "light") => ({
+ getPropertyValue: (name: string) => values[name] ?? "",
+ fontFamily,
+ colorScheme,
+ });
+
+ it("copies the defined tokens and the font, skipping undefined ones", () => {
+ const theme = readHtmlBlockTheme(styles({ "--foreground": " oklch(0.2 0 0) ", "--chart-1": "blue" }));
+ expect(theme.declarations).toBe(
+ "--foreground:oklch(0.2 0 0);--chart-1:blue;--font-sans:Inter, sans-serif",
+ );
+ });
+
+ it("gives --background the block's surface color", () => {
+ const theme = readHtmlBlockTheme(styles({ "--background": "gray", "--surface": "white" }));
+ expect(theme.declarations).toContain("--background:white;--surface:white");
+ expect(readHtmlBlockTheme(styles({ "--background": "gray" })).declarations).toContain(
+ "--background:gray",
+ );
+ });
+
+ it("drops a value that could break out of the style rule", () => {
+ const theme = readHtmlBlockTheme(styles({ "--foreground": "red}</style><script>" }));
+ expect(theme.declarations).not.toContain("script");
+ });
+
+ it("reads dark only when the host is dark", () => {
+ expect(readHtmlBlockTheme(styles({}, "", "dark")).colorScheme).toBe("dark");
+ expect(readHtmlBlockTheme(styles({}, "", "light dark")).colorScheme).toBe("light");
+ expect(readHtmlBlockTheme(styles({}, "", "normal")).colorScheme).toBe("light");
+ });
+});
+
+describe("readHtmlBlockMessage", () => {
+ const msg = (data: Record<string, unknown>) => ({ [HTML_BLOCK_MESSAGE_KEY]: 1, ...data });
+
+ it("reads height and error messages", () => {
+ expect(readHtmlBlockMessage(msg({ type: "height", height: 240.2 }))).toEqual({
+ type: "height",
+ height: 241,
+ });
+ expect(readHtmlBlockMessage(msg({ type: "error", message: "boom", line: 9 }))).toEqual({
+ type: "error",
+ message: "boom",
+ line: 9,
+ });
+ });
+
+ it("clamps what the sandbox sends", () => {
+ expect(readHtmlBlockMessage(msg({ type: "height", height: 1e9 }))).toEqual({
+ type: "height",
+ height: HTML_BLOCK_MAX_CONTENT_PX,
+ });
+ expect(readHtmlBlockMessage(msg({ type: "height", height: -5 }))).toEqual({ type: "height", height: 0 });
+ const long = readHtmlBlockMessage(msg({ type: "error", message: "x".repeat(2000), line: "9" }));
+ expect(long).toEqual({ type: "error", message: "x".repeat(500), line: 0 });
+ });
+
+ it("ignores anything else", () => {
+ expect(readHtmlBlockMessage({ type: "height", height: 10 })).toBeNull();
+ expect(readHtmlBlockMessage(msg({ type: "height", height: "10" }))).toBeNull();
+ expect(readHtmlBlockMessage(msg({ type: "resize" }))).toBeNull();
+ expect(readHtmlBlockMessage("height")).toBeNull();
+ expect(readHtmlBlockMessage(null)).toBeNull();
+ });
+});
+
+describe("nextHtmlBlockHeight", () => {
+ const run = (reports: number[]) => reports.reduce(nextHtmlBlockHeight, INITIAL_HTML_BLOCK_HEIGHT);
+
+ it("follows the content up and down", () => {
+ expect(run([40, 320]).height).toBe(320);
+ expect(run([40, 320, 180]).height).toBe(180);
+ });
+
+ // A document sized in `vh` grows by the same step each time the frame
+ // grows. Three equal steps in a row stop it.
+ it("stops a document whose height follows the frame", () => {
+ const state = run([300, 316, 332, 348, 364, 380]);
+ expect(state.frozen).toBe(true);
+ expect(state.height).toBe(332);
+ expect(nextHtmlBlockHeight(state, 100).height).toBe(332);
+ });
+
+ it("does not stop content that grows by different amounts", () => {
+ const state = run([100, 180, 300, 330, 480]);
+ expect(state.frozen).toBe(false);
+ expect(state.height).toBe(480);
+ });
+});
diff --git a/packages/views/editor/utils/html-block-document.ts b/packages/views/editor/utils/html-block-document.ts
new file mode 100644
index 0000000000..b15c5ae7a4
--- /dev/null
+++ b/packages/views/editor/utils/html-block-document.ts
@@ -0,0 +1,233 @@
+import { withFragmentNavShim } from "./iframe-fragment-nav";
+
+/**
+ * Document assembly for the ```html dynamic block (MUL-7649).
+ *
+ * The block sizes itself to its content and explains a script error in place,
+ * which needs the sandboxed document to talk back. A sandbox without
+ * `allow-same-origin` blocks every parent-side read of the frame, but
+ * `postMessage` still crosses it, so a tiny bridge script is placed in front
+ * of the author's markup. It reports two things: the content height and the
+ * first uncaught error. The parent treats both as untrusted input — it checks
+ * the message source and clamps every value (see readHtmlBlockMessage).
+ *
+ * The prefix also carries the app's theme tokens as CSS custom properties, so
+ * HTML written against `var(--foreground)` / `var(--chart-1)` follows light and
+ * dark mode. Using a token is the opt-in: only then does the document also get
+ * the app's `color-scheme`. That matters in dark mode, where a light document
+ * inside a dark page is painted on an opaque white canvas — right for HTML
+ * that was written for white, wrong for HTML that asked for the theme. HTML
+ * that uses no token is left exactly as written: no reset, no scheme.
+ */
+
+/** Marker on every bridge message; anything without it is ignored. */
+export const HTML_BLOCK_MESSAGE_KEY = "__multicaHtmlBlock";
+
+/**
+ * Theme tokens copied into the sandbox. Only color and shape tokens: a chart
+ * needs these to match the page, and every one resolves to a plain value.
+ */
+export const HTML_BLOCK_THEME_TOKENS = [
+ "--background",
+ "--foreground",
+ "--surface",
+ "--muted",
+ "--muted-foreground",
+ "--border",
+ "--primary",
+ "--primary-foreground",
+ "--secondary",
+ "--secondary-foreground",
+ "--accent",
+ "--accent-foreground",
+ "--destructive",
+ "--success",
+ "--warning",
+ "--info",
+ "--brand",
+ "--chart-1",
+ "--chart-2",
+ "--chart-3",
+ "--chart-4",
+ "--chart-5",
+ "--radius",
+] as const;
+
+// The bridge is one line on purpose: it sits on the author's first line, so a
+// script error's line number still points at the author's own source.
+//
+// Height is measured from what the body contains — its text and its child
+// elements' boxes plus their bottom margins — not from the document box. A
+// body with `min-height: 100vh` is as tall as whatever the frame is set to, so
+// measuring the box would report the frame's own height back and grow it
+// forever. Margins are included because coming up short puts a scrollbar
+// inside the frame, while a few spare pixels are invisible.
+const BRIDGE_SCRIPT = [
+ "(function(){",
+ `var K=${JSON.stringify(HTML_BLOCK_MESSAGE_KEY)};`,
+ "function post(m){m[K]=1;try{parent.postMessage(m,'*')}catch(_){}}",
+ "function px(v){return parseFloat(v)||0}",
+ "var last=-1;",
+ "function measure(){var b=document.body;if(!b)return;var bs=getComputedStyle(b);",
+ "var range=document.createRange();range.selectNodeContents(b);var rr=range.getBoundingClientRect();",
+ "var bottom=(rr.width||rr.height)?rr.bottom:0;var kids=b.children;",
+ "for(var i=0;i<kids.length;i++){var k=kids[i];var ks=getComputedStyle(k);",
+ "if(ks.display==='none'||ks.position==='fixed')continue;var r=k.getBoundingClientRect();",
+ "if(r.width||r.height)bottom=Math.max(bottom,r.bottom+px(ks.marginBottom))}",
+ "var h=bottom?Math.ceil(bottom+(window.scrollY||0)+px(bs.paddingBottom)+px(bs.borderBottomWidth)+px(bs.marginBottom)):0;",
+ "if(h!==last){last=h;post({type:'height',height:h})}}",
+ "var failed=false;",
+ "window.addEventListener('error',function(e){if(failed)return;var t=e.target;",
+ "if(t&&t!==window&&t.tagName){if(t.tagName!=='SCRIPT')return;failed=true;",
+ "post({type:'error',message:'Failed to load '+(t.getAttribute('src')||'a script'),line:0});return}",
+ "failed=true;post({type:'error',message:String(e.message||'Script error'),line:e.lineno||0})},true);",
+ "function watch(){measure();if(typeof ResizeObserver==='function'){var o=new ResizeObserver(measure);",
+ "o.observe(document.documentElement);if(document.body)o.observe(document.body)}}",
+ "if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',watch);else watch();",
+ "window.addEventListener('load',measure)",
+ "})();",
+].join("");
+
+/** Exposed for tests. */
+export const __HTML_BLOCK_BRIDGE__ = BRIDGE_SCRIPT;
+
+const DOCTYPE_RE = /^\s*<!doctype[^>]*>/i;
+
+/**
+ * The host's theme as the sandbox receives it.
+ */
+export interface HtmlBlockTheme {
+ /** `:root` declarations for the theme tokens (and `--font-sans`). */
+ declarations: string;
+ colorScheme: "light" | "dark";
+}
+
+// A value that could close the <style> element or the rule is dropped. Token
+// values come from the app's own stylesheet, so this is a backstop only.
+const UNSAFE_CSS_VALUE = /[<>{};]/;
+
+/**
+ * Reads the theme from the host's computed style. Tokens the host does not
+ * define are skipped rather than emitted empty, so an author's own fallback in
+ * `var(--x, fallback)` still applies.
+ *
+ * Inside a block the page is the block, so `--background` carries the block's
+ * surface color: a document that paints `var(--background)` sits flush in its
+ * frame instead of showing a slightly different panel.
+ */
+export function readHtmlBlockTheme(
+ styles: Pick<CSSStyleDeclaration, "getPropertyValue" | "fontFamily" | "colorScheme">,
+): HtmlBlockTheme {
+ const declarations: string[] = [];
+ for (const name of HTML_BLOCK_THEME_TOKENS) {
+ const value = (
+ (name === "--background" && styles.getPropertyValue("--surface")) ||
+ styles.getPropertyValue(name)
+ ).trim();
+ if (value && !UNSAFE_CSS_VALUE.test(value)) declarations.push(`${name}:${value}`);
+ }
+ const fontFamily = styles.fontFamily.trim();
+ if (fontFamily && !UNSAFE_CSS_VALUE.test(fontFamily)) {
+ declarations.push(`--font-sans:${fontFamily}`);
+ }
+ const scheme = styles.colorScheme ?? "";
+ return {
+ declarations: declarations.join(";"),
+ colorScheme: /\bdark\b/.test(scheme) && !/\blight\b/.test(scheme) ? "dark" : "light",
+ };
+}
+
+const THEME_TOKEN_USE = new RegExp(
+ `var\\(\\s*(?:${[...HTML_BLOCK_THEME_TOKENS, "--font-sans"].join("|")})(?![\\w-])`,
+);
+
+/** Whether the HTML reads any theme token, which opts it into the app's scheme. */
+export function usesThemeTokens(html: string): boolean {
+ return THEME_TOKEN_USE.test(html);
+}
+
+/**
+ * The srcdoc for a ```html block: theme tokens and the bridge in front of the
+ * author's markup (after a leading doctype, which must stay first), and the
+ * fragment-navigation shim after it.
+ */
+export function buildHtmlBlockDocument(html: string, theme: HtmlBlockTheme): string {
+ const root = usesThemeTokens(html)
+ ? `${theme.declarations};color-scheme:${theme.colorScheme}`
+ : theme.declarations;
+ const prefix = `<style>:root{${root}}</style><script>${BRIDGE_SCRIPT}</script>`;
+ const doctype = DOCTYPE_RE.exec(html)?.[0];
+ const body = doctype
+ ? doctype + prefix + html.slice(doctype.length)
+ : prefix + html;
+ return withFragmentNavShim(body);
+}
+
+export type HtmlBlockMessage =
+ | { type: "height"; height: number }
+ | { type: "error"; message: string; line: number };
+
+/** Upper bound on any reported height; a runaway document stops here. */
+export const HTML_BLOCK_MAX_CONTENT_PX = 10_000;
+const MAX_ERROR_LENGTH = 500;
+
+/**
+ * Parses a bridge message. Returns null for anything that is not one; values
+ * are clamped because the sandboxed document can post whatever it likes.
+ */
+export function readHtmlBlockMessage(data: unknown): HtmlBlockMessage | null {
+ if (typeof data !== "object" || data === null) return null;
+ const record = data as Record<string, unknown>;
+ if (record[HTML_BLOCK_MESSAGE_KEY] !== 1) return null;
+ if (record.type === "height") {
+ const height = record.height;
+ if (typeof height !== "number" || !Number.isFinite(height)) return null;
+ return {
+ type: "height",
+ height: Math.min(Math.max(Math.ceil(height), 0), HTML_BLOCK_MAX_CONTENT_PX),
+ };
+ }
+ if (record.type === "error") {
+ const message = typeof record.message === "string" ? record.message : "";
+ const line = typeof record.line === "number" && Number.isFinite(record.line) ? record.line : 0;
+ return {
+ type: "error",
+ message: message.slice(0, MAX_ERROR_LENGTH),
+ line: Math.max(0, Math.floor(line)),
+ };
+ }
+ return null;
+}
+
+/**
+ * Height tracking with a guard against documents whose height follows the
+ * frame (a child sized in `vh`, say): each resize makes such a document grow by
+ * the same step, forever. Three growths in a row by the same step read as that
+ * loop, and the height stops there.
+ */
+export interface HtmlBlockHeight {
+ height: number | null;
+ step: number;
+ streak: number;
+ frozen: boolean;
+}
+
+export const INITIAL_HTML_BLOCK_HEIGHT: HtmlBlockHeight = {
+ height: null,
+ step: 0,
+ streak: 0,
+ frozen: false,
+};
+
+const RUNAWAY_STREAK = 3;
+
+export function nextHtmlBlockHeight(state: HtmlBlockHeight, reported: number): HtmlBlockHeight {
+ if (state.frozen || reported === state.height) return state;
+ if (state.height == null || reported < state.height) {
+ return { height: reported, step: 0, streak: 0, frozen: false };
+ }
+ const step = reported - state.height;
+ const streak = Math.abs(step - state.step) <= 1 ? state.streak + 1 : 1;
+ if (streak >= RUNAWAY_STREAK) return { ...state, frozen: true };
+ return { height: reported, step, streak, frozen: false };
+}
diff --git a/packages/views/editor/utils/source-hash.ts b/packages/views/editor/utils/source-hash.ts
new file mode 100644
index 0000000000..f58887fa0e
--- /dev/null
+++ b/packages/views/editor/utils/source-hash.ts
@@ -0,0 +1,13 @@
+/**
+ * DJB2 hash of a rich block's source — small, fast, and sufficient for the
+ * sessionStorage keys that remember a block's rendered size. The source text
+ * itself is too unwieldy as a key (length, special chars), and a
+ * crypto-strength hash would have to be async.
+ */
+export 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);
+}
diff --git a/packages/views/editor/utils/zoom-transform.test.ts b/packages/views/editor/utils/zoom-transform.test.ts
index 22e471cdcc..9436d7c152 100644
--- a/packages/views/editor/utils/zoom-transform.test.ts
+++ b/packages/views/editor/utils/zoom-transform.test.ts
@@ -12,6 +12,7 @@ import {
distanceBetween,
midpointOf,
panBy,
+ resizeTransform,
wheelZoomFactor,
zoomByAtCenter,
zoomToAt,
@@ -105,6 +106,32 @@ describe("clampTransform", () => {
});
});
+describe("resizeTransform", () => {
+ const content = { width: 2000, height: 1200 };
+ const narrower = { width: 680, height: 600 };
+
+ it("re-fits content that was still at the old viewport's fit", () => {
+ const fitted = computeFitTransform(content, VIEWPORT);
+ expect(resizeTransform(fitted, content, VIEWPORT, narrower)).toEqual(
+ computeFitTransform(content, narrower),
+ );
+ });
+
+ it("only clamps content the reader zoomed or panned", () => {
+ const zoomed: ZoomTransform = { scale: 1, x: -200, y: -100 };
+ expect(resizeTransform(zoomed, content, VIEWPORT, narrower)).toEqual(
+ clampTransform(zoomed, content, narrower),
+ );
+ });
+
+ it("clamps when there was no previous viewport to compare against", () => {
+ const t: ZoomTransform = { scale: 0.5, x: 0, y: 0 };
+ expect(resizeTransform(t, content, { width: 0, height: 0 }, VIEWPORT)).toEqual(
+ clampTransform(t, content, VIEWPORT),
+ );
+ });
+});
+
describe("zoomToAt", () => {
const content = { width: 1000, height: 1000 };
diff --git a/packages/views/editor/utils/zoom-transform.ts b/packages/views/editor/utils/zoom-transform.ts
index 6e3c879464..9c90aaee1f 100644
--- a/packages/views/editor/utils/zoom-transform.ts
+++ b/packages/views/editor/utils/zoom-transform.ts
@@ -143,6 +143,30 @@ export function clampTransform(
};
}
+/**
+ * The transform after the viewport resizes under the content. Content still
+ * sitting at the old viewport's fit follows the resize and re-fits — the
+ * reader never zoomed, so the fit IS their view (e.g. an info panel opening
+ * beside the stage). Anything the reader zoomed or panned only gets clamped,
+ * so their place survives.
+ */
+export function resizeTransform(
+ transform: ZoomTransform,
+ content: Size,
+ previousViewport: Size,
+ viewport: Size,
+): ZoomTransform {
+ if (hasArea(content) && hasArea(previousViewport)) {
+ const previousFit = computeFitTransform(content, previousViewport);
+ const atFit =
+ Math.abs(transform.scale - previousFit.scale) < 0.001 &&
+ Math.abs(transform.x - previousFit.x) < 0.5 &&
+ Math.abs(transform.y - previousFit.y) < 0.5;
+ if (atFit && hasArea(viewport)) return computeFitTransform(content, viewport);
+ }
+ return clampTransform(transform, content, viewport);
+}
+
/**
* Zooms to `nextScale` while pinning the content point under `anchor` (in
* viewport coordinates) to that same spot. This is what makes wheel and pinch
diff --git a/packages/views/issues/components/comment-card.test.tsx b/packages/views/issues/components/comment-card.test.tsx
index 9a26340a4e..459a29ae3d 100644
--- a/packages/views/issues/components/comment-card.test.tsx
+++ b/packages/views/issues/components/comment-card.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import type { ReactElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -16,10 +16,9 @@ vi.mock("@multica/core/api", () => ({
PreviewUnsupportedError: class extends Error {},
}));
-// HtmlAttachmentPreview (kind="html" dispatch from AttachmentBlock) reads
-// useNavigation() + useWorkspaceSlug() for the Open-in-new-tab button.
-// Mock both so the standalone-attachment-routes-to-iframe test does not
-// need the surrounding NavigationProvider / WorkspaceSlugProvider tree.
+// The attachment viewer reads useNavigation() + useWorkspaceSlug() for its
+// Open-in-new-tab button. Mock both so these tests do not need the
+// surrounding NavigationProvider / WorkspaceSlugProvider tree.
vi.mock("../../navigation", () => ({
useNavigation: () => ({
push: vi.fn(),
@@ -41,7 +40,10 @@ vi.mock("@multica/core/paths", async (importOriginal) => {
};
});
+import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";
+import { renderWithI18n } from "../../test/i18n";
import { AttachmentList } from "./comment-card";
+import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";
function renderWithQuery(ui: ReactElement) {
const qc = new QueryClient({
@@ -53,41 +55,6 @@ function renderWithQuery(ui: ReactElement) {
beforeEach(() => vi.clearAllMocks());
afterEach(() => vi.restoreAllMocks());
-describe("AttachmentList — standalone HTML attachment routes through AttachmentBlock", () => {
- // Regression pin for comment-card.tsx:152. This is the entry point
- // MUL-2330 originally regressed on: standalone HTML attachments (not
- // referenced inline in the markdown body) MUST render through
- // <AttachmentBlock> so the html+attachmentId dispatch fires. Reverting to
- // <AttachmentCard> here re-introduces the "report.html shows as a bare
- // file card row instead of the rendered chart" bug.
- it("renders an iframe (no file-card chrome) for a standalone HTML attachment", async () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart</p>",
- originalContentType: "text/html",
- });
- const attachment = {
- id: "att-1",
- url: "/uploads/report.html",
- filename: "report.html",
- content_type: "text/html",
- size_bytes: 0,
- } as any;
-
- renderWithQuery(<AttachmentList attachments={[attachment]} content="" />);
-
- const frame = await waitFor(() => {
- const f = document.querySelector("iframe") as HTMLIFrameElement | null;
- expect(f).toBeTruthy();
- return f!;
- });
- expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
- expect(frame.getAttribute("srcdoc")).toContain("<p>chart</p>");
- // AttachmentCard chrome would render the filename as visible <p> text;
- // HtmlAttachmentPreview replaces the row entirely.
- expect(screen.queryByText("report.html")).toBeNull();
- });
-});
-
describe("AttachmentList — inline attachment filtering", () => {
it("does not render a bottom attachment row when the body already has the stable file-card URL", () => {
const id = "11111111-2222-3333-4444-555555555555";
@@ -133,3 +100,99 @@ describe("AttachmentList — inline attachment filtering", () => {
expect(container.firstChild).toBeNull();
});
});
+
+describe("AttachmentList — layout (MUL-7649)", () => {
+ const file = (id: string, filename: string, content_type: string) =>
+ ({
+ id,
+ url: `/uploads/${filename}`,
+ download_url: `/uploads/${filename}`,
+ filename,
+ content_type,
+ size_bytes: 2048,
+ created_at: "2026-09-20T10:00:00Z",
+ }) as any;
+
+ function renderList(ui: ReactElement) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ return renderWithI18n(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
+ }
+
+ it("shows files as cards, not full-width rows", () => {
+ renderList(
+ <AttachmentList
+ attachments={[file("a", "notes.md", "text/markdown"), file("b", "data.csv", "text/csv")]}
+ content=""
+ />,
+ );
+ expect(screen.getByRole("button", { name: "notes.md" })).toBeTruthy();
+ expect(screen.getByText("MD · 2 KB")).toBeTruthy();
+ expect(screen.getByText("CSV · 2 KB")).toBeTruthy();
+ // The row form's Eye button is gone — the whole card opens the file.
+ expect(screen.queryByTitle("Preview")).toBeNull();
+ });
+
+ it("puts several images in one row of tiles, and keeps a lone image full size", () => {
+ const { container, unmount } = renderList(
+ <AttachmentList
+ attachments={[file("a", "a.png", "image/png"), file("b", "b.png", "image/png")]}
+ content=""
+ />,
+ );
+ expect(container.querySelectorAll(".image-tile")).toHaveLength(2);
+ unmount();
+
+ const single = renderList(
+ <AttachmentList attachments={[file("c", "c.png", "image/png")]} content="" />,
+ );
+ expect(single.container.querySelector(".image-figure")).toBeTruthy();
+ expect(single.container.querySelector(".image-tile")).toBeNull();
+ });
+
+ it("lays groups out images, then files, whatever the upload order", () => {
+ const { container } = renderList(
+ <AttachmentList
+ attachments={[
+ file("a", "notes.md", "text/markdown"),
+ file("b", "a.png", "image/png"),
+ file("c", "b.png", "image/png"),
+ ]}
+ content=""
+ />,
+ );
+ const tile = container.querySelector(".image-tile")!;
+ const card = screen.getByRole("button", { name: "notes.md" });
+ expect(tile.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
+
+ // Reverses the MUL-2330 pin. An uploaded HTML file is a deliverable, not
+ // part of the text: it is a card that opens the viewer, and its contents are
+ // not fetched to embed. HTML meant to be read in place is a ```html block.
+ it("shows a standalone HTML file as a card, not an embedded preview", () => {
+ renderList(
+ <AttachmentList
+ attachments={[file("h", "report.html", "text/html"), file("m", "notes.md", "text/markdown")]}
+ content=""
+ />,
+ );
+ expect(screen.getByRole("button", { name: "report.html" })).toBeTruthy();
+ expect(screen.getByText("HTML · 2 KB")).toBeTruthy();
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(getAttachmentTextContentMock).not.toHaveBeenCalled();
+ });
+
+ it("marks a re-uploaded file with its version on the issue page", () => {
+ const v1 = { ...file("v1", "report.md", "text/markdown"), comment_id: "c1" };
+ const v2 = { ...file("v2", "report.md", "text/markdown"), comment_id: "c2", created_at: "2026-09-21T10:00:00Z" };
+ const files = collectDeliverableFiles([
+ { id: "c1", attachments: [v1] },
+ { id: "c2", attachments: [v2] },
+ ]);
+ renderList(
+ <AttachmentVersionsProvider files={files}>
+ <AttachmentList attachments={[v2]} content="" />
+ </AttachmentVersionsProvider>,
+ );
+ expect(screen.getByText("v2")).toBeTruthy();
+ });
+});
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index a344365eca..e56695a2d7 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -44,7 +44,11 @@ import { contentReferencesAttachment } from "@multica/core/types";
import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { commentSupplementReceipts, isSupplementInFlight } from "@multica/core/issues/run-steering";
import { useConfigStore } from "@multica/core/config";
-import { selectStandaloneAttachments } from "@multica/core/attachments/image-sequence";
+import {
+ orderStandaloneAttachments,
+ selectStandaloneAttachments,
+ standaloneAttachmentGroup,
+} from "@multica/core/attachments/image-sequence";
import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/issues/stores";
import { useT } from "../../i18n";
import { CommentsFoldBar } from "./resolved-thread-bar";
@@ -54,6 +58,9 @@ import { InlineCommentRun, PlacedInlineCommentRun, useInlineCommentRunState, typ
import { EMPTY_COMMENT_RUNS, isRunFailureNotice, orderThreadWithRuns, type CommentRun, type ThreadRunSlot } from "./comment-runs";
import { descriptionPreview } from "./description-preview";
import { useCommentAnnotations } from "./use-comment-annotations";
+import { useAttachmentVersions } from "./deliverables/attachment-versions";
+import { VersionBadge } from "./deliverables/version-badge";
+import { JustifiedImageRow } from "./justified-image-row";
import { useRunCommentMotion } from "./use-run-comment-motion";
const commentActionClassName =
@@ -211,25 +218,50 @@ export function AttachmentList({
className?: string;
onRemove?: (attachmentId: string) => void;
}) {
+ const versions = useAttachmentVersions();
if (!attachments?.length) return null;
// Skip attachments whose URL (stable or legacy) is already referenced in the
// markdown content, and duplicates of the same file that are referenced.
// Shared with the image-sequence builder (MUL-5752) so the cards rendered
- // here and the images the viewer pages through can't disagree.
- const standalone = selectStandaloneAttachments(content, attachments);
+ // here and the images the viewer pages through can't disagree — as is the
+ // grouping below, so paging follows the screen (MUL-7649).
+ const standalone = orderStandaloneAttachments(
+ selectStandaloneAttachments(content, attachments),
+ );
if (!standalone.length) return null;
+ const images = standalone.filter((a) => standaloneAttachmentGroup(a) === "image");
+ const files = standalone.filter((a) => standaloneAttachmentGroup(a) === "file");
+ const render = (a: Attachment, layout: "block" | "card") => {
+ const version = versions?.get(a.id);
+ return (
+ <AttachmentRenderer
+ key={a.id}
+ attachment={{ kind: "record", attachment: a }}
+ layout={layout}
+ badge={version ? <VersionBadge version={version} /> : undefined}
+ editable={!!onRemove}
+ onDelete={onRemove ? () => onRemove(a.id) : undefined}
+ />
+ );
+ };
+
+ // A lone image keeps its full size; several form justified rows (one
+ // height per row, edge to edge). Every other file — HTML too: an uploaded
+ // file is a deliverable to open, not part of the text — is a card in a
+ // grid, not a full-width row each.
return (
<AttachmentDownloadProvider attachments={attachments}>
- <div className={cn("flex flex-col gap-1", className)}>
- {standalone.map((a) => (
- <AttachmentRenderer
- key={a.id}
- attachment={{ kind: "record", attachment: a }}
- editable={!!onRemove}
- onDelete={onRemove ? () => onRemove(a.id) : undefined}
- />
- ))}
+ <div className={cn("flex flex-col gap-2", className)}>
+ {images.length === 1 && render(images[0]!, "block")}
+ {images.length > 1 && (
+ <JustifiedImageRow items={images} renderTile={(a) => render(a, "card")} />
+ )}
+ {files.length > 0 && (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(15rem,100%),1fr))] gap-2">
+ {files.map((a) => render(a, "card"))}
+ </div>
+ )}
</div>
</AttachmentDownloadProvider>
);
diff --git a/packages/views/issues/components/deliverables/attachment-versions.tsx b/packages/views/issues/components/deliverables/attachment-versions.tsx
new file mode 100644
index 0000000000..4b227397f0
--- /dev/null
+++ b/packages/views/issues/components/deliverables/attachment-versions.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { createContext, use, useMemo, type ReactNode } from "react";
+import type { DeliverableFile } from "@multica/core/attachments/deliverables";
+
+/**
+ * Which version of its file each comment upload is (MUL-7649), so a comment's
+ * file card can say `v2` without every card re-deriving the issue's
+ * deliverables. Only files uploaded more than once are in the map; surfaces
+ * without a provider (chat) show no versions.
+ */
+const AttachmentVersionsContext = createContext<ReadonlyMap<string, number> | null>(null);
+
+export function AttachmentVersionsProvider({
+ files,
+ children,
+}: {
+ files: ReadonlyArray<DeliverableFile>;
+ children: ReactNode;
+}) {
+ const versions = useMemo(() => {
+ const map = new Map<string, number>();
+ for (const file of files) {
+ if (file.versions.length < 2) continue;
+ file.versions.forEach((attachment, i) => map.set(attachment.id, i + 1));
+ }
+ return map;
+ }, [files]);
+ return (
+ <AttachmentVersionsContext.Provider value={versions}>
+ {children}
+ </AttachmentVersionsContext.Provider>
+ );
+}
+
+/** The 1-based version of an upload, when its file has more than one. */
+export function useAttachmentVersions(): ReadonlyMap<string, number> | null {
+ return use(AttachmentVersionsContext);
+}
diff --git a/packages/views/issues/components/deliverables/deliverable-details.tsx b/packages/views/issues/components/deliverables/deliverable-details.tsx
new file mode 100644
index 0000000000..cf3f9c88f8
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverable-details.tsx
@@ -0,0 +1,357 @@
+"use client";
+
+import { useCallback, type ReactNode } from "react";
+import { Check, ChevronDown, FileText, ImageIcon, MessageSquareText } from "lucide-react";
+import {
+ findDeliverableVersion,
+ type DeliverableFile,
+} from "@multica/core/attachments/deliverables";
+import type { ImageSequenceItem } from "@multica/core/attachments/image-sequence";
+import type { Attachment, TimelineEntry } from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import { useLocale, useT, useTimeAgo } from "../../../i18n";
+import { ActorAvatar } from "../../../common/actor-avatar";
+import { formatBytes } from "../../../common/format-bytes";
+import { fileTypeLabel } from "../../../editor/utils/preview";
+import type {
+ PreviewItemDetails,
+ PreviewSequenceControls,
+} from "../../../editor";
+import { descriptionPreview } from "../description-preview";
+import { DeliverableThumbnail } from "./deliverable-thumbnail";
+
+/** Block id the issue page gives its description in the preview sequence. */
+export const DESCRIPTION_BLOCK_ID = "description";
+
+/** Where a file was posted, as the viewer's "locate" action targets it. */
+export type DeliverableOrigin =
+ | { kind: "description" }
+ | { kind: "comment"; commentId: string };
+
+/**
+ * The issue page's `describeItem` for its preview sequence: the version
+ * switcher next to the file name, the info panel, and "show in comments".
+ */
+export function useDeliverableDetails({
+ files,
+ commentById,
+ onLocate,
+}: {
+ files: ReadonlyArray<DeliverableFile>;
+ commentById: ReadonlyMap<string, TimelineEntry>;
+ onLocate: (origin: DeliverableOrigin) => void;
+}) {
+ const { t } = useT("issues");
+ return useCallback(
+ (item: ImageSequenceItem, controls: PreviewSequenceControls): PreviewItemDetails => {
+ const origin: DeliverableOrigin | null =
+ item.blockId === DESCRIPTION_BLOCK_ID
+ ? { kind: "description" }
+ : item.blockId && commentById.has(item.blockId)
+ ? { kind: "comment", commentId: item.blockId }
+ : null;
+ const deliverable = item.attachment
+ ? findDeliverableVersion(files, item.attachment.id)
+ : undefined;
+ const locateLabel =
+ origin?.kind === "description"
+ ? t(($) => $.deliverables.locate_description)
+ : t(($) => $.deliverables.locate_comment);
+ // One action for the top bar and the info panel: the viewer covers the
+ // page, so it closes before the page scrolls to the file's origin.
+ const locate = origin
+ ? () => {
+ controls.close();
+ onLocate(origin);
+ }
+ : undefined;
+
+ return {
+ titleAccessory:
+ deliverable && deliverable.file.versions.length > 1 ? (
+ <VersionSwitcher
+ file={deliverable.file}
+ version={deliverable.version}
+ controls={controls}
+ />
+ ) : undefined,
+ info: (
+ <DeliverableInfo
+ item={item}
+ controls={controls}
+ comment={origin?.kind === "comment" ? commentById.get(origin.commentId) : undefined}
+ isDescription={origin?.kind === "description"}
+ version={deliverable}
+ locateLabel={locateLabel}
+ onLocate={locate}
+ />
+ ),
+ locate: locate ? { label: locateLabel, onSelect: locate } : undefined,
+ };
+ },
+ [files, commentById, onLocate, t],
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Version switcher
+// ---------------------------------------------------------------------------
+
+function VersionSwitcher({
+ file,
+ version,
+ controls,
+}: {
+ file: DeliverableFile;
+ version: number;
+ controls: PreviewSequenceControls;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const inSession = new Set(controls.items.map((i) => i.key));
+ // Newest first, like every version picker people know.
+ const entries = file.versions.map((attachment, i) => ({ attachment, n: i + 1 })).reverse();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ className="flex shrink-0 items-center gap-0.5 rounded-xs bg-secondary px-1.5 py-0.5 text-micro font-medium tabular-nums text-muted-foreground transition-colors hover:text-foreground"
+ aria-label={t(($) => $.deliverables.version_label, {
+ version,
+ total: file.versions.length,
+ })}
+ >
+ {t(($) => $.deliverables.version_short, { version })}
+ <ChevronDown className="size-3" />
+ </button>
+ }
+ />
+ {/* Portaled out of the viewer's dark chrome, so it opts in itself. */}
+ <DropdownMenuContent className="dark min-w-56" align="start">
+ {entries.map(({ attachment, n }) => (
+ <DropdownMenuItem
+ key={attachment.id}
+ disabled={!inSession.has(attachment.id)}
+ onClick={() => controls.goTo(attachment.id)}
+ >
+ <span className="w-7 font-medium tabular-nums">
+ {t(($) => $.deliverables.version_short, { version: n })}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-caption text-muted-foreground tabular-nums">
+ {new Date(attachment.created_at).toLocaleString(locale, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ })}
+ {attachment.size_bytes > 0 ? ` · ${formatBytes(attachment.size_bytes)}` : ""}
+ </span>
+ {n === version && <Check className="size-3.5 text-foreground" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Info panel
+// ---------------------------------------------------------------------------
+
+function DeliverableInfo({
+ item,
+ controls,
+ comment,
+ isDescription,
+ version,
+ locateLabel,
+ onLocate,
+}: {
+ item: ImageSequenceItem;
+ controls: PreviewSequenceControls;
+ comment?: TimelineEntry;
+ isDescription: boolean;
+ version?: { file: DeliverableFile; version: number };
+ locateLabel: string;
+ onLocate?: () => void;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const timeAgo = useTimeAgo();
+ const { getActorName } = useActorName();
+ const attachment = item.attachment;
+
+ // Files posted in the same comment (or the description), in page order.
+ const siblings = item.blockId
+ ? controls.items.filter((other) => other.blockId === item.blockId)
+ : [];
+ const excerpt = comment?.content ? descriptionPreview(comment.content) : "";
+
+ return (
+ <div className="space-y-6 px-4 py-4">
+ {(comment || isDescription) && (
+ <InfoSection title={t(($) => $.deliverables.info_source)}>
+ <div className="space-y-2 rounded-lg bg-secondary/60 p-3">
+ {comment ? (
+ <div className="flex min-w-0 items-center gap-1.5 text-caption">
+ <ActorAvatar
+ actorType={comment.actor_type}
+ actorId={comment.actor_id}
+ name={comment.actor_name}
+ avatarUrl={comment.actor_avatar_url}
+ size="xs"
+ profileLink={false}
+ />
+ <span className="truncate font-medium">
+ {comment.actor_name ?? getActorName(comment.actor_type, comment.actor_id)}
+ </span>
+ <span
+ className="shrink-0 text-muted-foreground"
+ title={new Date(comment.created_at).toLocaleString(locale)}
+ >
+ · {timeAgo(comment.created_at)}
+ </span>
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5 text-caption font-medium">
+ <FileText className="size-3.5 text-muted-foreground" />
+ {t(($) => $.deliverables.source_description)}
+ </div>
+ )}
+ {excerpt && (
+ <p className="line-clamp-4 text-caption text-muted-foreground">{excerpt}</p>
+ )}
+ {onLocate && (
+ <button
+ type="button"
+ className="inline-flex items-center gap-1.5 rounded-md border border-input px-2 py-1 text-caption text-foreground transition-colors hover:bg-secondary"
+ onClick={onLocate}
+ >
+ <MessageSquareText className="size-3.5" />
+ {locateLabel}
+ </button>
+ )}
+ </div>
+ </InfoSection>
+ )}
+
+ {siblings.length > 1 && (
+ <InfoSection
+ title={
+ isDescription
+ ? t(($) => $.deliverables.info_siblings_description, { count: siblings.length })
+ : t(($) => $.deliverables.info_siblings_comment, { count: siblings.length })
+ }
+ >
+ <div className="grid grid-cols-4 gap-1.5">
+ {siblings.map((sibling) => {
+ const current = sibling.key === item.key;
+ return (
+ <button
+ key={sibling.key}
+ type="button"
+ className={cn(
+ "aspect-square overflow-hidden rounded-md ring-1 transition-shadow",
+ current
+ ? "ring-2 ring-foreground"
+ : "ring-border hover:ring-foreground/40",
+ )}
+ title={sibling.filename}
+ aria-label={sibling.filename}
+ aria-current={current || undefined}
+ onClick={() => controls.goTo(sibling.key)}
+ >
+ {sibling.attachment ? (
+ <DeliverableThumbnail
+ attachment={sibling.attachment}
+ showTypeLabel={false}
+ className="size-full"
+ />
+ ) : (
+ <span className="flex size-full items-center justify-center bg-muted text-muted-foreground">
+ <ImageIcon className="size-4" />
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </InfoSection>
+ )}
+
+ {attachment && (
+ <InfoSection title={t(($) => $.deliverables.info_file)}>
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 text-caption">
+ <InfoRow label={t(($) => $.deliverables.info_type)}>
+ {fileTypeLabel(attachment.filename) || attachment.content_type || "—"}
+ </InfoRow>
+ {attachment.size_bytes > 0 && (
+ <InfoRow label={t(($) => $.deliverables.info_size)}>
+ {formatBytes(attachment.size_bytes)}
+ </InfoRow>
+ )}
+ <InfoRow label={t(($) => $.deliverables.info_uploader)}>
+ <UploaderName attachment={attachment} />
+ </InfoRow>
+ <InfoRow label={t(($) => $.deliverables.info_uploaded_at)}>
+ {new Date(attachment.created_at).toLocaleString(locale, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ })}
+ </InfoRow>
+ {version && version.file.versions.length > 1 && (
+ <InfoRow label={t(($) => $.deliverables.info_version)}>
+ {t(($) => $.deliverables.version_of, {
+ version: version.version,
+ total: version.file.versions.length,
+ })}
+ </InfoRow>
+ )}
+ </dl>
+ </InfoSection>
+ )}
+ </div>
+ );
+}
+
+function InfoSection({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section>
+ <h3 className="mb-2 text-micro font-medium text-muted-foreground">{title}</h3>
+ {children}
+ </section>
+ );
+}
+
+function InfoRow({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <>
+ <dt className="text-muted-foreground">{label}</dt>
+ <dd className="min-w-0 truncate">{children}</dd>
+ </>
+ );
+}
+
+function UploaderName({ attachment }: { attachment: Attachment }) {
+ const { getActorName } = useActorName();
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1.5 align-middle">
+ <ActorAvatar
+ actorType={attachment.uploader_type}
+ actorId={attachment.uploader_id}
+ size="xs"
+ profileLink={false}
+ />
+ <span className="truncate">
+ {getActorName(attachment.uploader_type, attachment.uploader_id)}
+ </span>
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/deliverables/deliverable-kind.ts b/packages/views/issues/components/deliverables/deliverable-kind.ts
new file mode 100644
index 0000000000..74c123efab
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverable-kind.ts
@@ -0,0 +1,24 @@
+import { getPreviewKind } from "../../../editor/utils/preview";
+import { isDocumentFile } from "../../../editor/utils/file-icon";
+
+/** The overview's filters. Every file lands in exactly one. */
+export type DeliverableCategory = "image" | "document" | "video" | "other";
+
+export const DELIVERABLE_CATEGORIES: readonly DeliverableCategory[] = [
+ "image",
+ "document",
+ "video",
+ "other",
+];
+
+// Data (CSV, JSON) and code are "other" even though the viewer shows them as
+// text: nobody filters for "documents" to find a migration script.
+export function deliverableCategory(
+ contentType: string,
+ filename: string,
+): DeliverableCategory {
+ const kind = getPreviewKind(contentType, filename);
+ if (kind === "image") return "image";
+ if (kind === "video") return "video";
+ return isDocumentFile(contentType, filename) ? "document" : "other";
+}
diff --git a/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx
new file mode 100644
index 0000000000..8beb245648
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { useState } from "react";
+import type { Attachment } from "@multica/core/types";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
+import { cn } from "@multica/ui/lib/utils";
+import { useResignedInlineMedia } from "../../../editor/hooks/use-inline-media-url";
+import { fileTypeLabel, getPreviewKind } from "../../../editor/utils/preview";
+import { fileIcon } from "../../../editor/utils/file-icon";
+
+/**
+ * A file's face in a grid or strip: the image itself for images, otherwise
+ * its type icon and extension. Fills its box — the caller sizes it.
+ */
+export function DeliverableThumbnail({
+ attachment,
+ showTypeLabel = true,
+ className,
+}: {
+ attachment: Attachment;
+ /** The extension under the icon; off where the tile is too small for it. */
+ showTypeLabel?: boolean;
+ className?: string;
+}) {
+ if (getPreviewKind(attachment.content_type, attachment.filename) === "image") {
+ return <ImageThumbnail attachment={attachment} className={className} />;
+ }
+ return (
+ <FileFace
+ attachment={attachment}
+ showTypeLabel={showTypeLabel}
+ className={className}
+ />
+ );
+}
+
+function FileFace({
+ attachment,
+ showTypeLabel,
+ className,
+}: {
+ attachment: Attachment;
+ showTypeLabel: boolean;
+ className?: string;
+}) {
+ const Icon = fileIcon(attachment.content_type, attachment.filename);
+ const label = fileTypeLabel(attachment.filename);
+ return (
+ <div
+ className={cn(
+ "flex flex-col items-center justify-center gap-1.5 bg-muted text-muted-foreground",
+ className,
+ )}
+ >
+ <Icon className="size-5" />
+ {showTypeLabel && label && (
+ <span className="text-micro font-medium tracking-wide">{label}</span>
+ )}
+ </div>
+ );
+}
+
+// Loads the original — there is no thumbnail endpoint yet — so callers keep
+// these few (the sidebar shows three) or lazy (the overview's grid).
+function ImageThumbnail({
+ attachment,
+ className,
+}: {
+ attachment: Attachment;
+ className?: string;
+}) {
+ const picked =
+ attachment.download_url || attachment.markdown_url || attachment.url;
+ const { url, pending } = useResignedInlineMedia(
+ attachment.id,
+ resolvePublicFileUrl(picked) ?? picked,
+ true,
+ );
+ const [failedUrl, setFailedUrl] = useState<string | null>(null);
+
+ if (pending || !url || failedUrl === url) {
+ return (
+ <FileFace attachment={attachment} showTypeLabel={false} className={className} />
+ );
+ }
+ return (
+ <img
+ src={url}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ draggable={false}
+ onError={() => setFailedUrl(url)}
+ className={cn("bg-muted object-cover", className)}
+ />
+ );
+}
diff --git a/packages/views/issues/components/deliverables/deliverables-overview.tsx b/packages/views/issues/components/deliverables/deliverables-overview.tsx
new file mode 100644
index 0000000000..b09e9ce986
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverables-overview.tsx
@@ -0,0 +1,367 @@
+"use client";
+
+import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
+import { LayoutGrid, MessageSquareText, X } from "lucide-react";
+import type { DeliverableFile } from "@multica/core/attachments/deliverables";
+import type { TimelineEntry } from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
+import { useLocale, useT, useTimeAgo } from "../../../i18n";
+import { ActorAvatar } from "../../../common/actor-avatar";
+import { formatBytes } from "../../../common/format-bytes";
+import { SegmentedToggle } from "../../../common/segmented-toggle";
+import { usePreviewSequence } from "../../../editor";
+import { fileTypeLabel } from "../../../editor/utils/preview";
+import { useImmersiveMode } from "../../../platform";
+import type { DeliverableOrigin } from "./deliverable-details";
+import {
+ DELIVERABLE_CATEGORIES,
+ deliverableCategory,
+ type DeliverableCategory,
+} from "./deliverable-kind";
+import { DeliverableThumbnail } from "./deliverable-thumbnail";
+import { VersionBadge } from "./version-badge";
+import { useOpenAttachment } from "./use-open-attachment";
+
+type Filter = "all" | DeliverableCategory;
+
+// Same desktop window-chrome contract as the attachment viewer: the overlay
+// covers the title bar's drag region, so it is `no-drag` itself, its header
+// drags the window, and the header's controls opt back out.
+const NO_DRAG = { WebkitAppRegion: "no-drag" } as CSSProperties;
+const DRAG = { WebkitAppRegion: "drag" } as CSSProperties;
+
+interface FileGroup {
+ commentId: string;
+ comment?: TimelineEntry;
+ files: DeliverableFile[];
+}
+
+/**
+ * Every deliverable of the issue on one dark stage (MUL-7649), opened from
+ * the sidebar's "view all" and from the viewer's grid button (`G`).
+ *
+ * Files grouped by the comment that posted them, in page order, each group
+ * one click from that comment. Files show their latest version only, so the
+ * count here always equals the sidebar's.
+ *
+ * A full-window Dialog: the primitive owns focus (moved in on open, trapped
+ * while open, returned to the opener on close) and Escape; this only restyles
+ * the popup to cover the window.
+ */
+export function DeliverablesOverview({
+ open,
+ onClose,
+ identifier,
+ files,
+ commentById,
+ onLocate,
+ returnKey,
+}: {
+ open: boolean;
+ onClose: () => void;
+ identifier: string;
+ files: ReadonlyArray<DeliverableFile>;
+ commentById: ReadonlyMap<string, TimelineEntry>;
+ onLocate: (origin: DeliverableOrigin) => void;
+ /** The file the viewer was showing when it opened this; `G` goes back to it. */
+ returnKey: string | null;
+}) {
+ useImmersiveMode(open);
+ const { open: openAttachment, modal } = useOpenAttachment();
+ const { openAt } = usePreviewSequence();
+ const onReturn = useMemo(
+ () =>
+ returnKey
+ ? () => {
+ onClose();
+ openAt(returnKey);
+ }
+ : undefined,
+ [returnKey, onClose, openAt],
+ );
+
+ useEffect(() => {
+ if (!open || !onReturn) return;
+ const handler = (e: KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (e.key.toLowerCase() === "g") {
+ e.preventDefault();
+ onReturn();
+ }
+ };
+ document.addEventListener("keydown", handler);
+ return () => document.removeEventListener("keydown", handler);
+ }, [open, onReturn]);
+
+ return (
+ <>
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ style={NO_DRAG}
+ className="dark top-0 left-0 flex h-dvh max-h-none w-screen max-w-none translate-x-0 translate-y-0 flex-col gap-0 overflow-hidden rounded-none bg-black/95 p-0 text-foreground shadow-none ring-0 backdrop-blur-xl sm:max-w-none"
+ >
+ <OverviewBody
+ identifier={identifier}
+ files={files}
+ commentById={commentById}
+ onClose={onClose}
+ onOpenFile={(file) => {
+ onClose();
+ openAttachment(file.latest);
+ }}
+ onLocate={(origin) => {
+ onClose();
+ onLocate(origin);
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ {modal}
+ </>
+ );
+}
+
+function OverviewBody({
+ identifier,
+ files,
+ commentById,
+ onClose,
+ onOpenFile,
+ onLocate,
+}: {
+ identifier: string;
+ files: ReadonlyArray<DeliverableFile>;
+ commentById: ReadonlyMap<string, TimelineEntry>;
+ onClose: () => void;
+ onOpenFile: (file: DeliverableFile) => void;
+ onLocate: (origin: DeliverableOrigin) => void;
+}) {
+ const { t } = useT("issues");
+ const [filter, setFilter] = useState<Filter>("all");
+ const count = files.length;
+
+ const categoryByKey = useMemo(
+ () =>
+ new Map(
+ files.map((f) => [f.key, deliverableCategory(f.latest.content_type, f.latest.filename)]),
+ ),
+ [files],
+ );
+ const counts = useMemo(() => {
+ const c: Record<DeliverableCategory, number> = { image: 0, document: 0, video: 0, other: 0 };
+ for (const category of categoryByKey.values()) c[category] += 1;
+ return c;
+ }, [categoryByKey]);
+
+ // Groups in page order: by when the posting comment was written.
+ const groups = useMemo(() => {
+ const byComment = new Map<string, FileGroup>();
+ for (const file of files) {
+ if (filter !== "all" && categoryByKey.get(file.key) !== filter) continue;
+ const commentId = file.latest.comment_id ?? "";
+ let group = byComment.get(commentId);
+ if (!group) {
+ group = { commentId, comment: commentById.get(commentId), files: [] };
+ byComment.set(commentId, group);
+ }
+ group.files.push(file);
+ }
+ const startedAt = (g: FileGroup) =>
+ Date.parse(g.comment?.created_at ?? g.files[g.files.length - 1]!.latest.created_at);
+ const list = [...byComment.values()].sort((a, b) => startedAt(a) - startedAt(b));
+ // `files` is newest first; inside a group read them in upload order.
+ for (const group of list) group.files.reverse();
+ return list;
+ }, [files, filter, categoryByKey, commentById]);
+
+ const totalBytes = files.reduce((sum, f) => sum + Math.max(0, f.latest.size_bytes), 0);
+
+ const categoryLabels: Record<DeliverableCategory, string> = {
+ image: t(($) => $.deliverables.filter_image),
+ document: t(($) => $.deliverables.filter_document),
+ video: t(($) => $.deliverables.filter_video),
+ other: t(($) => $.deliverables.filter_misc),
+ };
+ const filterOptions: ReadonlyArray<readonly [Filter, ReactNode]> = [
+ ["all", <FilterLabel key="all" label={t(($) => $.deliverables.filter_all)} count={count} />],
+ ...DELIVERABLE_CATEGORIES.map(
+ (category) =>
+ [
+ category,
+ <FilterLabel key={category} label={categoryLabels[category]} count={counts[category]} />,
+ ] as const,
+ ),
+ ];
+
+ return (
+ <>
+ {/* Three columns keep the filters centered on the window; on a phone
+ they drop to a row of their own under the title. */}
+ <header
+ className="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 py-2 pl-3 pr-2 sm:h-14 sm:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] sm:py-0"
+ style={DRAG}
+ >
+ <div className="flex min-w-0 items-center gap-2.5">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground">
+ <LayoutGrid className="size-4" />
+ </span>
+ <div className="min-w-0">
+ <DialogTitle className="truncate text-body leading-(--text-body--line-height) font-medium">
+ {t(($) => $.deliverables.overview_title, { identifier })}
+ </DialogTitle>
+ <p className="truncate text-caption text-muted-foreground tabular-nums">
+ {totalBytes > 0
+ ? t(($) => $.deliverables.overview_summary_with_size, {
+ count,
+ size: formatBytes(totalBytes),
+ })
+ : t(($) => $.deliverables.overview_summary, { count })}
+ </p>
+ </div>
+ </div>
+ <div
+ className="col-span-2 row-start-2 justify-self-center sm:col-span-1 sm:row-start-auto"
+ style={NO_DRAG}
+ >
+ <SegmentedToggle value={filter} options={filterOptions} onChange={setFilter} />
+ </div>
+ <div className="flex items-center justify-self-end" style={NO_DRAG}>
+ <button
+ type="button"
+ className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ title={t(($) => $.deliverables.overview_close)}
+ aria-label={t(($) => $.deliverables.overview_close)}
+ onClick={onClose}
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 pb-10 pt-4 sm:px-16">
+ {groups.length === 0 ? (
+ <p className="pt-24 text-center text-body text-muted-foreground">
+ {t(($) => $.deliverables.overview_empty)}
+ </p>
+ ) : (
+ <div className="space-y-10">
+ {groups.map((group) => (
+ <CommentGroup
+ key={group.commentId}
+ group={group}
+ onOpenFile={onOpenFile}
+ onLocate={
+ group.comment
+ ? () => onLocate({ kind: "comment", commentId: group.commentId })
+ : undefined
+ }
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
+function FilterLabel({ label, count }: { label: string; count: number }) {
+ return (
+ <span className="inline-flex items-center gap-1.5 px-1">
+ {label}
+ <span className="tabular-nums text-muted-foreground">{count}</span>
+ </span>
+ );
+}
+
+function CommentGroup({
+ group,
+ onOpenFile,
+ onLocate,
+}: {
+ group: FileGroup;
+ onOpenFile: (file: DeliverableFile) => void;
+ onLocate?: () => void;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const timeAgo = useTimeAgo();
+ const { getActorName } = useActorName();
+ const first = group.files[0]!.latest;
+ // The comment names its author; without it (not loaded) the uploader stands in.
+ const actorType = group.comment?.actor_type ?? first.uploader_type;
+ const actorId = group.comment?.actor_id ?? first.uploader_id;
+ const name = group.comment?.actor_name ?? getActorName(actorType, actorId);
+ const at = group.comment?.created_at ?? first.created_at;
+
+ return (
+ <section aria-label={t(($) => $.deliverables.group_comment_by, { name })}>
+ <div className="mb-3 flex items-center gap-2">
+ <ActorAvatar
+ actorType={actorType}
+ actorId={actorId}
+ name={group.comment?.actor_name}
+ avatarUrl={group.comment?.actor_avatar_url}
+ size="sm"
+ profileLink={false}
+ />
+ <h2 className="min-w-0 truncate text-body font-medium">
+ {t(($) => $.deliverables.group_comment_by, { name })}
+ </h2>
+ <span
+ className="shrink-0 text-caption text-muted-foreground"
+ title={new Date(at).toLocaleString(locale)}
+ >
+ · {timeAgo(at)}
+ </span>
+ {onLocate && (
+ <button
+ type="button"
+ className="ml-auto inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-caption text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ onClick={onLocate}
+ >
+ <MessageSquareText className="size-3.5" />
+ {t(($) => $.deliverables.locate_comment)}
+ </button>
+ )}
+ </div>
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-x-4 gap-y-5">
+ {group.files.map((file) => (
+ <FileTile key={file.key} file={file} onOpen={() => onOpenFile(file)} />
+ ))}
+ </div>
+ </section>
+ );
+}
+
+function FileTile({ file, onOpen }: { file: DeliverableFile; onOpen: () => void }) {
+ const { latest } = file;
+ const meta = [
+ fileTypeLabel(latest.filename),
+ latest.size_bytes > 0 ? formatBytes(latest.size_bytes) : "",
+ ].filter(Boolean);
+ return (
+ <button type="button" className="group min-w-0 text-left" onClick={onOpen} title={latest.filename}>
+ <span className="block aspect-[16/10] overflow-hidden rounded-lg ring-1 ring-border transition-shadow group-hover:ring-foreground/40 group-focus-visible:ring-2 group-focus-visible:ring-ring">
+ <DeliverableThumbnail attachment={latest} className="size-full" />
+ </span>
+ <span className="mt-2 flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-body">{latest.filename}</span>
+ {file.versions.length > 1 && (
+ <VersionBadge version={file.versions.length} className="bg-secondary" />
+ )}
+ </span>
+ {meta.length > 0 && (
+ <span className="block text-caption text-muted-foreground tabular-nums">
+ {meta.join(" · ")}
+ </span>
+ )}
+ </button>
+ );
+}
diff --git a/packages/views/issues/components/deliverables/deliverables-section.tsx b/packages/views/issues/components/deliverables/deliverables-section.tsx
new file mode 100644
index 0000000000..3ae03fab7b
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverables-section.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronRight, LayoutGrid } from "lucide-react";
+import type { DeliverableFile } from "@multica/core/attachments/deliverables";
+import { useT } from "../../../i18n";
+import { formatBytes } from "../../../common/format-bytes";
+import { fileIcon } from "../../../editor/utils/file-icon";
+import { getPreviewKind } from "../../../editor/utils/preview";
+import { DeliverableThumbnail } from "./deliverable-thumbnail";
+import { useOpenAttachment } from "./use-open-attachment";
+import { VersionBadge } from "./version-badge";
+
+// The sidebar is a summary, not the list: the newest few of each, and the
+// overview for the rest.
+const RECENT_IMAGES = 3;
+const RECENT_FILES = 4;
+
+/**
+ * "Deliverables" in the issue sidebar (MUL-7649): the files this issue's
+ * comments delivered, as a whole — not grouped by run; each comment still
+ * shows its own files. Pull requests keep their own section above: linking
+ * one and PR auto-complete are issue workflow, not output. Renders nothing
+ * until a comment delivers a file.
+ */
+export function DeliverablesSection({
+ files,
+ onOpenOverview,
+}: {
+ files: ReadonlyArray<DeliverableFile>;
+ onOpenOverview: () => void;
+}) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(true);
+ const { open: openAttachment, modal } = useOpenAttachment();
+
+ if (files.length === 0) return null;
+
+ const images: DeliverableFile[] = [];
+ const others: DeliverableFile[] = [];
+ for (const file of files) {
+ const isImage =
+ getPreviewKind(file.latest.content_type, file.latest.filename) === "image";
+ if (isImage && images.length < RECENT_IMAGES) images.push(file);
+ else if (!isImage && others.length < RECENT_FILES) others.push(file);
+ }
+
+ return (
+ <div>
+ <button
+ type="button"
+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${open ? "" : "text-muted-foreground hover:text-foreground"}`}
+ onClick={() => setOpen(!open)}
+ aria-expanded={open}
+ >
+ {t(($) => $.deliverables.section_title)}{" "}
+ <span className="rounded-xs bg-muted px-1 text-micro font-medium tabular-nums text-muted-foreground">
+ {files.length}
+ </span>
+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${open ? "rotate-90" : ""}`} />
+ </button>
+ {open && (
+ <div className="pl-2">
+ {images.length > 0 && (
+ <div className="mb-1.5 grid grid-cols-3 gap-1.5">
+ {images.map((file) => (
+ <button
+ key={file.key}
+ type="button"
+ className="relative aspect-[4/3] overflow-hidden rounded-md ring-1 ring-border transition-shadow hover:ring-foreground/25 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ title={file.latest.filename}
+ aria-label={versionedName(file, t)}
+ onClick={() => openAttachment(file.latest)}
+ >
+ <DeliverableThumbnail
+ attachment={file.latest}
+ showTypeLabel={false}
+ className="size-full"
+ />
+ </button>
+ ))}
+ </div>
+ )}
+ {others.map((file) => (
+ <FileRow
+ key={file.key}
+ file={file}
+ onOpen={() => openAttachment(file.latest)}
+ />
+ ))}
+ <button
+ type="button"
+ className="mt-0.5 flex w-[calc(100%+1rem)] -mx-2 items-center gap-2 rounded-md px-2 py-1 text-left text-caption text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
+ onClick={onOpenOverview}
+ >
+ <LayoutGrid className="size-3.5 shrink-0" />
+ {t(($) => $.deliverables.view_all, { count: files.length })}
+ </button>
+ </div>
+ )}
+ {modal}
+ </div>
+ );
+}
+
+type IssuesT = ReturnType<typeof useT<"issues">>["t"];
+
+function versionedName(file: DeliverableFile, t: IssuesT): string {
+ return file.versions.length > 1
+ ? t(($) => $.deliverables.name_with_version, {
+ name: file.latest.filename,
+ version: file.versions.length,
+ })
+ : file.latest.filename;
+}
+
+function FileRow({ file, onOpen }: { file: DeliverableFile; onOpen: () => void }) {
+ const { t } = useT("issues");
+ const { latest } = file;
+ const Icon = fileIcon(latest.content_type, latest.filename);
+ return (
+ <button
+ type="button"
+ className="group flex w-[calc(100%+1rem)] -mx-2 items-center gap-2 rounded-md px-2 py-1 text-left text-caption transition-colors hover:bg-accent/50"
+ title={latest.filename}
+ aria-label={versionedName(file, t)}
+ onClick={onOpen}
+ >
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate">{latest.filename}</span>
+ {file.versions.length > 1 && <VersionBadge version={file.versions.length} />}
+ <span className="ml-auto shrink-0 pl-2 text-micro tabular-nums text-muted-foreground">
+ {latest.size_bytes > 0 ? formatBytes(latest.size_bytes) : null}
+ </span>
+ </button>
+ );
+}
diff --git a/packages/views/issues/components/deliverables/deliverables.test.tsx b/packages/views/issues/components/deliverables/deliverables.test.tsx
new file mode 100644
index 0000000000..59b57daa7d
--- /dev/null
+++ b/packages/views/issues/components/deliverables/deliverables.test.tsx
@@ -0,0 +1,305 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { useState, type ReactNode } from "react";
+import {
+ collectDeliverableFiles,
+ type DeliverableFile,
+} from "@multica/core/attachments/deliverables";
+import type { Attachment, TimelineEntry } from "@multica/core/types";
+import { renderWithI18n } from "../../../test/i18n";
+
+const { openAtMock, tryOpenMock, downloadMock } = vi.hoisted(() => ({
+ openAtMock: vi.fn((_key: string) => true),
+ tryOpenMock: vi.fn(() => false),
+ downloadMock: vi.fn(),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getActorName: (type: string, id: string) => (type === "agent" ? `Agent ${id}` : `Member ${id}`),
+ }),
+}));
+
+vi.mock("../../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+
+vi.mock("../../../editor", () => ({
+ usePreviewSequence: () => ({ openAt: openAtMock }),
+ useAttachmentPreview: () => ({ open: vi.fn(), tryOpen: tryOpenMock, modal: null }),
+ useDownloadAttachment: () => downloadMock,
+}));
+
+vi.mock("../../../editor/hooks/use-inline-media-url", () => ({
+ useResignedInlineMedia: (_id: string | undefined, url: string) => ({ url, pending: false }),
+}));
+
+vi.mock("@multica/core/workspace/avatar-url", () => ({
+ resolvePublicFileUrl: (url: string) => url,
+}));
+
+vi.mock("../../../platform", () => ({ useImmersiveMode: () => {} }));
+
+import { DeliverablesSection } from "./deliverables-section";
+import { DeliverablesOverview } from "./deliverables-overview";
+import { useDeliverableDetails, type DeliverableOrigin } from "./deliverable-details";
+
+function attachment(over: Partial<Attachment> & { id: string }): Attachment {
+ return {
+ workspace_id: "ws-1",
+ issue_id: "issue-1",
+ comment_id: "c-1",
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "agent",
+ uploader_id: "lambda",
+ filename: "report.md",
+ url: `https://cdn.example.test/${over.id}`,
+ download_url: `https://cdn.example.test/${over.id}?sig=1`,
+ markdown_url: `https://cdn.example.test/${over.id}`,
+ content_type: "text/markdown",
+ size_bytes: 6 * 1024,
+ created_at: "2026-09-20T10:00:00Z",
+ ...over,
+ };
+}
+
+function comment(
+ id: string,
+ attachments: Attachment[],
+ over: Partial<TimelineEntry> = {},
+): TimelineEntry {
+ return {
+ type: "comment",
+ id,
+ actor_type: "agent",
+ actor_id: "lambda",
+ actor_name: "Lambda",
+ created_at: attachments[0]?.created_at ?? "2026-09-20T10:00:00Z",
+ content: "Done — see the files.",
+ attachments: attachments.map((a) => ({ ...a, comment_id: id })),
+ ...over,
+ };
+}
+
+// A run posted a screenshot and a report, a later run re-uploaded the
+// report next to a CSV: four uploads, three deliverables.
+const SHOT = attachment({
+ id: "shot",
+ filename: "settings.png",
+ content_type: "image/png",
+ size_bytes: 412 * 1024,
+ created_at: "2026-09-20T10:00:00Z",
+});
+const REPORT_V1 = attachment({ id: "report-1", created_at: "2026-09-20T10:00:01Z" });
+const REPORT_V2 = attachment({ id: "report-2", created_at: "2026-09-21T09:00:00Z" });
+const CSV = attachment({
+ id: "csv",
+ filename: "latency.csv",
+ content_type: "text/csv",
+ size_bytes: 18 * 1024,
+ created_at: "2026-09-21T09:00:01Z",
+});
+const TIMELINE: TimelineEntry[] = [
+ comment("c-1", [SHOT, REPORT_V1]),
+ comment("c-2", [REPORT_V2, CSV], { created_at: "2026-09-21T09:00:00Z" }),
+];
+const FILES = collectDeliverableFiles(TIMELINE);
+
+function withQuery(children: ReactNode) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+}
+
+function renderSection(files: ReadonlyArray<DeliverableFile>, onOpenOverview = vi.fn()) {
+ return renderWithI18n(
+ withQuery(<DeliverablesSection files={files} onOpenOverview={onOpenOverview} />),
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("DeliverablesSection", () => {
+ it("renders nothing while nothing has been delivered", () => {
+ const { container } = renderSection([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("shows the latest version of each file and the total", () => {
+ renderSection(FILES);
+
+ expect(screen.getByRole("button", { name: /Deliverables/ })).toHaveTextContent("3");
+ // One row for the report, marked as its second version.
+ const report = screen.getByRole("button", { name: "report.md, version 2" });
+ expect(report).toHaveTextContent("v2");
+ expect(screen.getAllByTitle("report.md")).toHaveLength(1);
+ expect(screen.getByRole("button", { name: "settings.png" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "View all 3 deliverables" })).toBeInTheDocument();
+ });
+
+ it("opens the latest version in the page's viewer", () => {
+ renderSection(FILES);
+ fireEvent.click(screen.getByRole("button", { name: "report.md, version 2" }));
+ expect(openAtMock).toHaveBeenCalledWith("report-2");
+ });
+
+ it("downloads a file neither the sequence nor the viewer can open", () => {
+ openAtMock.mockReturnValueOnce(false);
+ renderSection(
+ collectDeliverableFiles([
+ comment("c-9", [
+ attachment({ id: "zip", filename: "bundle.zip", content_type: "application/zip" }),
+ ]),
+ ]),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "bundle.zip" }));
+ expect(tryOpenMock).toHaveBeenCalled();
+ expect(downloadMock).toHaveBeenCalledWith("zip");
+ });
+
+ it("opens the overview from view all", () => {
+ const onOpenOverview = vi.fn();
+ renderSection(FILES, onOpenOverview);
+ fireEvent.click(screen.getByRole("button", { name: "View all 3 deliverables" }));
+ expect(onOpenOverview).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("DeliverablesOverview", () => {
+ const commentById = new Map(TIMELINE.map((entry) => [entry.id, entry]));
+
+ function renderOverview(props: Partial<Parameters<typeof DeliverablesOverview>[0]> = {}) {
+ const onClose = vi.fn();
+ const onLocate = vi.fn();
+ renderWithI18n(
+ withQuery(
+ <DeliverablesOverview
+ open
+ onClose={onClose}
+ identifier="MUL-7588"
+ files={FILES}
+ commentById={commentById}
+ onLocate={onLocate}
+ returnKey={null}
+ {...props}
+ />,
+ ),
+ );
+ return { onClose, onLocate };
+ }
+
+ it("counts exactly what the sidebar counts", () => {
+ renderOverview();
+ const dialog = screen.getByRole("dialog", { name: "MUL-7588 deliverables" });
+ expect(within(dialog).getByText(/^3 deliverables/)).toBeInTheDocument();
+ expect(within(dialog).getByRole("button", { name: /^All\s*3$/ })).toBeInTheDocument();
+ // One group per posting comment; the report sits with its v2.
+ const groups = within(dialog).getAllByRole("region", { name: "Comment by Lambda" });
+ expect(groups).toHaveLength(2);
+ expect(within(groups[0]!).getByTitle("settings.png")).toBeInTheDocument();
+ expect(within(groups[1]!).getByTitle("report.md")).toHaveTextContent("v2");
+ });
+
+ it("filters by kind", () => {
+ renderOverview();
+ fireEvent.click(screen.getByRole("button", { name: /^Images\s*1$/ }));
+ expect(screen.getByTitle("settings.png")).toBeInTheDocument();
+ expect(screen.queryByTitle("report.md")).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: /^Videos\s*0$/ }));
+ expect(screen.getByText("No deliverables of this type.")).toBeInTheDocument();
+ });
+
+ it("opens a file and locates a comment, closing itself first", () => {
+ const { onClose, onLocate } = renderOverview();
+ fireEvent.click(screen.getByTitle("latency.csv"));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(openAtMock).toHaveBeenCalledWith("csv");
+
+ const [, secondGroup] = screen.getAllByRole("region", { name: "Comment by Lambda" });
+ fireEvent.click(within(secondGroup!).getByRole("button", { name: "Show in comments" }));
+ expect(onClose).toHaveBeenCalledTimes(2);
+ expect(onLocate).toHaveBeenCalledWith({ kind: "comment", commentId: "c-2" });
+ });
+
+ it("goes back to the viewer's file with G, and closes with Escape", () => {
+ const { onClose } = renderOverview({ returnKey: "shot" });
+ act(() => {
+ fireEvent.keyDown(document, { key: "g" });
+ });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(openAtMock).toHaveBeenCalledWith("shot");
+
+ act(() => {
+ fireEvent.keyDown(document, { key: "Escape" });
+ });
+ expect(onClose).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("DeliverablesOverview focus", () => {
+ // A full-window overlay the keyboard can't reach is not a dialog: focus
+ // must move in when it opens and go back to the opener when it closes.
+ it("takes focus when it opens and returns it to the opener on close", async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ View all
+ </button>
+ <DeliverablesOverview
+ open={open}
+ onClose={() => setOpen(false)}
+ identifier="MUL-7588"
+ files={FILES}
+ commentById={new Map(TIMELINE.map((entry) => [entry.id, entry]))}
+ onLocate={vi.fn()}
+ returnKey={null}
+ />
+ </>
+ );
+ }
+ renderWithI18n(withQuery(<Harness />));
+ const opener = screen.getByRole("button", { name: "View all" });
+ opener.focus();
+ fireEvent.click(opener);
+
+ const dialog = await screen.findByRole("dialog", { name: "MUL-7588 deliverables" });
+ await waitFor(() => expect(dialog.contains(document.activeElement)).toBe(true));
+
+ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(opener));
+ });
+});
+
+describe("useDeliverableDetails", () => {
+ // The viewer covers the page, so "Show in comments" in the info panel has
+ // to close it first, exactly like the same action in the top bar.
+ it("closes the viewer before locating, from the info panel and the top bar", () => {
+ const calls: string[] = [];
+ const close = vi.fn(() => calls.push("close"));
+ const onLocate = vi.fn((origin: DeliverableOrigin) => calls.push(`locate:${JSON.stringify(origin)}`));
+ let locateFromTopBar: (() => void) | undefined;
+
+ function Harness() {
+ const describe = useDeliverableDetails({
+ files: FILES,
+ commentById: new Map(TIMELINE.map((entry) => [entry.id, entry])),
+ onLocate,
+ });
+ const item = { key: "csv", url: CSV.url, filename: CSV.filename, attachment: CSV, imageByConstruction: false, blockId: "c-2" };
+ const details = describe(item, { items: [item], goTo: () => true, close });
+ locateFromTopBar = details.locate?.onSelect;
+ return <>{details.info}</>;
+ }
+ renderWithI18n(withQuery(<Harness />));
+
+ fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
+ locateFromTopBar?.();
+ const located = `locate:${JSON.stringify({ kind: "comment", commentId: "c-2" })}`;
+ expect(calls).toEqual(["close", located, "close", located]);
+ });
+});
diff --git a/packages/views/issues/components/deliverables/use-open-attachment.ts b/packages/views/issues/components/deliverables/use-open-attachment.ts
new file mode 100644
index 0000000000..1bf0c840a3
--- /dev/null
+++ b/packages/views/issues/components/deliverables/use-open-attachment.ts
@@ -0,0 +1,31 @@
+"use client";
+
+import { useCallback } from "react";
+import type { Attachment } from "@multica/core/types";
+import {
+ useAttachmentPreview,
+ useDownloadAttachment,
+ usePreviewSequence,
+} from "../../../editor";
+
+/**
+ * Open a file in the issue's viewer at its place in the page's sequence. A
+ * file the sequence doesn't hold opens on its own, and one the viewer can't
+ * show downloads. Render `modal` for the on-its-own case.
+ */
+export function useOpenAttachment() {
+ const sequence = usePreviewSequence();
+ const preview = useAttachmentPreview();
+ const download = useDownloadAttachment();
+ const { openAt } = sequence;
+ const { tryOpen } = preview;
+ const open = useCallback(
+ (attachment: Attachment) => {
+ if (openAt(attachment.id)) return;
+ if (tryOpen({ kind: "full", attachment })) return;
+ download(attachment.id);
+ },
+ [openAt, tryOpen, download],
+ );
+ return { open, modal: preview.modal };
+}
diff --git a/packages/views/issues/components/deliverables/version-badge.tsx b/packages/views/issues/components/deliverables/version-badge.tsx
new file mode 100644
index 0000000000..e1c975b567
--- /dev/null
+++ b/packages/views/issues/components/deliverables/version-badge.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../../i18n";
+
+/**
+ * `v2` beside a file that was uploaded more than once. Decorative: the
+ * accessible name of whatever it sits in carries the version in words.
+ */
+export function VersionBadge({
+ version,
+ className,
+}: {
+ version: number;
+ className?: string;
+}) {
+ const { t } = useT("issues");
+ return (
+ <span
+ className={cn(
+ "shrink-0 rounded-xs bg-muted px-1 text-micro font-medium tabular-nums text-muted-foreground",
+ className,
+ )}
+ aria-hidden
+ >
+ {t(($) => $.deliverables.version_short, { version })}
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 1af247c25b..0223fa1617 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -2,7 +2,7 @@ import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from "re
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { AgentTask, Issue, IssueStatusEntry, Label, TimelineEntry } from "@multica/core/types";
+import type { AgentTask, Attachment, Issue, IssueStatusEntry, Label, TimelineEntry } from "@multica/core/types";
import { issueKeys } from "@multica/core/issues/queries";
import { issueStatusKeys } from "@multica/core/issue-statuses";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -171,7 +171,15 @@ vi.mock("../../editor", async () => ({
// preview-sequence-context.test.tsx against the real provider.
PreviewSequenceProvider: ({ children }: { children: React.ReactNode }) =>
children,
+ usePreviewSequence: () => ({ openAt: () => false }),
collectPreviewSequence: () => [],
+ // Comment attachments render as their filename — the viewer and file cards
+ // have their own suites.
+ AttachmentDownloadProvider: ({ children }: { children: React.ReactNode }) =>
+ children,
+ Attachment: ({ attachment }: { attachment: { filename?: string } }) => (
+ <span data-testid="comment-attachment">{attachment.filename}</span>
+ ),
isPreviewable: () => false,
ReadonlyContent: ({ content }: { content: string }) => {
readonlyContentRenders.push(content);
@@ -730,6 +738,44 @@ describe("IssueDetail (shared)", () => {
mockApiObj.getProject.mockReset();
});
+ it("counts comment files as deliverables, a re-upload once as v2, never the description's (MUL-7649)", async () => {
+ const file = (id: string, over: Partial<Attachment>): Attachment => ({
+ id,
+ workspace_id: "ws-1",
+ issue_id: "issue-1",
+ comment_id: null,
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "agent",
+ uploader_id: "agent-1",
+ filename: "report.md",
+ url: `https://cdn.example.test/${id}`,
+ download_url: `https://cdn.example.test/${id}`,
+ markdown_url: `https://cdn.example.test/${id}`,
+ content_type: "text/markdown",
+ size_bytes: 2048,
+ created_at: "2026-01-16T00:00:00Z",
+ ...over,
+ });
+ const brief = file("brief", { filename: "brief.pdf", content_type: "application/pdf", uploader_type: "member" });
+ const v1 = file("report-v1", { comment_id: "comment-1" });
+ const v2 = file("report-v2", { comment_id: "comment-2", created_at: "2026-01-17T00:00:00Z" });
+ mockApiObj.getIssue.mockResolvedValue({ ...mockIssue, description: "!file[brief.pdf](https://cdn.example.test/brief)" });
+ mockApiObj.listAttachments.mockResolvedValue([brief, v1, v2]);
+ mockApiObj.listTimeline.mockResolvedValue([
+ { ...mockTimeline[0]!, attachments: [v1] },
+ { ...mockTimeline[1]!, attachments: [v2] },
+ ]);
+
+ renderIssueDetail();
+
+ const header = await screen.findByRole("button", { name: /^Deliverables/ });
+ expect(header).toHaveTextContent("1");
+ expect(screen.getByRole("button", { name: "report.md, version 2" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "View all 1 deliverable" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "brief.pdf" })).toBeNull();
+ });
+
it("opens source-context creation from both a root comment and a reply", async () => {
mockApiObj.listTimeline.mockResolvedValue([
{ ...mockTimeline[0], id: "source-root", parent_id: null },
@@ -2466,6 +2512,105 @@ describe("IssueDetail (shared)", () => {
expect(useResolvedExpandStore.getState().expandedByIssue["issue-1"]?.has("comment-3")).toBe(true);
});
+ // "Show in comments" for a file shares the rail's path, so a file posted
+ // in a reply is reachable whatever hides that reply (MUL-7649).
+ it("reopens a collapsed thread when a file's reply is located from the overview", async () => {
+ useCommentCollapseStore.setState({ collapsedByIssue: { "issue-1": ["comment-1"] } });
+ const csv: Attachment = {
+ id: "csv",
+ workspace_id: "ws-1",
+ issue_id: "issue-1",
+ comment_id: "reply-2",
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "agent",
+ uploader_id: "agent-1",
+ filename: "latency.csv",
+ url: "https://cdn.example.test/csv",
+ download_url: "https://cdn.example.test/csv",
+ markdown_url: "https://cdn.example.test/csv",
+ content_type: "text/csv",
+ size_bytes: 2048,
+ created_at: "2026-01-16T01:00:00Z",
+ };
+ mockApiObj.listTimeline.mockResolvedValue([
+ ...mockTimeline,
+ {
+ type: "comment",
+ id: "reply-2",
+ actor_type: "member",
+ actor_id: "user-1",
+ content: "Latency numbers attached",
+ parent_id: "comment-1",
+ created_at: "2026-01-16T01:00:00Z",
+ updated_at: "2026-01-16T01:00:00Z",
+ comment_type: "comment",
+ attachments: [csv],
+ } as TimelineEntry,
+ ]);
+
+ renderIssueDetail();
+
+ fireEvent.click(await screen.findByRole("button", { name: "View all 1 deliverable" }));
+ const overview = await screen.findByRole("dialog", { name: /deliverables$/ });
+ expect(document.getElementById("comment-reply-2")).toBeNull();
+ fireEvent.click(within(overview).getByRole("button", { name: "Show in comments" }));
+
+ await waitFor(() => {
+ expect(document.getElementById("comment-reply-2")?.className).toContain(highlightTint);
+ });
+ expect(useCommentCollapseStore.getState().isCollapsed("issue-1", "comment-1")).toBe(false);
+ });
+
+ it("unfolds a resolved thread when a file on its root is located from the overview", async () => {
+ const pdf: Attachment = {
+ id: "pdf",
+ workspace_id: "ws-1",
+ issue_id: "issue-1",
+ comment_id: "comment-3",
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "member",
+ uploader_id: "user-1",
+ filename: "spec.pdf",
+ url: "https://cdn.example.test/pdf",
+ download_url: "https://cdn.example.test/pdf",
+ markdown_url: "https://cdn.example.test/pdf",
+ content_type: "application/pdf",
+ size_bytes: 2048,
+ created_at: "2026-01-18T00:00:00Z",
+ };
+ mockApiObj.listTimeline.mockResolvedValue([
+ ...mockTimeline,
+ {
+ type: "comment",
+ id: "comment-3",
+ actor_type: "member",
+ actor_id: "user-1",
+ content: "Spec attached",
+ parent_id: null,
+ created_at: "2026-01-18T00:00:00Z",
+ updated_at: "2026-01-18T00:00:00Z",
+ comment_type: "comment",
+ resolved_at: "2026-01-19T00:00:00Z",
+ attachments: [pdf],
+ } as TimelineEntry,
+ ]);
+
+ renderIssueDetail();
+
+ fireEvent.click(await screen.findByRole("button", { name: "View all 1 deliverable" }));
+ const overview = await screen.findByRole("dialog", { name: /deliverables$/ });
+ fireEvent.click(within(overview).getByRole("button", { name: "Show in comments" }));
+
+ await waitFor(() => {
+ expect(useResolvedExpandStore.getState().expandedByIssue["issue-1"]?.has("comment-3")).toBe(true);
+ });
+ await waitFor(() => {
+ expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-3"))).toBe(true);
+ });
+ });
+
it("reopens a thread the reader collapsed before landing on its reply", async () => {
useCommentCollapseStore.setState({ collapsedByIssue: { "issue-1": ["comment-1"] } });
mockApiObj.listTimeline.mockResolvedValue([
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 5739a7f2bc..2794723582 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -105,6 +105,15 @@ import { QuickActionsSection } from "./quick-actions-section";
import { PluginPanelSection } from "../../plugins";
import { PullRequestsSection } from "./pull-requests-section";
import { useGitHubSettings } from "@multica/core/github";
+import { DeliverablesSection } from "./deliverables/deliverables-section";
+import { DeliverablesOverview } from "./deliverables/deliverables-overview";
+import {
+ DESCRIPTION_BLOCK_ID,
+ useDeliverableDetails,
+ type DeliverableOrigin,
+} from "./deliverables/deliverable-details";
+import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";
+import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";
import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspacePaths } from "@multica/core/paths";
@@ -2253,6 +2262,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const previewSequence = useMemo(() => {
const blocks: ImageSequenceBlock[] = [
{
+ id: DESCRIPTION_BLOCK_ID,
content: issue?.description,
attachments: descEditorAttachments,
standalone: false,
@@ -2261,16 +2271,95 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
for (const item of items) {
if (item.kind === "activity-group" || !item.entry) continue;
blocks.push({
+ id: item.entry.id,
content: item.entry.content,
attachments: item.entry.attachments,
});
for (const reply of timelineView.threadReplies.get(item.entry.id) ?? []) {
- blocks.push({ content: reply.content, attachments: reply.attachments });
+ blocks.push({ id: reply.id, content: reply.content, attachments: reply.attachments });
}
}
return collectPreviewSequence(blocks);
}, [issue?.description, descEditorAttachments, items, timelineView.threadReplies]);
+ // The files this issue has delivered as a whole: the sidebar section, the
+ // overview grid, the viewer's info panel and the comments' version badges
+ // all read this (MUL-7649).
+ const deliverableFiles = useMemo(() => collectDeliverableFiles(timeline), [timeline]);
+ const commentById = useMemo(
+ () =>
+ new Map(
+ timeline
+ .filter((entry) => entry.type === "comment")
+ .map((entry) => [entry.id, entry] as const),
+ ),
+ [timeline],
+ );
+
+ // "Show in comments" from the viewer and the overview. A reply goes through
+ // the quick-jump rail's path, which already undoes everything that hides one
+ // (the reader's collapse, a resolution folding the thread) and waits for the
+ // reply to mount. A root is visible unless its own thread is collapsed or
+ // folded into a resolved bar: open that, then jump once the open thread has
+ // rendered, so the flash lands on the comment and not on the bar.
+ const [locateRootRequest, setLocateRootRequest] = useState<string | null>(null);
+ const locateOrigin = useCallback(
+ (origin: DeliverableOrigin) => {
+ if (origin.kind === "description") {
+ scrollContainerEl?.scrollTo({ top: 0, behavior: "smooth" });
+ return;
+ }
+ const { commentId } = origin;
+ if (replyToRoot.has(commentId)) {
+ jumpToReply(commentId);
+ return;
+ }
+ const rootItem = items.find((it) => it.id === commentId);
+ const root = rootItem && rootItem.kind !== "activity-group" ? rootItem.entry : undefined;
+ if (!root) return;
+ const collapse = useCommentCollapseStore.getState();
+ if (collapse.isCollapsed(id, commentId)) collapse.toggle(id, commentId);
+ if (
+ !expandedResolved.has(commentId) &&
+ deriveThreadResolution(root, timelineView.threadReplies.get(commentId) ?? EMPTY_REPLIES)
+ .kind === "root"
+ ) {
+ toggleResolvedExpand(commentId, true);
+ }
+ setLocateRootRequest(commentId);
+ },
+ [scrollContainerEl, replyToRoot, jumpToReply, items, id, expandedResolved, timelineView.threadReplies, toggleResolvedExpand],
+ );
+ useEffect(() => {
+ if (!locateRootRequest) return;
+ setLocateRootRequest(null);
+ jumpToThread(locateRootRequest);
+ }, [locateRootRequest, jumpToThread]);
+
+ const describeDeliverable = useDeliverableDetails({
+ files: deliverableFiles,
+ commentById,
+ onLocate: locateOrigin,
+ });
+ // The overview remembers the file the viewer was showing, so `G` can go
+ // back to it.
+ const [overview, setOverview] = useState<{ open: boolean; returnKey: string | null }>({
+ open: false,
+ returnKey: null,
+ });
+ useEffect(() => {
+ setOverview({ open: false, returnKey: null });
+ }, [id]);
+ const openOverview = useCallback(() => setOverview({ open: true, returnKey: null }), []);
+ const openOverviewFromViewer = useCallback(
+ (key: string) => setOverview({ open: true, returnKey: key }),
+ [],
+ );
+ const closeOverview = useCallback(
+ () => setOverview((current) => ({ ...current, open: false })),
+ [],
+ );
+
const handleDescriptionUpload = useCallback(
async (file: File) => {
const result = await uploadWithToast(file);
@@ -2770,6 +2859,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
/>
)}
+ {/* Deliverables — the files this issue's comments delivered. Hidden
+ while there are none. */}
+ <DeliverablesSection files={deliverableFiles} onOpenOverview={openOverview} />
+
{/* Execution log — active runs + collapsed past runs, each carrying its
own token spend, with the issue total on the section header.
Self-contained; owns its own collapse state and WS subscriptions.
@@ -2959,11 +3052,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
: [];
const detailContent = (
- // Hosts the one viewer this issue's files page through — see
- // PreviewSequenceProvider. Wraps the whole column so the description
- // editor's files and the timeline's files share one sequence.
<CurrentIssueRenderContextProvider value={currentIssueRenderContext}>
- <PreviewSequenceProvider items={previewSequence}>
<div className="relative flex h-full min-w-0 flex-1 flex-col">
{/* In-page find bar — floats over the top-right of the content column
(below the breadcrumb header), outside the scroll container so it
@@ -3712,12 +3801,35 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
/>
)}
</div>
- </PreviewSequenceProvider>
</CurrentIssueRenderContextProvider>
);
+ // Hosts the one viewer this issue's files page through — see
+ // PreviewSequenceProvider. Wraps the column and the sidebar, so the
+ // description's files, the timeline's and the sidebar's deliverables all
+ // open into one sequence. The versions provider lets each comment's file
+ // cards mark a re-uploaded file `v2`.
+ const withPreview = (layout: ReactNode) => (
+ <PreviewSequenceProvider
+ items={previewSequence}
+ describeItem={describeDeliverable}
+ onOpenOverview={openOverviewFromViewer}
+ >
+ <AttachmentVersionsProvider files={deliverableFiles}>{layout}</AttachmentVersionsProvider>
+ <DeliverablesOverview
+ open={overview.open}
+ onClose={closeOverview}
+ returnKey={overview.returnKey}
+ identifier={issue.identifier}
+ files={deliverableFiles}
+ commentById={commentById}
+ onLocate={locateOrigin}
+ />
+ </PreviewSequenceProvider>
+ );
+
if (isMobile) {
- return (
+ return withPreview(
<div className="flex flex-1 min-h-0">
{detailContent}
<Sheet open={mobileSidebarOpen} onOpenChange={setMobileSidebarOpen}>
@@ -3725,11 +3837,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{sidebarContent}
</SheetContent>
</Sheet>
- </div>
+ </div>,
);
}
- return (
+ return withPreview(
<ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}>
<ResizablePanel id="content" minSize="50%">
{detailContent}
@@ -3751,6 +3863,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{sidebarContent}
</AnimatedRightSidebar>
</ResizablePanel>
- </ResizablePanelGroup>
+ </ResizablePanelGroup>,
);
}
diff --git a/packages/views/issues/components/justified-image-row.tsx b/packages/views/issues/components/justified-image-row.tsx
new file mode 100644
index 0000000000..29ef654d0d
--- /dev/null
+++ b/packages/views/issues/components/justified-image-row.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { clampRatio, justifyRows } from "./justified-layout";
+
+const GAP_PX = 8;
+const MIN_ROW_HEIGHT = 100;
+const MAX_ROW_HEIGHT = 240;
+// Until an image has loaded its shape is unknown; most are screenshots.
+const DEFAULT_RATIO = 16 / 10;
+
+/**
+ * Several images under one comment, laid out as justified rows (MUL-7649):
+ * one shared height per row, each full row edge to edge. Widths come from
+ * each image's real aspect ratio once it has loaded, so the row settles into
+ * place instead of cropping.
+ */
+export function JustifiedImageRow<T extends { id: string }>({
+ items,
+ renderTile,
+}: {
+ items: ReadonlyArray<T>;
+ /** Renders one image filling the box it is given. */
+ renderTile: (item: T) => ReactNode;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+ const [ratios, setRatios] = useState<ReadonlyMap<string, number>>(() => new Map());
+
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const measure = () => setWidth(el.clientWidth);
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ // `load` does not bubble, but it does travel the capture phase — one
+ // listener here hears every tile's image, including ones that swap URL
+ // after a re-sign. Images already decoded before this ran are read once.
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const record = (img: HTMLImageElement) => {
+ const key = img.closest<HTMLElement>("[data-ratio-key]")?.dataset.ratioKey;
+ if (!key || img.naturalWidth <= 0 || img.naturalHeight <= 0) return;
+ const ratio = img.naturalWidth / img.naturalHeight;
+ setRatios((prev) => {
+ if (Math.abs((prev.get(key) ?? 0) - ratio) < 0.001) return prev;
+ return new Map(prev).set(key, ratio);
+ });
+ };
+ el.querySelectorAll("img").forEach((img) => {
+ if (img.complete) record(img);
+ });
+ const onLoad = (e: Event) => {
+ if (e.target instanceof HTMLImageElement) record(e.target);
+ };
+ el.addEventListener("load", onLoad, true);
+ return () => el.removeEventListener("load", onLoad, true);
+ }, [items]);
+
+ const rows = useMemo(
+ () =>
+ justifyRows(
+ items.map((item) => ratios.get(item.id) ?? DEFAULT_RATIO),
+ width,
+ { gap: GAP_PX, minHeight: MIN_ROW_HEIGHT, maxHeight: MAX_ROW_HEIGHT },
+ ),
+ [items, ratios, width],
+ );
+
+ return (
+ <div ref={containerRef} className="flex flex-col" style={{ gap: GAP_PX }}>
+ {rows.map((row) => (
+ <div key={items[row.items[0]!]!.id} className="flex" style={{ gap: GAP_PX }}>
+ {row.items.map((index) => {
+ const item = items[index]!;
+ const ratio = clampRatio(ratios.get(item.id) ?? DEFAULT_RATIO);
+ return (
+ <div
+ key={item.id}
+ data-ratio-key={item.id}
+ className="shrink-0"
+ style={{ width: ratio * row.height, height: row.height }}
+ >
+ {renderTile(item)}
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/justified-layout.test.ts b/packages/views/issues/components/justified-layout.test.ts
new file mode 100644
index 0000000000..582aaef5fd
--- /dev/null
+++ b/packages/views/issues/components/justified-layout.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { clampRatio, justifyRows } from "./justified-layout";
+
+const OPTIONS = { gap: 8, minHeight: 100, maxHeight: 240 };
+
+function rowWidth(ratios: number[], row: { items: number[]; height: number }) {
+ return (
+ row.items.reduce((sum, i) => sum + clampRatio(ratios[i]!) * row.height, 0) +
+ OPTIONS.gap * (row.items.length - 1)
+ );
+}
+
+describe("justifyRows", () => {
+ it("keeps a comment's three screenshots in one full row in a narrow column", () => {
+ const ratios = [1.6, 1.78, 1.6];
+ const rows = justifyRows(ratios, 585, OPTIONS);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.items).toEqual([0, 1, 2]);
+ expect(rowWidth(ratios, rows[0]!)).toBeCloseTo(584, 0);
+ });
+
+ it("caps the height, so two images in a wide column stop short of the edge", () => {
+ const rows = justifyRows([1.6, 1.6], 1200, OPTIONS);
+ expect(rows).toEqual([{ items: [0, 1], height: 240 }]);
+ });
+
+ it("wraps before a row would get too short, and the last row keeps the height above", () => {
+ const ratios = Array.from({ length: 5 }, () => 1.6);
+ const rows = justifyRows(ratios, 585, OPTIONS);
+ expect(rows.map((r) => r.items.length)).toEqual([3, 2]);
+ expect(rowWidth(ratios, rows[0]!)).toBeCloseTo(584, 0);
+ expect(rows[1]!.height).toBeCloseTo(rows[0]!.height, 5);
+ });
+
+ it("lays everything out in one row before the width is known", () => {
+ expect(justifyRows([1.6, 1.6, 1.6], 0, OPTIONS)).toEqual([
+ { items: [0, 1, 2], height: 240 },
+ ]);
+ expect(justifyRows([], 600, OPTIONS)).toEqual([]);
+ });
+});
+
+describe("clampRatio", () => {
+ it("bounds extreme shapes and falls back on nonsense", () => {
+ expect(clampRatio(10)).toBe(3);
+ expect(clampRatio(0.1)).toBe(0.5);
+ expect(clampRatio(Number.NaN)).toBe(1);
+ expect(clampRatio(0)).toBe(1);
+ expect(clampRatio(1.6)).toBe(1.6);
+ });
+});
diff --git a/packages/views/issues/components/justified-layout.ts b/packages/views/issues/components/justified-layout.ts
new file mode 100644
index 0000000000..f228fff690
--- /dev/null
+++ b/packages/views/issues/components/justified-layout.ts
@@ -0,0 +1,71 @@
+/**
+ * Justified rows for a set of images (MUL-7649): every image in a row shares
+ * one height and a full row spans the container exactly — the album layout,
+ * instead of fixed-height tiles that wrap and leave a ragged edge.
+ *
+ * Rows take as many images as fit without dropping below `minHeight`, so a
+ * comment's handful of screenshots stays one tidy row even in a narrow
+ * column. No row grows past `maxHeight` (two screenshots in a wide column
+ * stop short of the edge rather than turning huge), and a final row that
+ * does not fill keeps the height of the row above it, never larger.
+ */
+
+export interface JustifiedRow {
+ /** Indexes into the input, in order. */
+ items: number[];
+ height: number;
+}
+
+export interface JustifyOptions {
+ gap: number;
+ minHeight: number;
+ maxHeight: number;
+}
+
+// Past these, an image would claim an absurd share of the row (a panorama)
+// or a sliver of it (a phone-length screenshot); it is cropped to fit instead.
+const MIN_RATIO = 0.5;
+const MAX_RATIO = 3;
+
+export function clampRatio(ratio: number): number {
+ if (!Number.isFinite(ratio) || ratio <= 0) return 1;
+ return Math.min(MAX_RATIO, Math.max(MIN_RATIO, ratio));
+}
+
+export function justifyRows(
+ ratios: ReadonlyArray<number>,
+ width: number,
+ { gap, minHeight, maxHeight }: JustifyOptions,
+): JustifiedRow[] {
+ if (ratios.length === 0) return [];
+ if (width <= 0) {
+ return [{ items: ratios.map((_, i) => i), height: maxHeight }];
+ }
+ // A pixel of slack keeps sub-pixel rounding from wrapping the last image.
+ const heightFor = (count: number, sum: number) =>
+ (width - gap * (count - 1) - 1) / sum;
+
+ const rows: JustifiedRow[] = [];
+ let items: number[] = [];
+ let ratioSum = 0;
+ ratios.forEach((raw, index) => {
+ const ratio = clampRatio(raw);
+ if (items.length > 0 && heightFor(items.length + 1, ratioSum + ratio) < minHeight) {
+ rows.push({
+ items,
+ height: Math.min(maxHeight, heightFor(items.length, ratioSum)),
+ });
+ items = [];
+ ratioSum = 0;
+ }
+ items.push(index);
+ ratioSum += ratio;
+ });
+
+ const above = rows.length > 0 ? rows[rows.length - 1]!.height : maxHeight;
+ rows.push({
+ items,
+ height: Math.min(maxHeight, above, heightFor(items.length, ratioSum)),
+ });
+ return rows;
+}
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index a9d2841c55..f8f232a258 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -61,7 +61,9 @@
"remove": "Remove attachment",
"previous": "Previous",
"next": "Next",
- "sequence_position": "{{index}} / {{total}}"
+ "sequence_position": "{{index}} / {{total}}",
+ "overview": "All deliverables",
+ "info": "Info"
},
"link_hover": {
"copy_link": "Copy link",
@@ -96,6 +98,19 @@
"show_source": "Show source",
"fullscreen": "Fullscreen"
},
+ "dynamic_block": {
+ "preview": "Preview",
+ "source": "Source",
+ "view": "View",
+ "copy_source": "Copy source",
+ "show_all": "Show all",
+ "rendering": "Rendering...",
+ "error_html": "The preview hit a script error",
+ "error_mermaid": "Couldn't draw this diagram",
+ "error_at_line": "{{message}} (line {{line}})",
+ "view_source": "View source",
+ "copy_error": "Copy error"
+ },
"file_card": {
"uploading": "Uploading {{filename}}"
},
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 3166f17701..0baf8bdb00 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1152,5 +1152,39 @@
"all_merged_to": "All PRs merged. The next merged PR moves this issue to {{status}}.",
"issue_disabled": "PR merges won’t change this issue",
"issue_disabled_action": "Turn on"
+ },
+ "deliverables": {
+ "section_title": "Deliverables",
+ "view_all_one": "View all {{count}} deliverable",
+ "view_all_other": "View all {{count}} deliverables",
+ "name_with_version": "{{name}}, version {{version}}",
+ "version_short": "v{{version}}",
+ "locate_comment": "Show in comments",
+ "locate_description": "Show in description",
+ "version_label": "Version {{version}} of {{total}}",
+ "version_of": "v{{version}} of {{total}}",
+ "info_source": "Source",
+ "source_description": "Issue description",
+ "info_siblings_comment": "Files in this comment · {{count}}",
+ "info_siblings_description": "Files in the description · {{count}}",
+ "info_file": "File",
+ "info_type": "Type",
+ "info_size": "Size",
+ "info_uploader": "Uploaded by",
+ "info_uploaded_at": "Uploaded",
+ "info_version": "Version",
+ "filter_all": "All",
+ "filter_image": "Images",
+ "filter_document": "Documents",
+ "filter_video": "Videos",
+ "filter_misc": "Other",
+ "overview_title": "{{identifier}} deliverables",
+ "overview_summary_one": "{{count}} deliverable",
+ "overview_summary_other": "{{count}} deliverables",
+ "overview_summary_with_size_one": "{{count}} deliverable · {{size}}",
+ "overview_summary_with_size_other": "{{count}} deliverables · {{size}} total",
+ "overview_close": "Close",
+ "overview_empty": "No deliverables of this type.",
+ "group_comment_by": "Comment by {{name}}"
}
}
diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.json
index 0e3de3ac5a..1caf00b71d 100644
--- a/packages/views/locales/fr/editor.json
+++ b/packages/views/locales/fr/editor.json
@@ -61,7 +61,9 @@
"remove": "Supprimer la pièce jointe",
"previous": "Précédent",
"next": "Suivant",
- "sequence_position": "{{index}} / {{total}}"
+ "sequence_position": "{{index}} / {{total}}",
+ "overview": "Tous les livrables",
+ "info": "Informations"
},
"link_hover": {
"copy_link": "Copier le lien",
@@ -96,6 +98,19 @@
"show_source": "Afficher la source",
"fullscreen": "Plein écran"
},
+ "dynamic_block": {
+ "preview": "Aperçu",
+ "source": "Source",
+ "view": "Affichage",
+ "copy_source": "Copier la source",
+ "show_all": "Tout afficher",
+ "rendering": "Rendu en cours...",
+ "error_html": "Erreur de script dans l’aperçu",
+ "error_mermaid": "Impossible de dessiner ce diagramme",
+ "error_at_line": "{{message}} (ligne {{line}})",
+ "view_source": "Voir la source",
+ "copy_error": "Copier l’erreur"
+ },
"file_card": {
"uploading": "Envoi de {{filename}}"
},
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 37cb9551e3..172404146c 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1152,5 +1152,39 @@
"all_merged_to": "Toutes les PR sont fusionnées. La prochaine PR fusionnée fera passer la tâche à {{status}}.",
"issue_disabled": "Les fusions de PR ne changent pas cette tâche",
"issue_disabled_action": "Réactiver"
+ },
+ "deliverables": {
+ "section_title": "Livrables",
+ "view_all_one": "Voir le livrable",
+ "view_all_other": "Voir les {{count}} livrables",
+ "name_with_version": "{{name}}, version {{version}}",
+ "version_short": "v{{version}}",
+ "locate_comment": "Afficher dans les commentaires",
+ "locate_description": "Afficher dans la description",
+ "version_label": "Version {{version}} sur {{total}}",
+ "version_of": "v{{version}} sur {{total}}",
+ "info_source": "Source",
+ "source_description": "Description de la tâche",
+ "info_siblings_comment": "Fichiers de ce commentaire · {{count}}",
+ "info_siblings_description": "Fichiers de la description · {{count}}",
+ "info_file": "Fichier",
+ "info_type": "Type",
+ "info_size": "Taille",
+ "info_uploader": "Ajouté par",
+ "info_uploaded_at": "Ajouté le",
+ "info_version": "Version",
+ "filter_all": "Tout",
+ "filter_image": "Images",
+ "filter_document": "Documents",
+ "filter_video": "Vidéos",
+ "filter_misc": "Autres",
+ "overview_title": "Livrables de {{identifier}}",
+ "overview_summary_one": "{{count}} livrable",
+ "overview_summary_other": "{{count}} livrables",
+ "overview_summary_with_size_one": "{{count}} livrable · {{size}}",
+ "overview_summary_with_size_other": "{{count}} livrables · {{size}} au total",
+ "overview_close": "Fermer",
+ "overview_empty": "Aucun livrable de ce type.",
+ "group_comment_by": "Commentaire de {{name}}"
}
}
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index f6ac5dd798..0d0a8cf0bf 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -61,7 +61,9 @@
"remove": "添付ファイルを削除",
"previous": "前へ",
"next": "次へ",
- "sequence_position": "{{index}} / {{total}}"
+ "sequence_position": "{{index}} / {{total}}",
+ "overview": "すべての成果物",
+ "info": "情報"
},
"link_hover": {
"copy_link": "リンクをコピー",
@@ -89,6 +91,19 @@
"show_source": "ソースを表示",
"fullscreen": "全画面"
},
+ "dynamic_block": {
+ "preview": "プレビュー",
+ "source": "ソース",
+ "view": "表示",
+ "copy_source": "ソースをコピー",
+ "show_all": "すべて表示",
+ "rendering": "レンダリング中...",
+ "error_html": "プレビューでスクリプトエラーが発生しました",
+ "error_mermaid": "この図を描画できませんでした",
+ "error_at_line": "{{message}}({{line}} 行目)",
+ "view_source": "ソースを表示",
+ "copy_error": "エラーをコピー"
+ },
"file_card": {
"uploading": "{{filename}} をアップロード中"
},
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index b4f632e755..3cbd484bcb 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1119,5 +1119,36 @@
"all_merged_to": "PR はすべてマージ済みです。次に PR がマージされると {{status}} に変更します。",
"issue_disabled": "このタスクは PR マージでステータスを変えません",
"issue_disabled_action": "再開"
+ },
+ "deliverables": {
+ "section_title": "成果物",
+ "view_all_other": "成果物 {{count}} 件をすべて表示",
+ "name_with_version": "{{name}}(バージョン {{version}})",
+ "version_short": "v{{version}}",
+ "locate_comment": "コメントで表示",
+ "locate_description": "説明で表示",
+ "version_label": "バージョン {{version}}(全 {{total}} 版)",
+ "version_of": "v{{version}}(全 {{total}} 版)",
+ "info_source": "投稿元",
+ "source_description": "タスクの説明",
+ "info_siblings_comment": "同じコメントのファイル · {{count}}",
+ "info_siblings_description": "説明のファイル · {{count}}",
+ "info_file": "ファイル情報",
+ "info_type": "種類",
+ "info_size": "サイズ",
+ "info_uploader": "アップロード者",
+ "info_uploaded_at": "アップロード日時",
+ "info_version": "バージョン",
+ "filter_all": "すべて",
+ "filter_image": "画像",
+ "filter_document": "ドキュメント",
+ "filter_video": "動画",
+ "filter_misc": "その他",
+ "overview_title": "{{identifier}} の成果物",
+ "overview_summary_other": "成果物 {{count}} 件",
+ "overview_summary_with_size_other": "成果物 {{count}} 件 · 合計 {{size}}",
+ "overview_close": "閉じる",
+ "overview_empty": "この種類の成果物はありません。",
+ "group_comment_by": "{{name}} のコメント"
}
}
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index cdb89e340d..dd44211bff 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -61,7 +61,9 @@
"remove": "첨부 파일 제거",
"previous": "이전",
"next": "다음",
- "sequence_position": "{{index}} / {{total}}"
+ "sequence_position": "{{index}} / {{total}}",
+ "overview": "모든 산출물",
+ "info": "정보"
},
"link_hover": {
"copy_link": "링크 복사",
@@ -89,6 +91,19 @@
"show_source": "소스 표시",
"fullscreen": "전체 화면"
},
+ "dynamic_block": {
+ "preview": "미리보기",
+ "source": "소스",
+ "view": "보기",
+ "copy_source": "소스 복사",
+ "show_all": "모두 보기",
+ "rendering": "렌더링 중...",
+ "error_html": "미리보기에서 스크립트 오류가 발생했습니다",
+ "error_mermaid": "이 다이어그램을 그릴 수 없습니다",
+ "error_at_line": "{{message}} ({{line}}행)",
+ "view_source": "소스 보기",
+ "copy_error": "오류 복사"
+ },
"file_card": {
"uploading": "{{filename}} 업로드 중"
},
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 146cbbb346..a82fd9ad2d 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1119,5 +1119,36 @@
"all_merged_to": "PR이 모두 병합되었습니다. 다음 PR이 병합되면 {{status}}(으)로 변경합니다.",
"issue_disabled": "이 태스크는 PR 병합 시 상태를 바꾸지 않음",
"issue_disabled_action": "다시 켜기"
+ },
+ "deliverables": {
+ "section_title": "산출물",
+ "view_all_other": "산출물 {{count}}개 모두 보기",
+ "name_with_version": "{{name}}, 버전 {{version}}",
+ "version_short": "v{{version}}",
+ "locate_comment": "댓글에서 보기",
+ "locate_description": "설명에서 보기",
+ "version_label": "버전 {{version}} / 전체 {{total}}개",
+ "version_of": "v{{version}} / 전체 {{total}}개",
+ "info_source": "출처",
+ "source_description": "태스크 설명",
+ "info_siblings_comment": "같은 댓글의 파일 · {{count}}",
+ "info_siblings_description": "설명의 파일 · {{count}}",
+ "info_file": "파일 정보",
+ "info_type": "유형",
+ "info_size": "크기",
+ "info_uploader": "업로드한 사람",
+ "info_uploaded_at": "업로드 시간",
+ "info_version": "버전",
+ "filter_all": "전체",
+ "filter_image": "이미지",
+ "filter_document": "문서",
+ "filter_video": "동영상",
+ "filter_misc": "기타",
+ "overview_title": "{{identifier}} 산출물",
+ "overview_summary_other": "산출물 {{count}}개",
+ "overview_summary_with_size_other": "산출물 {{count}}개 · 총 {{size}}",
+ "overview_close": "닫기",
+ "overview_empty": "이 유형의 산출물이 없습니다.",
+ "group_comment_by": "{{name}}의 댓글"
}
}
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index 5d10fb31a9..8b80226744 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -61,7 +61,9 @@
"remove": "移除附件",
"previous": "上一个",
"next": "下一个",
- "sequence_position": "{{index}} / {{total}}"
+ "sequence_position": "{{index}} / {{total}}",
+ "overview": "全部产物",
+ "info": "信息"
},
"link_hover": {
"copy_link": "复制链接",
@@ -96,6 +98,19 @@
"show_source": "显示源码",
"fullscreen": "放大"
},
+ "dynamic_block": {
+ "preview": "预览",
+ "source": "源码",
+ "view": "视图",
+ "copy_source": "复制源码",
+ "show_all": "展开全部",
+ "rendering": "正在渲染...",
+ "error_html": "预览中的脚本出错",
+ "error_mermaid": "无法绘制这张图",
+ "error_at_line": "{{message}}(第 {{line}} 行)",
+ "view_source": "查看源码",
+ "copy_error": "复制错误"
+ },
"file_card": {
"uploading": "正在上传 {{filename}}"
},
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 00624f390b..4bc0de6757 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1119,5 +1119,36 @@
"all_merged_to": "PR 均已合并。之后有新 PR 合并时会改为 {{status}}。",
"issue_disabled": "此任务合并后不改状态",
"issue_disabled_action": "恢复"
+ },
+ "deliverables": {
+ "section_title": "产物",
+ "view_all_other": "查看全部 {{count}} 个产物",
+ "name_with_version": "{{name}},第 {{version}} 版",
+ "version_short": "v{{version}}",
+ "locate_comment": "定位到评论",
+ "locate_description": "定位到描述",
+ "version_label": "第 {{version}} 版,共 {{total}} 版",
+ "version_of": "v{{version}}(共 {{total}} 版)",
+ "info_source": "来源",
+ "source_description": "任务描述",
+ "info_siblings_comment": "同一条评论中的附件 · {{count}}",
+ "info_siblings_description": "描述中的附件 · {{count}}",
+ "info_file": "文件信息",
+ "info_type": "类型",
+ "info_size": "大小",
+ "info_uploader": "上传者",
+ "info_uploaded_at": "上传时间",
+ "info_version": "版本",
+ "filter_all": "全部",
+ "filter_image": "图片",
+ "filter_document": "文档",
+ "filter_video": "视频",
+ "filter_misc": "其他",
+ "overview_title": "{{identifier}} 的产物",
+ "overview_summary_other": "{{count}} 个产物",
+ "overview_summary_with_size_other": "{{count}} 个产物 · 共 {{size}}",
+ "overview_close": "关闭",
+ "overview_empty": "没有这类产物。",
+ "group_comment_by": "{{name}} 的评论"
}
}
diff --git a/packages/views/rich-content/index.ts b/packages/views/rich-content/index.ts
index b1bbd9eca0..5bab84599c 100644
--- a/packages/views/rich-content/index.ts
+++ b/packages/views/rich-content/index.ts
@@ -9,4 +9,4 @@ export {
shouldUpgradeFence,
type RichFenceLanguage,
} from "./rich-code-block";
-export { computeClosedFenceOffsets } from "./streaming-fence";
+export { computeClosedFences } from "./streaming-fence";
diff --git a/packages/views/rich-content/rich-code-block.tsx b/packages/views/rich-content/rich-code-block.tsx
index 5af1015b88..8b1415ae65 100644
--- a/packages/views/rich-content/rich-code-block.tsx
+++ b/packages/views/rich-content/rich-code-block.tsx
@@ -16,8 +16,10 @@
* 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
+ * Upgraded fences render as dynamic blocks (MermaidBlock / HtmlBlockPreview):
+ * one frame with an always-visible title bar, content height and in-place
+ * loading and error states (MUL-7649). The frame and its leaves live in
+ * `editor/` next to the Tiptap NodeViews that share the leaves. They are
* imported by direct path — never through the `editor` barrel — so this module
* does not pull the editor's Tiptap graph into Chat.
*/
@@ -29,13 +31,14 @@ 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";
+ MermaidBlock,
+ MERMAID_BLOCK_DEFAULT_RESERVED_PX,
+ reservedMermaidBlockHeightPx,
+} from "../editor/mermaid-block";
import {
HtmlBlockPreview,
- HTML_BLOCK_PREVIEW_HEIGHT_PX,
+ HTML_BLOCK_DEFAULT_RESERVED_PX,
+ reservedHtmlBlockHeightPx,
} from "../editor/html-block-preview";
import { highlightCode } from "../editor/syntax-highlight";
import { LazyRichBlock } from "./lazy-rich-block";
@@ -67,7 +70,7 @@ export function shouldUpgradeFence(
// 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 MemoMermaidBlock = memo(MermaidBlock);
const MemoHtmlBlockPreview = memo(HtmlBlockPreview);
/**
@@ -175,50 +178,51 @@ export function CodeBlockShell({
export function RichFenceBlock({
language,
body,
+ title,
}: {
language: RichFenceLanguage;
body: string;
+ /** From the fence info string: ```html title="…". */
+ title?: string | null;
}) {
- // 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} />;
+ const reservedHeightPx = useReservedHeightPx(language, body);
+ return (
+ <LazyRichBlock reservedHeightPx={reservedHeightPx} sourceKey={body}>
+ {language === "mermaid" ? (
+ <MemoMermaidBlock chart={body} title={title} />
+ ) : (
+ <MemoHtmlBlockPreview html={body} title={title} />
+ )}
+ </LazyRichBlock>
+ );
}
+const DEFAULT_RESERVED_PX: Record<RichFenceLanguage, number> = {
+ mermaid: MERMAID_BLOCK_DEFAULT_RESERVED_PX,
+ html: HTML_BLOCK_DEFAULT_RESERVED_PX,
+};
+
+const cachedReservedPx: Record<RichFenceLanguage, (body: string) => number> = {
+ mermaid: reservedMermaidBlockHeightPx,
+ html: reservedHtmlBlockHeightPx,
+};
+
/**
- * Reserved height for a diagram: the skeleton default on the first frame, then
- * the session-cached real height once mounted.
+ * Reserved height for a block: the 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.
+ * during render therefore produces the default 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);
+function useReservedHeightPx(language: RichFenceLanguage, body: string): number {
+ const [height, setHeight] = useState(DEFAULT_RESERVED_PX[language]);
useEffect(() => {
- const cached = reservedMermaidHeightPx(chart);
+ const cached = cachedReservedPx[language](body);
setHeight((current) => (current === cached ? current : cached));
- }, [chart]);
+ }, [language, body]);
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-parity.test.tsx b/packages/views/rich-content/rich-content-parity.test.tsx
index 8425c59097..ed5f3bdfa1 100644
--- a/packages/views/rich-content/rich-content-parity.test.tsx
+++ b/packages/views/rich-content/rich-content-parity.test.tsx
@@ -205,8 +205,10 @@ async function expectMermaidRendered(container: HTMLElement) {
await waitFor(() => {
expect(mermaidLeaf(container)).not.toBeNull();
});
+ // Rendered, not still loading: the diagram's sandboxed frame carries the SVG.
await waitFor(() => {
- expect(mermaidLeaf(container)?.querySelector("svg")).not.toBeNull();
+ const frame = mermaidLeaf(container)?.querySelector<HTMLIFrameElement>(".mermaid-diagram-frame");
+ expect(frame?.srcdoc).toContain("<svg");
});
// Not a plain code block: the fence was upgraded.
expect(container.querySelector("code.hljs")).toBeNull();
diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsx
index 889b701e72..dff1f2748a 100644
--- a/packages/views/rich-content/rich-content.tsx
+++ b/packages/views/rich-content/rich-content.tsx
@@ -68,7 +68,7 @@ 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 { computeClosedFences, type ClosedFence } from "./streaming-fence";
import { remarkRepairCjkStrongTrailingWhitespace } from "./cjk-emphasis";
import {
CodeBlockShell,
@@ -94,13 +94,16 @@ export type RichContentPhase = "streaming" | "settled";
// 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>());
+const ClosedFenceContext = createContext<ReadonlyMap<number, ClosedFence>>(
+ new Map<number, ClosedFence>(),
+);
-function useIsFenceClosed(offset: number | undefined): boolean {
+/** The closed fence at this source offset, or undefined while it is still open. */
+function useClosedFence(offset: number | undefined): ClosedFence | undefined {
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);
+ return offset == null ? undefined : closed.get(offset);
}
// ---------------------------------------------------------------------------
@@ -343,13 +346,19 @@ function isMultiLineNode(node: ExtraProps["node"]): boolean {
function RichCode({ className, children, node, ...props }: RichCodeProps) {
const language = /language-(\w+)/.exec(className || "")?.[1];
const isBlock = isMultiLineNode(node);
- const isFenceClosed = useIsFenceClosed(nodeStartOffset(node));
+ const fence = useClosedFence(nodeStartOffset(node));
- if (isBlock && shouldUpgradeFence(language, isFenceClosed)) {
+ if (isBlock && shouldUpgradeFence(language, fence != null)) {
// isRichFenceLanguage is re-checked for the type narrow; shouldUpgradeFence
// already required it.
if (isRichFenceLanguage(language)) {
- return <RichFenceBlock language={language} body={String(children).replace(/\n$/, "")} />;
+ return (
+ <RichFenceBlock
+ language={language}
+ body={String(children).replace(/\n$/, "")}
+ title={fence?.title}
+ />
+ );
}
}
@@ -388,7 +397,7 @@ function readFencedCodeChild(children: ReactNode): {
*/
function RichPre({ children }: RichPreProps) {
const { language, offset } = readFencedCodeChild(children);
- const isFenceClosed = useIsFenceClosed(offset);
+ const isFenceClosed = useClosedFence(offset) != null;
// Upgraded fences escape the <pre><code> envelope entirely. An OPEN
// mermaid/html fence deliberately falls through to the normal code shell, so
@@ -528,7 +537,7 @@ export const RichContent = memo(function RichContent({
// 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 closedFences = useMemo(() => computeClosedFences(processed), [processed]);
const wrapperRef = useRef<HTMLDivElement>(null);
const hover = useLinkHover(wrapperRef);
diff --git a/packages/views/rich-content/rich-fence-block-ssr.test.tsx b/packages/views/rich-content/rich-fence-block-ssr.test.tsx
index 6e863c22fe..687ba605fc 100644
--- a/packages/views/rich-content/rich-fence-block-ssr.test.tsx
+++ b/packages/views/rich-content/rich-fence-block-ssr.test.tsx
@@ -42,9 +42,13 @@ import { resetMountedBlocks } from "./mounted-block-registry";
const CHART = "flowchart LR\n A --> B";
const CACHED_HEIGHT = 412;
-const SKELETON_HEIGHT = 280;
+// What the shell reserves for the whole block: the title bar (38px) plus the
+// body — the 280px skeleton, or the cached drawn height plus the diagram's
+// 32px of padding.
+const SKELETON_BLOCK_HEIGHT = 38 + 280;
+const CACHED_BLOCK_HEIGHT = 38 + CACHED_HEIGHT + 32;
-/** Mirrors the DJB2 key derivation in editor/mermaid-diagram.tsx. */
+/** Mirrors the layout-cache key: editor/mermaid-diagram.tsx + utils/source-hash.ts. */
function cacheKey(chart: string): string {
let hash = 5381;
for (let i = 0; i < chart.length; i++) {
@@ -90,8 +94,8 @@ 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`);
+ expect(html).toContain(`min-height:${SKELETON_BLOCK_HEIGHT}px`);
+ expect(html).not.toContain(`min-height:${CACHED_BLOCK_HEIGHT}px`);
});
it("uses the skeleton height on the client's first frame despite a warm cache", () => {
@@ -104,7 +108,7 @@ describe("RichFenceBlock reserved height", () => {
flushSync(() => root.render(block()));
const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
- expect(shell.style.minHeight).toBe(`${SKELETON_HEIGHT}px`);
+ expect(shell.style.minHeight).toBe(`${SKELETON_BLOCK_HEIGHT}px`);
act(() => root.unmount());
container.remove();
@@ -146,7 +150,7 @@ describe("RichFenceBlock reserved height", () => {
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`);
+ expect(shell.style.minHeight).toBe(`${CACHED_BLOCK_HEIGHT}px`);
await act(async () => root.unmount());
container.remove();
@@ -164,7 +168,7 @@ describe("RichFenceBlock reserved height", () => {
});
const shell = container.querySelector("[data-rich-block-shell]") as HTMLElement;
- expect(shell.style.minHeight).toBe(`${SKELETON_HEIGHT}px`);
+ expect(shell.style.minHeight).toBe(`${SKELETON_BLOCK_HEIGHT}px`);
await act(async () => root.unmount());
container.remove();
diff --git a/packages/views/rich-content/streaming-fence.test.ts b/packages/views/rich-content/streaming-fence.test.ts
index c75ebc9404..2de21c09f7 100644
--- a/packages/views/rich-content/streaming-fence.test.ts
+++ b/packages/views/rich-content/streaming-fence.test.ts
@@ -1,11 +1,11 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { computeClosedFenceOffsets } from "./streaming-fence";
+import { computeClosedFences, parseFenceTitle } from "./streaming-fence";
const isClosed = (src: string, offset = 0): boolean =>
- computeClosedFenceOffsets(src).has(offset);
+ computeClosedFences(src).has(offset);
-describe("computeClosedFenceOffsets", () => {
+describe("computeClosedFences", () => {
it("treats a closed backtick fence as closed", () => {
expect(isClosed("```mermaid\ngraph TD\n```\n")).toBe(true);
});
@@ -51,7 +51,7 @@ describe("computeClosedFenceOffsets", () => {
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(computeClosedFences(src).size).toBe(1);
expect(isClosed(src, src.indexOf("```"))).toBe(true);
});
@@ -59,14 +59,14 @@ describe("computeClosedFenceOffsets", () => {
// 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);
+ const offsets = computeClosedFences(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);
+ const offsets = computeClosedFences(src);
expect(offsets.has(0)).toBe(true);
expect(offsets.has(src.lastIndexOf("```html"))).toBe(false);
});
@@ -90,14 +90,34 @@ describe("computeClosedFenceOffsets", () => {
// 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);
+ expect(computeClosedFences(src).size).toBe(1);
});
- it("returns an empty set for empty input", () => {
- expect(computeClosedFenceOffsets("").size).toBe(0);
+ it("returns an empty map for empty input", () => {
+ expect(computeClosedFences("").size).toBe(0);
});
- it("returns an empty set for prose with no code", () => {
- expect(computeClosedFenceOffsets("just some **text**\n").size).toBe(0);
+ it("returns an empty map for prose with no code", () => {
+ expect(computeClosedFences("just some **text**\n").size).toBe(0);
+ });
+});
+
+describe("fence titles", () => {
+ it("reads the title attribute from a closed fence's info string", () => {
+ const src = '```html title="Weekly p95"\n<b>x</b>\n```\n';
+ expect(computeClosedFences(src).get(0)).toEqual({ title: "Weekly p95" });
+ });
+
+ it("has no title when the info string carries none", () => {
+ expect(computeClosedFences("```html\n<b>x</b>\n```\n").get(0)).toEqual({ title: null });
+ });
+
+ it("accepts double, single and bare values", () => {
+ expect(parseFenceTitle('title="Weekly p95" theme=dark')).toBe("Weekly p95");
+ expect(parseFenceTitle("title='Sign-up funnel'")).toBe("Sign-up funnel");
+ expect(parseFenceTitle("title=Funnel")).toBe("Funnel");
+ expect(parseFenceTitle('subtitle="nope"')).toBeNull();
+ expect(parseFenceTitle('title=" "')).toBeNull();
+ expect(parseFenceTitle(null)).toBeNull();
});
});
diff --git a/packages/views/rich-content/streaming-fence.ts b/packages/views/rich-content/streaming-fence.ts
index 7c9a71c2f9..6e19b6fb7a 100644
--- a/packages/views/rich-content/streaming-fence.ts
+++ b/packages/views/rich-content/streaming-fence.ts
@@ -10,8 +10,12 @@ import type { Root, RootContent, Code } from "mdast";
* 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.
+ * This module answers one question — "which fenced code blocks in this source
+ * are closed?" — and returns their offsets. Since it holds the only parse that
+ * still sees a fence's info string, it also reads the block title from it
+ * (```html title="Weekly p95", MUL-7649): rehype-raw rebuilds the tree and
+ * drops the `meta` the code renderer would otherwise have received. 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.
*
@@ -71,15 +75,32 @@ function endsWithClosingFence(raw: string): boolean {
return closeFence[0] === marker && closeFence.length >= openFence.length;
}
+const TITLE_RE = /(?:^|\s)title=(?:"([^"]*)"|'([^']*)'|(\S+))/;
+
+/**
+ * The `title` attribute of a fence info string, e.g. `title="Weekly p95"` in
+ * ```html title="Weekly p95". Double, single or no quotes.
+ */
+export function parseFenceTitle(meta: string | null | undefined): string | null {
+ if (!meta) return null;
+ const match = TITLE_RE.exec(meta);
+ const title = (match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
+ return title || null;
+}
+
+export interface ClosedFence {
+ title: string | null;
+}
+
/**
- * Start offsets of every fenced code block that is closed in `source`.
+ * Every fenced code block that is closed in `source`, keyed by start offset.
*
* `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>();
+export function computeClosedFences(source: string): Map<number, ClosedFence> {
+ const closed = new Map<number, ClosedFence>();
if (!source) return closed;
let tree: Root;
@@ -98,7 +119,9 @@ export function computeClosedFenceOffsets(source: string): Set<number> {
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);
+ if (endsWithClosingFence(source.slice(start, end))) {
+ closed.set(start, { title: parseFenceTitle(node.meta) });
+ }
}
return closed;
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 98e4c370f7..f2b96ad723 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -702,7 +702,7 @@ func init() {
issueCommentAddCmd.Flags().String("content-file", "", "Read comment content from a UTF-8 file (preserves multi-line content verbatim; use this on Windows when stdin piping mangles non-ASCII bytes). The path must be inside the current working directory unless --allow-external-file is set.")
issueCommentAddCmd.Flags().Bool("allow-external-file", false, "Allow --content-file / --attachment to read a path outside the current working directory. Off by default so a stale file from another run/environment can't be picked up (MUL-4252).")
issueCommentAddCmd.Flags().String("parent", "", "Parent comment ID to reply under. A comment-triggered agent run must reply under its trigger comment; omitting --parent to post a top-level comment is rejected")
- issueCommentAddCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times)")
+ issueCommentAddCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times). Non-image files, HTML included, show as file cards that open in the viewer; to render a chart inside the comment, put a ```html or ```mermaid block in the content instead")
issueCommentAddCmd.Flags().String("output", "json", "Output format: table or json")
// issue comment update
diff --git a/server/internal/daemon/execenv/runtime_config_delivery_test.go b/server/internal/daemon/execenv/runtime_config_delivery_test.go
index b51197c75a..7675dc5267 100644
--- a/server/internal/daemon/execenv/runtime_config_delivery_test.go
+++ b/server/internal/daemon/execenv/runtime_config_delivery_test.go
@@ -57,6 +57,12 @@ func deliveryInvariantFixtures() map[string]TaskContextForEnv {
}
}
+// inlineBlocksRule is the brief's one-line rule for charts and diagrams
+// (MUL-7649). Surfaces the web renders carry it; surfaces that deliver plain
+// text (channel chats, autopilot results, quick-create stdout) must not, since
+// a fenced html/mermaid block does not render there.
+const inlineBlocksRule = "fenced `html` or `mermaid` code block"
+
func TestBriefDeliveryInvariantIsAlwaysOn(t *testing.T) {
t.Parallel()
@@ -86,17 +92,17 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
}{
// Issue surfaces: files ride the comment.
"comment": {
- mustHave: []string{"`--attachment <path>` to `multica issue comment add`"},
+ mustHave: []string{"`--attachment <path>` to `multica issue comment add`", inlineBlocksRule},
mustNot: []string{"multica attachment upload"},
},
"assignment": {
- mustHave: []string{"`--attachment <path>` to `multica issue comment add`"},
+ mustHave: []string{"`--attachment <path>` to `multica issue comment add`", inlineBlocksRule},
mustNot: []string{"multica attachment upload"},
},
// Direct chat: the upload binds to the reply and the browser renders a
// card, so the file can sit inline where the agent puts it.
"chat_direct": {
- mustHave: []string{"`multica attachment upload <local-path>`"},
+ mustHave: []string{"`multica attachment upload <local-path>`", inlineBlocksRule},
mustNot: []string{"text-only", "separate message"},
},
// A channel-backed chat names its platform, defers the verdict to the
@@ -116,6 +122,7 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
"separate message",
"conversation is text-only",
"does NOT apply",
+ inlineBlocksRule,
},
},
"chat_wecom_no_store": {
@@ -128,6 +135,7 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
"separate message",
"conversation is text-only",
"does NOT apply",
+ inlineBlocksRule,
},
},
"chat_wecom_old_server": {
@@ -140,6 +148,7 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
"separate message",
"conversation is text-only",
"does NOT apply",
+ inlineBlocksRule,
},
},
// No deployment carries files into Slack or Lark today, but the brief
@@ -171,6 +180,7 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
"separate message",
"conversation is text-only",
"does NOT apply",
+ inlineBlocksRule,
},
},
"chat_feishu": {
@@ -184,15 +194,16 @@ func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
"separate message",
"conversation is text-only",
"does NOT apply",
+ inlineBlocksRule,
},
},
"autopilot": {
mustHave: []string{"this surface is text-only"},
- mustNot: []string{"multica attachment upload"},
+ mustNot: []string{"multica attachment upload", inlineBlocksRule},
},
"quickcreate": {
mustHave: []string{"your stdout is text-only", "`multica issue create` call itself via `--attachment <path>`"},
- mustNot: []string{"multica attachment upload"},
+ mustNot: []string{"multica attachment upload", inlineBlocksRule},
},
}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 6c2626db1d..7e41e81251 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -953,6 +953,21 @@ func writeDeliveryInvariant(b *strings.Builder) {
b.WriteString("**Runtime-local paths are never deliverables.** Your working directory exists only on the machine running you — NEVER write an absolute path or a `file://` URL as a clickable link or an embedded image. Reference code locations as inline code, never a link: `path/to/file.ts:42`. Deliver files through this surface's mechanism (above); if it has none, say so in words — never link the path and imply the file was delivered.\n\n")
}
+// writeInlineBlocksPolicy tells a surface that renders the reply as rich text
+// where a chart or diagram goes (MUL-7649). A fenced `html` / `mermaid` block
+// renders in place as a dynamic block; an attachment, HTML included, is a file
+// and shows as a card. Agents that uploaded report.html expecting an inline
+// chart now get a card, and the platform skill's reference is only opened on
+// demand, so the one-line rule sits here, beside the file-delivery line, where
+// it is in front of the agent when it writes the reply. The detail (theme
+// variables, sizing) stays in the reference.
+//
+// Only surfaces the web renders get it: channel chats, autopilot run results
+// and quick-create stdout do not render these blocks.
+func writeInlineBlocksPolicy(b *strings.Builder) {
+ b.WriteString("\n**Charts and diagrams:** put them in the text as a fenced `html` or `mermaid` code block — it renders in place (name it with `title=\"...\"` after the language). An attached file, HTML included, shows as a card instead. Theming and sizing: the multica-platform issues reference.\n")
+}
+
// writeOutput emits the kind-specific Output section: the always-on delivery
// invariant plus one per-surface file-delivery policy line per kind.
func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
@@ -990,6 +1005,7 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
fmt.Fprintf(b, "**Delivering files here:** whether Multica can push a file you produce into this %s conversation depends on how this deployment is configured, so it is stated per turn rather than here: the per-turn user message tells you, every turn. Follow what it says about files, and never report a file as delivered unless it told you how to deliver one.\n", ChannelDisplayName(ctx.ChatChannelType))
} else {
b.WriteString("**Delivering files here:** run `multica attachment upload <local-path>` — it binds the file to your reply and it renders as an attachment card. That command is the ONLY way a file reaches the user; a path written into your reply text is not.\n")
+ writeInlineBlocksPolicy(b)
}
default:
if ctx.IsSquadLeader {
@@ -1000,6 +1016,7 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
b.WriteString("**Post exactly ONE comment per run — your final result, before this turn exits.** Do NOT post progress updates or plans along the way.\n\n")
b.WriteString("Keep comments concise and natural — state the outcome, not the process.\n\n")
b.WriteString("**Delivering files here:** pass `--attachment <path>` to `multica issue comment add` (repeatable) — the only way a screenshot or artifact reaches the reader.\n")
+ writeInlineBlocksPolicy(b)
}
b.WriteString("\n")
writeDeliveryInvariant(b)
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
index ba67142a71..71cf0529ec 100644
--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md
@@ -1,6 +1,6 @@
---
name: multica-platform
-description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, skill import. Not for the product code you are working on."
+description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, skill import. Not for the product code you are working on."
user-invocable: false
allowed-tools: Bash(multica *), Bash(git *), Bash(gh *)
---
@@ -19,7 +19,7 @@ Read the invariants below, then open the reference(s) your task actually needs
| Open | When the task is about |
|---|---|
-| `references/issues.md` | Issues: PR linking, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running, event/time wakeups |
+| `references/issues.md` | Issues: PR linking, reading a linked PR's state, custom properties, status side effects, sub-issues and stages, who else is running, event/time wakeups, charts vs attached files in a comment |
| `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing |
| `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding |
| `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run |
diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.md
index e90d36e2d3..a86e015c09 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md
@@ -8,6 +8,7 @@ Product contracts the runtime brief does not fully encode.
- [Status changes have server side effects](#status-changes-have-server-side-effects)
- [Who else is running right now](#who-else-is-running-right-now)
- [Sub-issues: todo starts work now, backlog parks it](#sub-issues-todo-starts-work-now-backlog-parks-it)
+- [Charts and files in a comment](#charts-and-files-in-a-comment)
- [Incorrect to correct](#incorrect-to-correct)
To attach a local file to an existing issue description, use `multica issue update <id> --attachment <local-path>`. The CLI appends the file's Markdown reference to the end of the description; to replace an image, also use `--description-file` to remove the old reference. Do not put local filesystem paths in the description.
@@ -348,6 +349,39 @@ Read each sub-issue's description before promoting and only promote items whose
stated dependencies are met; if a description conflicts with the parent's
breakdown, leave it `backlog` and comment to confirm first.
+## Charts and files in a comment
+
+Where content goes decides how it shows:
+
+- **In the body, rendered in place** — a fenced ` ```html ` or ` ```mermaid `
+ block in the comment content. It renders inside the comment with a title
+ bar (Preview / Source, fullscreen, copy) and takes its content's height;
+ anything taller than 480px collapses behind "Show all". Name it with
+ `title="..."` on the fence line. HTML runs in a scripts-only sandbox (no
+ cookies, storage or parent access; CDN `<script src>` works).
+- **An attached file** — `--attachment <path>`. Every non-image file shows as
+ a file card that opens in the viewer, **HTML included**: an uploaded
+ `report.html` is a deliverable to open, not an inline chart. Use it for
+ something the reader keeps or downloads.
+
+For HTML that should follow light / dark mode, style it with the page's theme
+variables: `var(--background)`, `var(--foreground)`, `var(--muted)`,
+`var(--muted-foreground)`, `var(--border)`, `var(--primary)`,
+`var(--chart-1)` … `var(--chart-5)`, `var(--font-sans)`. Using any of them opts
+the block into the app's color scheme, so also set the page background
+(`body { background: var(--background); color: var(--foreground) }`). HTML
+that uses none keeps its own look. Size to the content, not the viewport:
+`100vh` heights have no fixed viewport to fill here.
+
+````markdown
+```html title="p95 latency, last 7 days"
+<canvas id="c"></canvas>
+<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+<script>/* draw with getComputedStyle(document.documentElement)
+ .getPropertyValue("--chart-1") so it follows the theme */</script>
+```
+````
+
## Incorrect to correct
PR title (link the issue):