Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8683 fix(attachments): align Markdown image preview sequences across clients (#10034)
Jiahao164290ee14f6
diff --git a/apps/mobile/lib/markdown/image-sequence.test.ts b/apps/mobile/lib/markdown/image-sequence.test.tsnew file mode 100644index 0000000000..224ac4092e--- /dev/null+++ b/apps/mobile/lib/markdown/image-sequence.test.ts@@ -0,0 +1,102 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Attachment } from "@multica/core/types";++const state = vi.hoisted(() => ({+ contexts: new Map<unknown, unknown>(),+ setters: [] as ReturnType<typeof vi.fn>[],+}));++vi.mock("react", async (importOriginal) => ({+ ...await importOriginal<typeof import("react")>(),+ use: (context: unknown) => state.contexts.get(context),+ useMemo: (factory: () => unknown) => factory(),+ useEffect: vi.fn(),+ useState: (initial: unknown) => {+ const setter = vi.fn();+ state.setters.push(setter);+ return [initial, setter];+ },+}));+vi.mock("react-native", () => ({+ Image: { getSize: vi.fn() }, Pressable: "Pressable", View: "View",+}));+vi.mock("expo-image", () => ({ Image: "ExpoImage" }));+vi.mock("react-native-image-viewing", () => ({ default: "ImageView" }));+vi.mock("@/components/ui/text", () => ({ Text: "Text" }));++import { preprocessMobileMarkdown } from "./preprocess";+import { splitMarkdown } from "./split-markdown";+import { ImageSequenceProvider } from "./image-sequence";+import { MarkdownImage } from "./markdown-image";+import { LightboxProvider } from "./lightbox-provider";++const ID = "11111111-1111-4111-8111-111111111111";+const attachment: Attachment = {+ id: ID, workspace_id: "ws", issue_id: null, comment_id: null,+ chat_session_id: null, chat_message_id: null, uploader_type: "member", uploader_id: "u",+ markdown_url: `/api/attachments/${ID}/download`,+ filename: "shot.png", content_type: "image/png", size_bytes: 1,+ url: "https://cdn.example/图 v2.png", download_url: "https://cdn.example/signed.png?Signature=raw%2Bvalue",+ created_at: "2026-11-06T00:00:00Z",+};++beforeEach(() => {+ vi.clearAllMocks();+ state.contexts.clear();+ state.setters.length = 0;+});++// Follow real parsing, provider values and press/open callbacks. Native leaves+// and hooks are stubbed; this does not render React Native or simulate swipes.+describe("mobile Markdown image sequence wiring", () => {+ it.each([+ ["Unicode", "", "https://cdn.example/%E5%9B%BE.png", []],+ ["angle URL with space", "", "https://cdn.example/a%20b.png", []],+ ["single-segment relative space", "", "/chart%20v2.png", []],+ ["escaped backslash", String.raw`.png>)`, "https://cdn.example/a%5C(b).png", []],+ ["existing percent escape", "", "https://cdn.example/a%20b.png", []],+ ["numeric entity", "", "https://cdn.example/a.png?a=1&b=2", []],+ ["relative angle URL with space", "", "/uploads/a%20b.png", []],+ ["legacy attachment URL", "", attachment.download_url!, [attachment]],+ ["space entity", "", "https://cdn.example/a%20b.png", []],+ ["CRLF image label with entity", "", "https://cdn.example/a.png?a=1&b=2", []],+ ["named entity", "", "https://cdn.example/a.png?a=1&b=2", []],+ ["escaped entity", String.raw``, "https://cdn.example/a.png?a=1&b=2", []],+ ["escaped nested entity", String.raw``, "https://cdn.example/a.png?a=1&amp;b=2", []],+ ["escaped reference entity", String.raw`![middle][shot]++[shot]: https://cdn.example/a.png?a=1\&amp;b=2`, "https://cdn.example/a.png?a=1&amp;b=2", []],+ ["escaped collapsed reference entity", String.raw`![shot][]++[shot]: https://cdn.example/a.png?a=1\&amp;b=2`, "https://cdn.example/a.png?a=1&amp;b=2", []],+ ["escaped shortcut reference entity", String.raw`![shot]++[shot]: https://cdn.example/a.png?a=1\&amp;b=2`, "https://cdn.example/a.png?a=1&amp;b=2", []],+ ["escaped backslash before entity", String.raw``, "https://cdn.example/a.png?a=1%5C&b=2", []],+ ["entity-generated backslash", "", "https://cdn.example/a.png?a=1%5C&b=2", []],+ ["nested entity", "", "https://cdn.example/a.png?a=1&b=2", []],+ ["reference", "![middle][shot]\n\n[shot]: https://cdn.example/图.png", "https://cdn.example/%E5%9B%BE.png", []],+ ["attachment", ``, attachment.download_url!, [attachment]],+ ] as const)("keeps the %s image inside the screen sequence", (_name, middle, expectedUri, attachments) => {+ const content = `\n\n${middle}\n\n`;+ const segments = splitMarkdown(preprocessMobileMarkdown(content)).filter((segment) => segment.type === "image");+ expect(segments).toHaveLength(3);+ const lightbox = LightboxProvider({ children: null });+ state.contexts.set(lightbox.type, lightbox.props.value);+ const provider = ImageSequenceProvider({ blocks: [{ content, attachments }], children: null });+ state.contexts.set(provider.type, provider.props.value);+ const image = MarkdownImage({ uri: segments[1]!.uri, attachments: [...attachments] });+ const renderedUri = image.props.children.props.children.props.source.uri;+ image.props.onPress();+ expect(state.setters[0]).toHaveBeenCalledExactlyOnceWith({+ images: [+ { uri: "https://cdn.example/first.png" },+ { uri: expectedUri },+ { uri: "https://cdn.example/last.png" },+ ],+ index: 1,+ });+ expect(renderedUri).toBe(expectedUri);+ });+});diff --git a/apps/mobile/lib/markdown/preprocess.test.ts b/apps/mobile/lib/markdown/preprocess.test.tsindex b709cc4e4f..80a4e54fe9 100644--- a/apps/mobile/lib/markdown/preprocess.test.ts+++ b/apps/mobile/lib/markdown/preprocess.test.ts@@ -60,3 +60,19 @@ describe("preprocessMobileMarkdown — !file file cards", () => {expect(preprocessMobileMarkdown(input)).toBe(output);});});++describe("preprocessMobileMarkdown — angle-bracket image destinations", () => {+ it.each([+ "",+ "",+ "",+ "![image][shot]\n\n[shot]: <https://cdn.example/a b.png>",+ ])("preserves %s", (content) => {+ expect(preprocessMobileMarkdown(content)).toBe(content);+ });++ it("still strips HTML tags while preserving text and hard breaks", () => {+ expect(preprocessMobileMarkdown('<div class="note">A<br/><b>B</b></div>'))+ .toBe("A \nB");+ });+});diff --git a/apps/mobile/lib/markdown/preprocess.ts b/apps/mobile/lib/markdown/preprocess.tsindex a78a0bc4bd..8c9455ef5e 100644--- a/apps/mobile/lib/markdown/preprocess.ts+++ b/apps/mobile/lib/markdown/preprocess.ts@@ -116,7 +116,9 @@ function stripHtml(input: string): string {return input.replace(/<!--[\s\S]*?-->/g, "").replace(/<br\s*\/?>/gi, " \n")- .replace(/<\/?[a-z][^>]*>/gi, "");+ // Angle-bracket URL destinations are not HTML tags. Closing tags have+ // no attributes, so </chart v2.png> must also survive for the lexer.+ .replace(/<(?:\/[a-z][a-z\d:-]*\s*|[a-z][a-z\d:-]*(?:\s[^>]*|\/?))>/gi, "");}export function preprocessMobileMarkdown(input: string): string {diff --git a/apps/mobile/lib/markdown/split-markdown.ts b/apps/mobile/lib/markdown/split-markdown.tsindex b723be8115..6df7547e4a 100644--- a/apps/mobile/lib/markdown/split-markdown.ts+++ b/apps/mobile/lib/markdown/split-markdown.ts@@ -7,6 +7,44 @@* renderer to preserve its surrounding Markdown structure.*/import { marked, type Tokens } from "marked";+import { fromMarkdown } from "mdast-util-from-markdown";+import { normalizeUri } from "micromark-util-sanitize-uri";++function imageUrisBySource(input: string): Map<string, string> {+ // Marked's href has already lost backslash escapes. Read destinations from+ // the source with the sequence's CommonMark parser instead of decoding href+ // again: \& must stay literal, while & must decode once.+ const tree = fromMarkdown(input);+ type Node = typeof tree | (typeof tree.children)[number];+ const pending: Node[] = [tree];+ const nodes: Node[] = [];+ while (pending.length) {+ const node = pending.pop()!;+ nodes.push(node);+ if ("children" in node) {+ for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]!);+ }+ }+ const definitions = new Map<string, string>();+ for (const node of nodes) {+ if (node.type === "definition" && !definitions.has(node.identifier)) {+ definitions.set(node.identifier, node.url);+ }+ }+ const uris = new Map<string, string>();+ for (const node of nodes) {+ if (node.type !== "image" && node.type !== "imageReference") continue;+ const url = node.type === "image" ? node.url : definitions.get(node.identifier);+ const start = node.position?.start.offset;+ const end = node.position?.end.offset;+ if (url !== undefined && start !== undefined && end !== undefined) {+ // Marked normalizes CRLF and bare CR before creating token.raw.+ const source = input.slice(start, end).replace(/\r\n?/g, "\n");+ uris.set(source, normalizeUri(url));+ }+ }+ return uris;+}export type MarkdownSegment =| { type: "prose"; content: string }@@ -19,6 +57,7 @@ export function splitMarkdown(input: string): MarkdownSegment[] {const tokens = marked.lexer(input);const out: MarkdownSegment[] = [];let proseBuffer = "";+ let imageUris: Map<string, string> | undefined;const flushProse = () => {const trimmed = proseBuffer.replace(/^\s+|\s+$/g, "");@@ -70,7 +109,9 @@ export function splitMarkdown(input: string): MarkdownSegment[] {const img = t as Tokens.Image;out.push({type: "image",- uri: img.href,+ // Only parse CommonMark destinations when an interactive image is+ // present. Marked-only extensions retain their lexer destination.+ uri: (imageUris ??= imageUrisBySource(input)).get(img.raw) ?? normalizeUri(img.href),alt: img.text ?? "",});} else {diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 286fd1c2dd..740ee6062b 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -61,6 +61,8 @@"i18next": "catalog:","input-otp-native": "^0.5.0","marked": "^18.0.3",+ "mdast-util-from-markdown": "2.0.3",+ "micromark-util-sanitize-uri": "2.0.1","nativewind": "^4.1.23","react": "19.2.3","react-dom": "19.2.3",diff --git a/packages/core/attachments/image-sequence.performance.test.ts b/packages/core/attachments/image-sequence.performance.test.tsnew file mode 100644index 0000000000..8390f54d6e--- /dev/null+++ b/packages/core/attachments/image-sequence.performance.test.ts@@ -0,0 +1,146 @@+// @vitest-environment node+import { writeFileSync } from "node:fs";+import { performance } from "node:perf_hooks";++// Timings are opt-in; default CI checks parser call counts instead.+// MULTICA_MARKDOWN_BENCHMARK=1 pnpm --filter @multica/core test attachments/image-sequence.performance.test.ts --maxWorkers=1 -t benchmarks+import { beforeEach, describe, expect, it, vi } from "vitest";++const { stats } = vi.hoisted(() => ({ stats: { calls: 0 } }));+vi.mock("mdast-util-from-markdown", async (importOriginal) => {+ const actual = await importOriginal<typeof import("mdast-util-from-markdown")>();+ return {+ ...actual,+ fromMarkdown: (...args: Parameters<typeof actual.fromMarkdown>) => {+ stats.calls++;+ return actual.fromMarkdown(...args);+ },+ };+});++let collectAttachmentSequence: typeof import("./image-sequence").collectAttachmentSequence;++beforeEach(async () => {+ vi.resetModules();+ ({ collectAttachmentSequence } = await import("./image-sequence"));+ stats.calls = 0;+});++const BLOCK_COUNT = 300;+const BLOCK_BYTES = 3072;+const PROSE = "The task is progressing. Review the implementation and tests before updating the issue.\n";++function timeline(imageEvery: number) {+ return Array.from({ length: BLOCK_COUNT }, (_, i) => {+ const prefix = `Comment ${i}\n\n`;+ const suffix = imageEvery && i % imageEvery === 0+ ? `\n\n`+ : "\n\nNo attachments in this update.\n";+ const prose = PROSE.repeat(40).slice(0, BLOCK_BYTES - prefix.length - suffix.length);+ return { id: `comment-${i}`, content: prefix + prose + suffix, attachments: [] };+ });+}++const scenarios = [+ { name: "no-images", imageEvery: 0, expected: 0 },+ { name: "sparse-images", imageEvery: 30, expected: 10 },+ { name: "all-images", imageEvery: 1, expected: 300 },+];++describe("large preview timelines", () => {+ it("does not parse unchanged or appended image-free comments", () => {+ const blocks = timeline(0);+ expect(collectAttachmentSequence(blocks, () => true)).toEqual([]);+ expect(collectAttachmentSequence([...blocks, { content: "Another update" }], () => true)).toEqual([]);+ expect(stats.calls).toBe(0);+ });++ it("only parses blocks that might contain images or file cards", () => {+ const blocks = timeline(30);+ expect(collectAttachmentSequence(blocks, () => true)).toHaveLength(10);+ expect(stats.calls).toBeLessThanOrEqual(10);+ });++ it("only parses new or edited content when rebuilding an image-dense timeline", () => {+ const blocks = timeline(1);+ const initial = collectAttachmentSequence(blocks, () => true);+ expect(initial).toHaveLength(BLOCK_COUNT);+ expect(stats.calls).toBe(BLOCK_COUNT);++ const updated = [+ ...blocks.map((block) => ({ ...block })),+ { id: "new-comment", content: "" },+ ];+ expect(collectAttachmentSequence(updated, () => true)).toEqual([+ ...initial,+ expect.objectContaining({ key: "https://cdn.example/new.png", blockId: "new-comment" }),+ ]);+ expect(stats.calls).toBe(BLOCK_COUNT + 1);++ updated[0] = { ...updated[0]!, content: "" };+ const edited = collectAttachmentSequence(updated, () => true);+ expect(edited[0]?.key).toBe("https://cdn.example/edited.png");+ expect(edited.slice(1, BLOCK_COUNT)).toEqual(initial.slice(1));+ expect(stats.calls).toBe(BLOCK_COUNT + 2);+ });++ it("reuses content whose image markers only appear in code", () => {+ const blocks = [{ content: "``" }];+ expect(collectAttachmentSequence(blocks, () => true)).toEqual([]);+ expect(collectAttachmentSequence(blocks, () => true)).toEqual([]);+ expect(stats.calls).toBe(1);+ });++ it("evicts the least recently used content after 500 entries", () => {+ const blocks = Array.from({ length: 501 }, (_, i) => ({+ content: ``,+ }));+ collectAttachmentSequence(blocks.slice(0, 500), () => true);+ expect(stats.calls).toBe(500);++ collectAttachmentSequence([blocks[0]], () => true);+ collectAttachmentSequence([blocks[500]], () => true);+ expect(stats.calls).toBe(501);+ collectAttachmentSequence([blocks[0]], () => true);+ expect(stats.calls).toBe(501);++ expect(collectAttachmentSequence([blocks[1]], () => true)[0]?.key)+ .toBe("https://cdn.example/lru-1.png");+ expect(stats.calls).toBe(502);+ });++ it.skipIf(process.env.MULTICA_MARKDOWN_BENCHMARK !== "1")("benchmarks 300 unique 3 KiB comments", () => {+ const results = scenarios.map(({ name, imageEvery, expected }) => {+ const blocks = timeline(imageEvery);+ expect(blocks.every((block) => Buffer.byteLength(block.content) === BLOCK_BYTES)).toBe(true);+ const coldStart = performance.now();+ const initial = collectAttachmentSequence(blocks, () => true);+ const cold_ms = performance.now() - coldStart;+ expect(initial).toHaveLength(expected);+ for (let i = 0; i < 3; i++) collectAttachmentSequence(blocks, () => true);+ const samples: number[] = [];+ for (let i = 0; i < 15; i++) {+ const start = performance.now();+ const items = collectAttachmentSequence(blocks, () => true);+ samples.push(performance.now() - start);+ expect(items).toHaveLength(expected);+ }+ samples.sort((a, b) => a - b);+ const appendedSamples: number[] = [];+ for (let i = 0; i < 15; i++) {+ const updated = [...blocks, { content: `` }];+ const start = performance.now();+ const items = collectAttachmentSequence(updated, () => true);+ appendedSamples.push(performance.now() - start);+ expect(items).toHaveLength(expected + 1);+ }+ appendedSamples.sort((a, b) => a - b);+ return { name, cold_ms, median_ms: samples[7], p95_ms: samples[14], min_ms: samples[0], append_median_ms: appendedSamples[7] };+ });+ const report = { node: process.version, blocks: BLOCK_COUNT, bytes_per_block: BLOCK_BYTES, warmups: 3, samples: 15, results };+ process.stdout.write("MARKDOWN_SEQUENCE_BENCHMARK " + JSON.stringify(report) + "\n");+ if (process.env.MULTICA_MARKDOWN_BENCHMARK_OUTPUT) {+ writeFileSync(process.env.MULTICA_MARKDOWN_BENCHMARK_OUTPUT, JSON.stringify(report, null, 2) + "\n");+ }+ }, 60_000);+});diff --git a/packages/core/attachments/image-sequence.test.ts b/packages/core/attachments/image-sequence.test.tsindex 88bb483c67..9512b9ee33 100644--- a/packages/core/attachments/image-sequence.test.ts+++ b/packages/core/attachments/image-sequence.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { describe, expect, it } from "vitest";import type { Attachment } from "../types/attachment";import {@@ -72,6 +73,20 @@ describe("matchAttachmentByURL", () => {expect(matchAttachmentByURL("/uploads/k?exp=9&sig=9", [legacy])).toBe(legacy);});+ it("matches encoded Markdown destinations to raw metadata without changing signed URLs", () => {+ const legacy = attachment({+ id: UUID_B,+ url: "https://cdn.example/图 v2.png",+ download_url: "https://cdn.example/signed.png?Signature=raw%2Bvalue",+ });+ const content = "";+ const items = collectImageSequence([{ content, attachments: [legacy], standalone: false }]);+ expect(items).toHaveLength(1);+ expect(items[0]?.attachment).toBe(legacy);+ expect(items[0]?.key).toBe(UUID_B);+ expect(items[0]?.url).toBe(legacy.download_url);+ });+it("returns undefined for unrelated URLs", () => {expect(matchAttachmentByURL("https://example.com/x.png", [a])).toBeUndefined();});@@ -201,6 +216,64 @@ describe("collectImageSequence", () => {]);});+ it.each([+ ["full reference", "![A][shot]", "[shot]: /a.png", "/a.png"],+ ["collapsed reference", "![shot][]", "[shot]: /a.png", "/a.png"],+ ["shortcut reference", "![shot]", "[shot]: /a.png", "/a.png"],+ ["normalized reference", "![A][ShOt Name]", "[shot name]: /a.png", "/a.png"],+ ["angle destination", "", "", "/chart%20v2.png"],+ ["Unicode destination", "", "", "/%E5%9B%BE.png"],+ ["balanced parentheses", ".png)", "", "/chart(v2).png"],+ ["escaped destination", String.raw`.png)`, "", "/chart(v2).png"],+ ["encoded destination", "", "", "/chart.png?a=1&b=2"],+ ])("collects %s using Markdown semantics", (_name, image, definition, url) => {+ const content = `${image}\n\n${definition}`;+ expect(collectImageSequence([{ content }]).map((item) => item.key)).toEqual([url]);+ });++ it("uses the first definition and keeps definitions local to each block", () => {+ const content = "![A][shot]\n\n[shot]: /first.png\n\n[shot]: /second.png";+ expect(collectImageSequence([{ content }, { content: "![B][shot]" }]).map((item) => item.key))+ .toEqual(["/first.png"]);+ });++ it("ignores HTML and file-card examples inside code", () => {+ const content = [+ "```html", '<img src="/hidden.png">', "!file[hidden.png](/hidden.png)", "```",+ "!file[visible.png](/visible.png)",+ ].join("\n");+ expect(collectImageSequence([{ content }]).map((item) => item.key)).toEqual(["/visible.png"]);+ });++ it("resolves reference attachments in occurrence order, not definition order", () => {+ const a = attachment({ id: UUID_A });+ const b = attachment({ id: UUID_B });+ const content = [+ "![B][second]", "![A][first]", "![again][second]",+ `[first]: /api/attachments/${UUID_A}/download`,+ `[second]: /api/attachments/${UUID_B}/download`,+ ].join("\n\n");+ const items = collectImageSequence([{ content, attachments: [a, b], standalone: false }]);+ expect(items.map((item) => item.key)).toEqual([UUID_B, UUID_A]);+ expect(items.map((item) => item.attachment)).toEqual([b, a]);+ });++ it.each([+ String.raw`\`,+ " ",+ "> ```md\n> \n> ```",+ "`\ncode`",+ "![undefined][missing]",+ ])("does not collect non-rendered images in %s", (content) => {+ expect(collectImageSequence([{ content }])).toEqual([]);+ });++ it("includes indented file cards that the renderer trims into images", () => {+ const content = " !file[photo.png](https://cdn.example/photo.png)";+ expect(collectImageSequence([{ content }]).map((item) => item.key))+ .toEqual(["https://cdn.example/photo.png"]);+ });+it("returns an empty sequence for empty input", () => {expect(collectImageSequence([])).toEqual([]);expect(collectImageSequence([null, undefined, {}])).toEqual([]);@@ -208,6 +281,39 @@ describe("collectImageSequence", () => {});describe("collectAttachmentSequence", () => {+ it("resolves current attachments, filters, and block ids when reusing body refs", () => {+ const content = "!file[report.pdf](https://cdn.example/report.pdf)";+ const blocks = [{ id: "first", content, standalone: false }];+ expect(collectImageSequence(blocks)).toEqual([]);+ expect(collectAttachmentSequence(blocks, () => true)).toEqual([+ expect.objectContaining({+ key: "https://cdn.example/report.pdf",+ blockId: "first",+ filename: "report.pdf",+ }),+ ]);++ const record = attachment({+ id: UUID_A,+ filename: "report.pdf",+ content_type: "application/pdf",+ url: "https://cdn.example/report.pdf",+ download_url: "https://cdn.example/report.pdf?signature=first",+ });+ const withRecord = [{ ...blocks[0]!, id: "second", attachments: [record] }];+ expect(collectAttachmentSequence(withRecord, () => true)).toEqual([+ expect.objectContaining({ key: UUID_A, url: record.download_url, attachment: record, blockId: "second" }),+ ]);++ const refreshed = { ...record, download_url: "https://cdn.example/report.pdf?signature=refreshed" };+ const result = collectAttachmentSequence([{ ...withRecord[0]!, attachments: [refreshed] }], () => true);+ expect(result[0]?.url).toBe(refreshed.download_url);+ expect(result[0]?.attachment).toBe(refreshed);+ result[0]!.filename = "changed by caller";+ expect(collectAttachmentSequence(blocks, () => true)[0]?.filename).toBe("report.pdf");+ expect(collectImageSequence(withRecord)).toEqual([]);+ });+// The web / desktop rule: anything the viewer can open.const previewable = ({ contentType, filename }: { contentType: string; filename: string }) =>isImageAttachment(contentType, filename) ||diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.tsindex c16c21f016..0e0d340110 100644--- a/packages/core/attachments/image-sequence.ts+++ b/packages/core/attachments/image-sequence.ts@@ -18,6 +18,8 @@* apps/mobile/CLAUDE.md: pure functions from @multica/core are importable).*/+import { fromMarkdown } from "mdast-util-from-markdown";+import { normalizeUri } from "micromark-util-sanitize-uri";import type { Attachment } from "../types/attachment";import {attachmentIdFromDownloadURL,@@ -83,10 +85,10 @@ function matchesAttachmentURL(attachmentURL?: string,): boolean {if (!embeddedURL || !attachmentURL) return false;- if (embeddedURL === attachmentURL) return true;+ if (normalizeUri(embeddedURL) === normalizeUri(attachmentURL)) return true;const embeddedStable = stripQueryAndFragment(embeddedURL);const attachmentStable = stripQueryAndFragment(attachmentURL);- return embeddedStable !== "" && embeddedStable === attachmentStable;+ return embeddedStable !== "" && normalizeUri(embeddedStable) === normalizeUri(attachmentStable);}/**@@ -177,47 +179,6 @@ export function orderStandaloneAttachments<T extends Pick<Attachment, "content_t// Inline image references-function blankOut(text: string): string {- // Newlines survive so line-anchored patterns below keep their line numbers.- return text.replace(/[^\n]/g, " ");-}--/**- * Blank every code span and fenced block, preserving offsets and line breaks.- *- * Without this, an `` shown as an EXAMPLE inside a fenced block —- * common in agent replies explaining markdown — would be counted as a real- * image and the reader would page onto something that was never rendered.- *- * Line scanner rather than one multiline regex: a backreferenced- * `(`{3,})[\s\S]*?\1` over agent output is a ReDoS shape, and this runs on- * every issue/chat render.- */-function maskCode(content: string): string {- const lines = content.split("\n");- let fence: string | null = null;- for (let i = 0; i < lines.length; i++) {- const line = lines[i]!;- const fenceMatch = /^[ \t]{0,3}(`{3,}|~{3,})/.exec(line);- if (fence !== null) {- lines[i] = blankOut(line);- const closes =- fenceMatch !== null &&- fenceMatch[1]![0] === fence[0] &&- fenceMatch[1]!.length >= fence.length;- if (closes) fence = null;- continue;- }- if (fenceMatch !== null) {- fence = fenceMatch[1]!;- lines[i] = blankOut(line);- continue;- }- lines[i] = line.replace(/(`+)[^`\n]*?\1/g, blankOut);- }- return lines.join("\n");-}-interface InlineRef {index: number;url: string;@@ -232,11 +193,10 @@ interface InlineRef {isFileCard: boolean;}-// ``. The URL char class stops at whitespace and `)` so a-// title never leaks into it; the optional <> wrapper is CommonMark's escape-// for URLs containing spaces.-const MARKDOWN_IMAGE_RE =- /!\[([^\]\n]*)\]\(\s*<([^>\n]*)>[^)]*\)|!\[([^\]\n]*)\]\(\s*([^)\s]+)[^)]*\)/g;+const INLINE_REF_CACHE_LIMIT = 500;+// Cache only content-derived refs, never resolved attachments or their signed URLs.+// Timeline updates can then resolve current metadata without reparsing old bodies.+const inlineRefCache = new Map<string, ReadonlyArray<InlineRef>>();// Raw `<img src=...>` — reachable because the readonly renderer runs// rehypeRaw + rehypeSanitize, and the sanitize schema keeps img.@@ -252,36 +212,88 @@ function unescapeLabel(label: string): string {return label.replace(/\\([[\]\\()])/g, "$1");}-function extractInlineRefs(rawContent: string): InlineRef[] {- if (!rawContent) return [];- const content = maskCode(rawContent);+function extractInlineRefs(rawContent: string): ReadonlyArray<InlineRef> {+ // Every supported image or file-card form has one of these markers. Most+ // timeline comments have none, so rebuilding a sequence need not parse them.+ if (+ !rawContent ||+ (!rawContent.includes("![") &&+ !rawContent.includes("!file[") &&+ !/<img\b/i.test(rawContent))+ ) return [];+ const cached = inlineRefCache.get(rawContent);+ if (cached) {+ inlineRefCache.delete(rawContent);+ inlineRefCache.set(rawContent, cached);+ return cached;+ }+ const tree = fromMarkdown(rawContent);const refs: InlineRef[] = [];+ type Node = typeof tree | (typeof tree.children)[number];+ const nodes: Node[] = [];+ const pending: Node[] = [tree];+ while (pending.length) {+ const node = pending.pop()!;+ nodes.push(node);+ if ("children" in node) {+ for (let i = node.children.length - 1; i >= 0; i--) {+ pending.push(node.children[i]!);+ }+ }+ }- for (const m of content.matchAll(MARKDOWN_IMAGE_RE)) {- // Two alternations: `<...>`-wrapped URL (groups 1/2) or bare (groups 3/4).- const alt = m[1] ?? m[3] ?? "";- const url = (m[2] ?? m[4] ?? "").trim();- if (!url) continue;- refs.push({- index: m.index ?? 0,- url,- filename: unescapeLabel(alt),- isFileCard: false,- });+ // The parser normalizes reference identifiers (case and whitespace). The+ // first definition wins, as in react-markdown's remark-parse pipeline.+ const definitions = new Map<string, string>();+ for (const node of nodes) {+ if (node.type === "definition" && !definitions.has(node.identifier)) {+ definitions.set(node.identifier, node.url);+ }}- for (const m of content.matchAll(HTML_IMAGE_RE)) {- const url = (m[1] ?? m[2] ?? m[3] ?? "").trim();- if (!url) continue;- refs.push({- index: m.index ?? 0,- url,- filename: "",- isFileCard: false,- });+ const codeRanges: Array<{ start: number; end: number }> = [];+ for (const node of nodes) {+ const index = node.position?.start.offset ?? 0;+ if (node.type === "image" || node.type === "imageReference") {+ const destination = node.type === "image"+ ? node.url+ : definitions.get(node.identifier);+ // mdast-util-to-hast applies the same normalization before RichContent's+ // img renderer sees the URL (spaces, Unicode, existing percent escapes).+ if (destination) {+ refs.push({+ index,+ url: normalizeUri(destination),+ filename: node.alt ?? "",+ isFileCard: false,+ });+ }+ } else if (node.type === "html") {+ for (const m of node.value.matchAll(HTML_IMAGE_RE)) {+ const url = (m[1] ?? m[2] ?? m[3] ?? "").trim();+ if (url) {+ refs.push({ index: index + m.index, url, filename: "", isFileCard: false });+ }+ }+ } else if (node.type === "code" || node.type === "inlineCode") {+ // File-card preprocessing trims indentation and renders indented cards.+ // Fenced blocks and code spans still display their contents literally.+ const fenced = node.type === "code" && /^ {0,3}(?:`{3}|~{3})/.test(rawContent.slice(index));+ if (node.type === "inlineCode" || fenced) {+ const end = node.position?.end.offset ?? index;+ codeRanges.push({ start: index, end });+ }+ }}- for (const m of content.matchAll(FILE_CARD_LINE_RE)) {+ let codeIndex = 0;+ for (const m of rawContent.matchAll(FILE_CARD_LINE_RE)) {+ const index = m.index;+ while (codeIndex < codeRanges.length && codeRanges[codeIndex]!.end <= index) {+ codeIndex++;+ }+ const code = codeRanges[codeIndex];+ if (code && index + m[0].length > code.start) continue;const url = (m[2] ?? "").trim();if (!url) continue;refs.push({@@ -292,7 +304,12 @@ function extractInlineRefs(rawContent: string): InlineRef[] {});}- return refs.sort((a, b) => a.index - b.index);+ refs.sort((a, b) => a.index - b.index);+ inlineRefCache.set(rawContent, refs);+ if (inlineRefCache.size > INLINE_REF_CACHE_LIMIT) {+ inlineRefCache.delete(inlineRefCache.keys().next().value!);+ }+ return refs;}// Sequence@@ -302,7 +319,7 @@ export interface ImageSequenceItem {/*** Identity used to open the sequence at the clicked attachment. The* attachment id when the reference resolves to a record, otherwise the URL- * as written in the body — matching what the renderer knows at click time.+ * passed to the image/card renderer after Markdown decoding/normalization.*/key: string;/** Best-known URL. Callers holding `attachment` should prefer re-resolving. */diff --git a/packages/core/package.json b/packages/core/package.jsonindex 47be3c134d..fcbcb6382c 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -190,6 +190,8 @@"@formatjs/intl-localematcher": "catalog:","@tanstack/react-query": "catalog:","i18next": "catalog:",+ "mdast-util-from-markdown": "catalog:",+ "micromark-util-sanitize-uri": "catalog:","posthog-js": "catalog:","react-i18next": "catalog:","yaml": "catalog:",diff --git a/packages/ui/markdown/linkify.performance.test.ts b/packages/ui/markdown/linkify.performance.test.tsnew file mode 100644index 0000000000..4422829289--- /dev/null+++ b/packages/ui/markdown/linkify.performance.test.ts@@ -0,0 +1,69 @@+// @vitest-environment node+import { writeFileSync } from 'node:fs'+import { performance } from 'node:perf_hooks'++// MULTICA_MARKDOWN_BENCHMARK=1 pnpm --filter @multica/ui test markdown/linkify.performance.test.ts --maxWorkers=1 -t benchmarks+import { describe, expect, it, vi } from 'vitest'++const { stats } = vi.hoisted(() => ({ stats: { calls: 0 } }))+vi.mock('mdast-util-from-markdown', async (importOriginal) => {+ const actual = await importOriginal<typeof import('mdast-util-from-markdown')>()+ return {+ ...actual,+ fromMarkdown: (...args: Parameters<typeof actual.fromMarkdown>) => {+ stats.calls+++ return actual.fromMarkdown(...args)+ },+ }+})++import { findMarkdownLinkRanges, preprocessLinks } from './linkify'++function comments(definitions: boolean) {+ return Array.from({ length: 300 }, (_, i) => {+ const prefix = `Comment ${i}\n\n`+ const suffix = definitions ? `\n\n[shot]: https://cdn.example/${i}.png` : '\n\nhttps://outside.example'+ return prefix + 'Review the implementation and tests.\n'.repeat(100).slice(0, 3072 - prefix.length - suffix.length) + suffix+ })+}++describe('linkify reference-definition precheck', () => {+ it('does not parse ordinary comments or existing inline links for definitions', () => {+ stats.calls = 0+ for (const content of comments(false)) findMarkdownLinkRanges(content)+ expect(preprocessLinks('[existing](https://cdn.example/a.png)')).toBe('[existing](https://cdn.example/a.png)')+ expect(stats.calls).toBe(0)+ })++ it.each([+ '[shot]: https://cdn.example/a.png',+ '[shot\nname]: https://cdn.example/a.png',+ '> [shot]: https://cdn.example/a.png',+ '- [shot]: https://cdn.example/a.png',+ '[a\\]b]: https://cdn.example/a.png',+ ])('still protects the definition in %s', (content) => {+ stats.calls = 0+ expect(preprocessLinks(content)).toBe(content)+ expect(stats.calls).toBeLessThanOrEqual(1)+ })++ it.skipIf(process.env.MULTICA_MARKDOWN_BENCHMARK !== '1')('benchmarks link-range discovery for 300 unique 3 KiB comments', () => {+ const results = [false, true].map((definitions) => {+ const blocks = comments(definitions)+ for (let i = 0; i < 3; i++) blocks.forEach(findMarkdownLinkRanges)+ const samples: number[] = []+ for (let i = 0; i < 15; i++) {+ const start = performance.now()+ blocks.forEach(findMarkdownLinkRanges)+ samples.push(performance.now() - start)+ }+ samples.sort((a, b) => a - b)+ return { name: definitions ? 'with-definitions' : 'no-definitions', median_ms: samples[7], p95_ms: samples[14], min_ms: samples[0] }+ })+ const report = { node: process.version, blocks: 300, bytes_per_block: 3072, warmups: 3, samples: 15, results }+ process.stdout.write("MARKDOWN_LINKIFY_BENCHMARK " + JSON.stringify(report) + "\n")+ if (process.env.MULTICA_MARKDOWN_BENCHMARK_OUTPUT) {+ writeFileSync(process.env.MULTICA_MARKDOWN_BENCHMARK_OUTPUT, JSON.stringify(report, null, 2) + "\n")+ }+ }, 60_000)+})diff --git a/packages/ui/markdown/linkify.test.ts b/packages/ui/markdown/linkify.test.tsindex cc68f9b85f..e6dd47fe43 100644--- a/packages/ui/markdown/linkify.test.ts+++ b/packages/ui/markdown/linkify.test.ts@@ -168,3 +168,17 @@ it.each(['x', ''])('scans repeated list prefixes without backtracking (%j)', (su)expect(performance.now() - start).toBeLessThan(250)})++describe('reference definitions during linkification', () => {+ it.each([+ '[shot]: https://cdn.example/chart.png',+ '[shot]: <https://cdn.example/chart(v2).png> "https://title.example"',+ '[shot]:\n https://cdn.example/chart.png',+ '> [shot]: https://cdn.example/chart.png',+ ])('preserves %s while still linking bare prose URLs', (definition) => {+ const source = `![A][shot]\n\n${definition}\n\nhttps://outside.example`+ expect(preprocessLinks(source)).toBe(+ `![A][shot]\n\n${definition}\n\n[https://outside.example](https://outside.example)`,+ )+ })+})diff --git a/packages/ui/markdown/linkify.ts b/packages/ui/markdown/linkify.tsindex 3b8f8f3648..5bc68534f4 100644--- a/packages/ui/markdown/linkify.ts+++ b/packages/ui/markdown/linkify.ts@@ -217,6 +217,20 @@ function findInlineLinkEnd(text: string, openParenIndex: number): number {*/export function findMarkdownLinkRanges(text: string): CodeRange[] {const ranges: CodeRange[] = []+ // Reference destinations are already links. Wrapping their URLs again+ // corrupts the definition before the Markdown renderer resolves images.+ // Even multiline labels and definitions in containers must contain `]:`.+ const pending: Nodes[] = text.includes(']:') ? [fromMarkdown(text)] : []+ while (pending.length > 0) {+ const node = pending.pop()!+ if (node.type === 'definition') {+ const start = node.position?.start.offset+ const end = node.position?.end.offset+ if (start !== undefined && end !== undefined) ranges.push({ start, end })+ } else if ('children' in node) {+ for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]!)+ }+ }for (let i = 0; i < text.length; i++) {if (text[i] !== '[' || isEscaped(text, i)) continuediff --git a/packages/views/rich-content/image-preview-sequence.test.tsx b/packages/views/rich-content/image-preview-sequence.test.tsxnew file mode 100644index 0000000000..7caf91b5a3--- /dev/null+++ b/packages/views/rich-content/image-preview-sequence.test.tsx@@ -0,0 +1,136 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { Attachment } from "@multica/core/types";+import { configStore } from "@multica/core/config";++vi.mock("../issues/hooks", () => ({+ useResolveIssueIdentifier: () => null,+}));++vi.mock("../i18n", async () => {+ const editor = (await import("../locales/en/editor.json")).default;+ return {+ useT: () => ({+ t: (select: (bundle: typeof editor) => string, params?: Record<string, string | number>) => {+ const value = select(editor);+ return params ? value.replace(/\{\{(\w+)\}\}/g, (_, key: string) => String(params[key])) : value;+ },+ }),+ useTimeAgo: () => "just now",+ };+});++vi.mock("@multica/core/api", () => ({+ api: { getBaseUrl: () => "", getAttachmentTextContent: vi.fn() },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({+ issueDetail: (id: string) => `/acme/issues/${id}`,+ projectDetail: (id: string) => `/acme/projects/${id}`,+ }),+ useWorkspaceSlug: () => "acme",+}));++vi.mock("../navigation", () => ({+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ resolveClickIntent: () => "push",+ useAppOrigin: () => null,+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));++vi.mock("../issues/components/issue-mention-card", () => ({+ IssueMentionCard: ({ issueId }: { issueId: string }) => <span>{issueId}</span>,+}));++vi.mock("../projects/components/project-chip", () => ({+ ProjectChip: ({ projectId }: { projectId: string }) => <span>{projectId}</span>,+}));++vi.mock("../editor/link-hover-card", () => ({+ useLinkHover: () => ({}),+ LinkHoverCard: () => null,+}));++vi.mock("../editor/use-download-attachment", () => ({+ useDownloadAttachment: () => vi.fn(),+}));++import { RichContent } from "./rich-content";+import { collectPreviewSequence, PreviewSequenceProvider } from "../editor/preview-sequence-context";++const ID = "11111111-1111-4111-8111-111111111111";+const attachment: Attachment = {+ id: ID,+ workspace_id: "ws",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "u",+ filename: "reference.png",+ content_type: "image/png",+ size_bytes: 10,+ url: "https://cdn.example/reference.png",+ download_url: "https://cdn.example/reference.png",+ markdown_url: `/api/attachments/${ID}/download`,+ created_at: "2026-11-06T00:00:00Z",+};++beforeEach(() => {+ configStore.setState({ cdnDomain: "", cdnSigned: false });+});++describe("RichContent image preview sequence", () => {+ it.each([+ ["reference attachment", "![Reference][shot]", `[shot]: /api/attachments/${ID}/download`, [attachment], attachment.markdown_url, "Reference"],+ ["external reference", "![Reference][shot]", "[shot]: https://cdn.example/chart.png", [], "https://cdn.example/chart.png", "Reference"],+ ["indented file-card image", " !file[photo.png](https://cdn.example/photo.png)", "", [], "https://cdn.example/photo.png", "photo.png"],+ ["angle destination", "", "", [], "/chart%20v2.png", "Reference"],+ ["escaped destination", String.raw`.png)`, "", [], "/chart(v2).png", "Reference"],+ ["parenthesized URL", ".png)", "", [], "/chart(v2).png", "Reference"],+ ] as const)("opens the %s in the shared viewer and pages through rendered images", (_name, image, definition, attachments, expectedSrc, imageAlt) => {+ const content = [+ "",+ image,+ "",+ String.raw`\`,+ " ",+ "```md\n\n```",+ definition,+ ].join("\n\n");+ const records = [...attachments];+ const items = collectPreviewSequence([{ content, attachments: records, standalone: false }]);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ render(+ <QueryClientProvider client={client}>+ <PreviewSequenceProvider items={items}>+ <RichContent content={content} attachments={records} />+ </PreviewSequenceProvider>+ </QueryClientProvider>,+ );+ expect(screen.getAllByRole("img")).toHaveLength(3);+ const reference = screen.getByRole("img", { name: imageAlt });+ expect(reference).toHaveAttribute("src", expectedSrc);+ fireEvent.click(reference);+ const dialog = screen.getByRole("dialog");+ expect(dialog).toHaveAttribute("aria-label", attachments.length ? "reference.png" : imageAlt);+ expect(within(dialog).getByText("2 / 3")).toBeInTheDocument();+ fireEvent.click(within(dialog).getByRole("button", { name: "Next" }));+ expect(within(dialog).getByText("3 / 3")).toBeInTheDocument();+ expect(within(dialog).getByRole("img", { name: "Last" })).toHaveAttribute("src", "/last.png");+ expect(within(dialog).getByRole("button", { name: "Next" })).toBeDisabled();+ fireEvent.click(within(dialog).getByRole("button", { name: "Previous" }));+ expect(within(dialog).getByText("2 / 3")).toBeInTheDocument();+ fireEvent.click(within(dialog).getByRole("button", { name: "Previous" }));+ expect(within(dialog).getByText("1 / 3")).toBeInTheDocument();+ expect(within(dialog).getByRole("button", { name: "Previous" })).toBeDisabled();+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dff0541b06..9a91cdf6ad 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -57,6 +57,12 @@ catalogs:katex:specifier: ^0.16.45version: 0.16.45+ mdast-util-from-markdown:+ specifier: ^2.0.3+ version: 2.0.3+ micromark-util-sanitize-uri:+ specifier: ^2.0.1+ version: 2.0.1mermaid:specifier: ^11.14.0version: 11.14.0@@ -463,6 +469,12 @@ importers:marked:specifier: ^18.0.3version: 18.0.3+ mdast-util-from-markdown:+ specifier: 2.0.3+ version: 2.0.3+ micromark-util-sanitize-uri:+ specifier: 2.0.1+ version: 2.0.1nativewind:specifier: ^4.1.23version: 4.2.4([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]([email protected]))@@ -651,6 +663,12 @@ importers:i18next:specifier: 'catalog:'version: 26.0.8(@typescript/[email protected])+ mdast-util-from-markdown:+ specifier: 'catalog:'+ version: 2.0.3+ micromark-util-sanitize-uri:+ specifier: 'catalog:'+ version: 2.0.1posthog-js:specifier: 'catalog:'version: 1.369.3diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex b530fe6f3f..6b34e220ed 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -23,6 +23,8 @@ catalog:i18next: ^26.0.8jsdom: ^29.0.1katex: ^0.16.45+ mdast-util-from-markdown: ^2.0.3+ micromark-util-sanitize-uri: ^2.0.1mermaid: ^11.14.0postcss: ^8posthog-js: ^1.176.1