Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mermaid-copy-clipboard-images.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Fix Mermaid Copy PNG/SVG in VS Code webviews so they put images on the clipboard instead of failing or copying SVG markup.
13 changes: 9 additions & 4 deletions packages/ui/src/kilocode/markdown-mermaid-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,15 @@ function Item(props: { label: string; onSelect: () => void }) {
export function MermaidActions(props: Props) {
const [copied, setCopied] = createSignal(false)
const copy = (run: () => Promise<void>) => {
void run().then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
void run()
.then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
.catch((err) => {
// Avoid unhandledrejection; Copy PNG used to fail silently under webview CSP.
console.warn("Mermaid copy failed", err)
})
}

return (
Expand Down
24 changes: 24 additions & 0 deletions packages/ui/src/kilocode/markdown-mermaid-data-url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test"
import { dataUrlToBlob } from "./markdown-mermaid-data-url"

describe("dataUrlToBlob", () => {
test("decodes base64 payload and preserves mime type", async () => {
const bytes = Uint8Array.from([0x89, 0x50, 0x4e, 0x47])
const dataUrl = `data:image/png;base64,${Buffer.from(bytes).toString("base64")}`
const blob = dataUrlToBlob(dataUrl)

expect(blob.type).toBe("image/png")
expect(blob.size).toBe(bytes.length)
expect(new Uint8Array(await blob.arrayBuffer())).toEqual(bytes)
})

test("defaults mime when the data URL omits it", async () => {
const blob = dataUrlToBlob(`data:;base64,${Buffer.from("hi").toString("base64")}`)
expect(blob.type).toBe("application/octet-stream")
expect(await blob.text()).toBe("hi")
})

test("rejects data URLs without a comma separator", () => {
expect(() => dataUrlToBlob("data:image/png;base64")).toThrow("Unable to export Mermaid diagram.")
})
})
12 changes: 12 additions & 0 deletions packages/ui/src/kilocode/markdown-mermaid-data-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// VS Code webview CSP blocks fetch(data:...); decode locally for clipboard/export helpers.
export function dataUrlToBlob(dataUrl: string): Blob {
const comma = dataUrl.indexOf(",")
if (comma < 0) throw new Error("Unable to export Mermaid diagram.")
const header = dataUrl.slice(0, comma)
const data = dataUrl.slice(comma + 1)
const mime = /^data:([^;,]*)/.exec(header)?.[1] || "application/octet-stream"
const binary = atob(data)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
return new Blob([bytes], { type: mime })
}
44 changes: 37 additions & 7 deletions packages/ui/src/kilocode/markdown-mermaid.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import DOMPurify from "dompurify"
import { fnv1a } from "../context/marked"
import { mountMermaidActions } from "./markdown-mermaid-actions"
import { dataUrlToBlob } from "./markdown-mermaid-data-url"

// DOMPurify >= 3.1.7 dropped foreignObject from the default HTML integration
// points, which caused the inner <div> / <span> / <p> labels Mermaid renders
Expand Down Expand Up @@ -303,14 +304,43 @@ async function copyText(text: string) {
await navigator.clipboard.writeText(text)
}

async function copyPng(svg: SVGSVGElement) {
const url = await png(svg)
const blob = await (await fetch(url)).blob()
function supportsClipboardType(type: string) {
return typeof ClipboardItem !== "undefined" && "supports" in ClipboardItem && ClipboardItem.supports(type)
}

async function writeClipboard(items: Record<string, Blob>) {
if (typeof ClipboardItem === "undefined") {
await navigator.clipboard.writeText(serialize(svg))
return
throw new Error("ClipboardItem is unavailable.")
}
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })])
await navigator.clipboard.write([new ClipboardItem(items)])
}

async function writePngClipboard(svg: SVGSVGElement) {
await writeClipboard({ "image/png": dataUrlToBlob(await png(svg)) })
}

async function copySvg(svg: SVGSVGElement) {
const markup = serialize(svg)
// Prefer a rich ClipboardItem so paste targets can pick SVG, PNG, or text.
// Previous writeText(serialize(svg)) always pasted markup instead of an image.
const pngBlob = dataUrlToBlob(await png(svg))
const items: Record<string, Blob> = {
"image/png": pngBlob,
"text/plain": new Blob([markup], { type: "text/plain" }),
}
if (supportsClipboardType("image/svg+xml")) {
items["image/svg+xml"] = new Blob([markup], { type: "image/svg+xml" })
}
try {
await writeClipboard(items)
} catch {
// Some hosts reject multi-type items; keep an image on the clipboard.
await writeClipboard({ "image/png": pngBlob })
}
}

async function copyPng(svg: SVGSVGElement) {
await writePngClipboard(svg)
}

function renderActions(el: HTMLDivElement, pre: HTMLPreElement, source: string, labels: MermaidLabels) {
Expand All @@ -329,7 +359,7 @@ function renderActions(el: HTMLDivElement, pre: HTMLPreElement, source: string,
mountMermaidActions(el, {
labels,
onCopySource: () => copyText(sourceText),
onCopySvg: () => copyText(sourceSvg()),
onCopySvg: () => copySvg(svg),
onCopyPng: () => copyPng(svg),
onDownloadSvg: () => save(sourceSvgUrl(), "mermaid-diagram.svg"),
onDownloadPng: async () => save(await png(svg), "mermaid-diagram.png"),
Expand Down
Loading