diff --git a/frontend/src/lib/components/MarkdownCodeBlock.svelte b/frontend/src/lib/components/MarkdownCodeBlock.svelte
index 26022e21cf..46ba73c281 100644
--- a/frontend/src/lib/components/MarkdownCodeBlock.svelte
+++ b/frontend/src/lib/components/MarkdownCodeBlock.svelte
@@ -28,12 +28,15 @@
applyButtonIcon = undefined,
// Render ```mermaid blocks as diagrams. Off by default so untrusted
// markdown surfaces don't execute mermaid — the chat opts in.
- renderMermaid = false
+ renderMermaid = false,
+ // Draw diagrams in the light theme whatever the app's theme (printing).
+ lightMermaid = false
}: {
showApplyButton?: boolean
onApplyCode?: () => void
applyButtonIcon?: typeof ClipboardCopy
renderMermaid?: boolean
+ lightMermaid?: boolean
} = $props()
const astNode = getAstNode()
@@ -131,7 +134,7 @@
{#if renderMermaid && language === 'mermaid'}
-
+
{:else}
- import { Check, Copy, Download } from 'lucide-svelte'
+ import { Check, Copy, Download, FileDown } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import { copyToClipboard, download } from '$lib/utils'
import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB'
+ import { printArtifact } from './printArtifact'
interface Props {
name: string
@@ -31,11 +32,23 @@
title="Copy raw markdown"
dropdownItems={[
{
- label: 'Download as .md',
+ label: `Download as .${kind}`,
icon: Download,
onClick: () => download(artifactFilename({ name, kind }), content, artifactMimeType(kind)),
disabled
- }
+ },
+ // Markdown only: an html artifact is agent-written markup, and printing it would run its
+ // scripts in this origin.
+ ...(kind === 'md'
+ ? [
+ {
+ label: 'Download as PDF',
+ icon: FileDown,
+ onClick: () => printArtifact(name, content),
+ disabled
+ }
+ ]
+ : [])
]}
>
{copied ? 'Copied' : 'Copy'}
diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte
new file mode 100644
index 0000000000..f07c6f643f
--- /dev/null
+++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte
@@ -0,0 +1,14 @@
+
+
+
+
+
diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte
new file mode 100644
index 0000000000..261b39febf
--- /dev/null
+++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte
@@ -0,0 +1,7 @@
+
+
+
+
diff --git a/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts b/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts
new file mode 100644
index 0000000000..0d2099a3ea
--- /dev/null
+++ b/frontend/src/lib/components/copilot/chat/artifacts/printArtifact.ts
@@ -0,0 +1,115 @@
+import { mount, unmount, tick } from 'svelte'
+import ArtifactPrintBody from './ArtifactPrintBody.svelte'
+
+/**
+ * Opens the browser's print dialog on a markdown artifact, where "Save as PDF" writes the file.
+ * The browser's print engine keeps the text selectable and the links live, which a
+ * canvas-rendered PDF would not.
+ *
+ * The document is rendered into a hidden iframe with the viewer's renderer rather than printing
+ * this page: the app's own print would include the whole session layout. The iframe copies
+ * this page's stylesheets, and its carries no `dark` class, so the PDF always uses the
+ * light theme.
+ */
+// Set while the iframe is being prepared, so a second click before the dialog opens does not
+// stack a second print behind the first.
+let preparing = false
+
+export async function printArtifact(name: string, content: string): Promise {
+ if (preparing) return
+ preparing = true
+ try {
+ await preparePrint(name, content)
+ } finally {
+ preparing = false
+ }
+}
+
+async function preparePrint(name: string, content: string): Promise {
+ const iframe = document.createElement('iframe')
+ iframe.setAttribute('aria-hidden', 'true')
+ iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0'
+ document.body.appendChild(iframe)
+
+ const doc = iframe.contentDocument
+ const win = iframe.contentWindow
+ if (!doc || !win) {
+ iframe.remove()
+ return
+ }
+ // The print dialog proposes the title as the PDF's file name.
+ doc.title = name
+ for (const node of Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))) {
+ doc.head.appendChild(node.cloneNode(true))
+ }
+ const page = doc.createElement('style')
+ // Without exact color adjust, browsers drop code-block and callout backgrounds. The break
+ // rules keep a code block, diagram, callout or table row whole and a heading with what follows.
+ // Code blocks scroll on screen; paper cannot, so they wrap and lose their height cap.
+ page.textContent = `
+ @page { margin: 16mm }
+ html, body { background: white }
+ body { margin: 0; print-color-adjust: exact; -webkit-print-color-adjust: exact }
+ pre, svg, blockquote, tr, .markdown-alert { break-inside: avoid }
+ h1, h2, h3, h4, h5, h6 { break-after: avoid }
+ .not-prose, .not-prose * { overflow: visible !important; max-height: none !important }
+ .not-prose pre, .not-prose code { white-space: pre-wrap !important; overflow-wrap: anywhere }
+ `
+ doc.head.appendChild(page)
+
+ // Printing before the stylesheets load gives an unstyled PDF; the cap keeps a link that
+ // never settles from swallowing the click.
+ const stylesheets = Array.from(
+ doc.head.querySelectorAll('link[rel="stylesheet"]'),
+ (link) =>
+ new Promise((resolve) => {
+ link.addEventListener('load', () => resolve(), { once: true })
+ link.addEventListener('error', () => resolve(), { once: true })
+ })
+ )
+ await Promise.race([
+ Promise.all(stylesheets),
+ new Promise((resolve) => setTimeout(resolve, 3000))
+ ])
+
+ const component = mount(ArtifactPrintBody, { target: doc.body, props: { content } })
+ await tick()
+ await diagramsSettled(doc)
+ await imagesSettled(doc)
+ await doc.fonts?.ready
+
+ const cleanup = () => {
+ unmount(component)
+ iframe.remove()
+ }
+ // print() blocks until the dialog closes in Chromium and Firefox, but returns at once in
+ // Safari, so the iframe is removed on afterprint rather than after the call.
+ win.addEventListener('afterprint', cleanup, { once: true })
+ win.focus()
+ win.print()
+}
+
+/** The print dialog snapshots the document as it is, so an image still loading is missing from
+ * the PDF. A broken image settles through `error`; the cap covers one that never answers. */
+async function imagesSettled(doc: Document): Promise {
+ const pending = Array.from(doc.images)
+ .filter((img) => !img.complete)
+ .map(
+ (img) =>
+ new Promise((resolve) => {
+ img.addEventListener('load', () => resolve(), { once: true })
+ img.addEventListener('error', () => resolve(), { once: true })
+ })
+ )
+ await Promise.race([Promise.all(pending), new Promise((resolve) => setTimeout(resolve, 10_000))])
+}
+
+/** Mermaid draws asynchronously; printing before it lands puts the diagram source in the PDF.
+ * A diagram that fails to parse settles too (as its source), so this waits only on renders
+ * still in flight; the cap covers one that never returns. */
+async function diagramsSettled(doc: Document): Promise {
+ const deadline = Date.now() + 10_000
+ while (doc.querySelector('[data-mermaid-pending="true"]') && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+}
diff --git a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte
index e17cdbcb36..d39ab52bf7 100644
--- a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte
+++ b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte
@@ -7,7 +7,7 @@
import { ClipboardCopy, Download, Maximize2, Minus, Plus, RotateCcw } from 'lucide-svelte'
import type { PanZoom } from 'panzoom'
- let { code }: { code: string } = $props()
+ let { code, forceLight = false }: { code: string; forceLight?: boolean } = $props()
const isDarkMode = useIsDarkMode()
@@ -19,6 +19,9 @@
// Monotonic token so an earlier-started render that resolves late can't
// overwrite the result of a newer one (out-of-order async on rapid code/theme changes).
let renderSeq = 0
+ // False while a render is in flight, true once it drew or failed. Exposed as
+ // data-mermaid-pending so a print can wait for diagrams without counting fences.
+ let settled = $state(false)
let expanded = $state(false)
@@ -27,8 +30,10 @@
if (!source?.trim()) {
svg = undefined
renderedCode = undefined
+ settled = true
return
}
+ settled = false
try {
const mermaid = (await import('mermaid')).default
mermaid.initialize({
@@ -65,11 +70,13 @@
// Parse failure (often a partial block still streaming in): fall back to the
// raw source. `showSvg` already hides any previous diagram since `renderedCode`
// no longer matches the current `code`.
+ } finally {
+ if (seq === renderSeq) settled = true
}
}
$effect(() => {
- void render(code, isDarkMode.val)
+ void render(code, !forceLight && isDarkMode.val)
})
// Only show the diagram while it corresponds to the current source.
@@ -130,8 +137,8 @@
{#if showSvg}
-