fix(web): preserve blob-backed images in shared exports (#2282)

* fix(web): preserve blob-backed images in shared exports

* test(web): include blob export spec in CI
This commit is contained in:
Ananovo
2026-11-05 07:27:45 +08:00
committed by GitHub
parent ec414ce474
commit f95dcee05e
5 changed files with 217 additions and 3 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
# Required by cli/src/utils/windowsProcessTree.pwsh.test.ts — image
# inspect alone does not pull; silent skip was fake B1 coverage (#1911).
- run: docker pull mcr.microsoft.com/powershell:latest
- run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts
- run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts attachment-removal.spec.ts history-navigation-layout.spec.ts share-turn.spec.ts share-turn-blob-export.spec.ts composer-attachment-controls.spec.ts image-preview-back.spec.ts
- run: bun run test
# Serial runner-integration suite: starts real detached runner/session
+62
View File
@@ -0,0 +1,62 @@
import { expect, test, type Page } from '@playwright/test'
import { readFile } from 'node:fs/promises'
async function countMagentaPixels(page: Page, bytes: Buffer): Promise<number> {
return page.evaluate(async (base64) => {
const image = new Image()
image.src = `data:image/png;base64,${base64}`
await image.decode()
const canvas = document.createElement('canvas')
canvas.width = image.naturalWidth
canvas.height = image.naturalHeight
const context = canvas.getContext('2d')
if (!context) throw new Error('Missing canvas context')
context.drawImage(image, 0, 0)
const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data
let count = 0
for (let index = 0; index < pixels.length; index += 4) {
if (pixels[index] > 220 && pixels[index + 1] < 80 && pixels[index + 2] > 130) count += 1
}
return count
}, bytes.toString('base64'))
}
async function exportPng(page: Page, outputPath: string): Promise<Buffer> {
const downloadPromise = page.waitForEvent('download')
await page.getByRole('dialog').getByRole('button', { name: /^(Download|下载)$/ }).click()
const download = await downloadPromise
await download.saveAs(outputPath)
return readFile(outputPath)
}
async function openBlobFixture(page: Page, mode: 'blob' | 'data'): Promise<void> {
const blobMode = mode === 'data' ? '&blobMode=data' : ''
await page.goto(`/e2e-fixtures/share-turn-fixture.html?blobImage=1&inlineWrap=1${blobMode}`)
const sourceImage = page.getByTestId('source-turn').getByAltText('Blob export fixture')
await expect(sourceImage).toHaveAttribute('src', mode === 'data' ? /^data:/ : /^blob:/)
await expect.poll(() => sourceImage.evaluate((image: HTMLImageElement) => image.complete && image.naturalWidth > 0)).toBe(true)
await page.getByRole('button', { name: 'Open share preview' }).click()
const previewImage = page.getByRole('dialog').getByAltText('Blob export fixture')
await expect(previewImage).toBeVisible()
await expect.poll(() => previewImage.evaluate((image: HTMLImageElement) => image.complete && image.naturalWidth > 0)).toBe(true)
}
test('preserves blob images in inline-code share exports', async ({ page }, testInfo) => {
test.setTimeout(60_000)
await page.setViewportSize({ width: 1280, height: 2200 })
await openBlobFixture(page, 'blob')
await page.getByRole('dialog').screenshot({ path: testInfo.outputPath('preview-blob.png') })
const blobBytes = await exportPng(page, testInfo.outputPath('export-blob.png'))
const blobMagentaPixels = await countMagentaPixels(page, blobBytes)
await openBlobFixture(page, 'data')
const dataBytes = await exportPng(page, testInfo.outputPath('export-data.png'))
const dataMagentaPixels = await countMagentaPixels(page, dataBytes)
console.log(`blob_magenta_pixels=${blobMagentaPixels} data_magenta_pixels=${dataMagentaPixels}`)
expect(blobBytes.subarray(1, 4).toString()).toBe('PNG')
expect(dataBytes.subarray(1, 4).toString()).toBe('PNG')
expect(blobMagentaPixels).toBeGreaterThan(10_000)
expect(dataMagentaPixels).toBeGreaterThan(10_000)
})
+62 -1
View File
@@ -1,4 +1,4 @@
import { useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom/client'
import '../src/index.css'
import { ShareTurnDialog } from '../src/components/AssistantChat/ShareTurnDialog'
@@ -26,6 +26,13 @@ const portraitFixtureImage = 'data:image/svg+xml;charset=utf-8,' + encodeURIComp
</svg>
`)
const blobExportFixture = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360">
<rect width="640" height="360" fill="#ff2fa8"/>
<text x="320" y="188" text-anchor="middle" fill="white" font-family="system-ui" font-size="38" font-weight="700">BLOB EXPORT FIXTURE</text>
</svg>
`)
const includeGeneratedFile = new URLSearchParams(window.location.search).get('generatedFile') === '1'
const generatedFileIsLoaded = new URLSearchParams(window.location.search).get('generatedFileState') === 'loaded'
@@ -106,9 +113,12 @@ function App() {
const sourceRef = useRef<HTMLDivElement>(null)
const [snapshots, setSnapshots] = useState<Snapshot[]>([])
const [open, setOpen] = useState(false)
const [blobImageSrc, setBlobImageSrc] = useState<string | null>(null)
const searchParams = new URLSearchParams(window.location.search)
const wideSource = searchParams.get('wide') === '1'
const narrowInlineSource = searchParams.get('inlineWrap') === '1'
const includeBlobImage = searchParams.get('blobImage') === '1'
const blobImageAsDataUrl = searchParams.get('blobMode') === 'data'
const { preferences: headerMetadata } = useSessionHeaderMetadata()
const getGeneratedMediaBlob = includeGeneratedFile
? async (imageId: string) => {
@@ -128,6 +138,31 @@ function App() {
worktree: { text: `${headerMetadata.showLabels ? 'Worktree: ' : ''}feat/share-turn-polish` },
})
useEffect(() => {
if (!includeBlobImage) {
setBlobImageSrc(null)
return undefined
}
if (blobImageAsDataUrl) {
setBlobImageSrc(blobExportFixture)
return undefined
}
let objectUrl: string | null = null
let disposed = false
void fetch(blobExportFixture)
.then((response) => response.blob())
.then((blob) => {
if (disposed) return
objectUrl = URL.createObjectURL(blob)
setBlobImageSrc(objectUrl)
})
return () => {
disposed = true
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
}, [blobImageAsDataUrl, includeBlobImage])
const openShare = () => {
const searchParams = new URLSearchParams(window.location.search)
const textOnlyUserFallback = searchParams.get('fallback') === 'user'
@@ -172,6 +207,32 @@ function App() {
<p data-testid="before-hidden-tool">Visible content before the hidden tool.</p>
<div data-hapi-share-exclude="true" className="mt-3 rounded-xl border p-3">Excluded tool output</div>
<p data-testid="after-hidden-tool">Visible content after the hidden tool.</p>
{includeBlobImage && blobImageSrc ? (
<div
className="max-w-[92%] rounded-2xl border border-[var(--app-border)] bg-[var(--app-tool-card-bg)] p-3"
data-hapi-generated-media-id="fixture-blob-image"
data-hapi-generated-media-file-name="blob-export-fixture.svg"
>
<div className="mb-2 min-w-0 truncate text-xs font-medium text-[var(--app-hint)]">
Displayed image: blob-export-fixture.svg
</div>
<div className="flex min-h-32 min-w-[12rem] items-center justify-center rounded-xl bg-[var(--app-subtle-bg)]">
<button
type="button"
title="Click to zoom"
data-image-preview-trigger=""
data-image-preview-label="Blob export fixture"
className="block max-h-[min(28rem,60vh)] max-w-full cursor-zoom-in rounded-xl text-left"
>
<img
src={blobImageSrc}
alt="Blob export fixture"
className="max-h-[min(28rem,60vh)] max-w-full rounded-xl object-contain"
/>
</button>
</div>
</div>
) : null}
{includeGeneratedFile ? (
<div
className="max-w-[92%] rounded-2xl border border-[var(--app-border)] bg-[var(--app-tool-card-bg)] p-3"
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { I18nProvider } from '@/lib/i18n-context'
import { ShareTurnDialog } from './ShareTurnDialog'
import { ShareTurnDialog, inlineBlobImageSources } from './ShareTurnDialog'
vi.mock('html2canvas-pro', () => ({
default: vi.fn(async () => {
@@ -42,6 +42,7 @@ function renderDialog(getGeneratedMediaBlob: (imageId: string) => Promise<Blob>,
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
describe('ShareTurnDialog generated-file lifecycle', () => {
@@ -80,3 +81,44 @@ describe('ShareTurnDialog generated-file lifecycle', () => {
expect(anchorClick).not.toHaveBeenCalled()
})
})
describe('inlineBlobImageSources', () => {
it('replaces blob sources with data URLs and reuses duplicate conversions', async () => {
const root = document.createElement('div')
root.innerHTML = `
<img src="blob:http://localhost/generated-image" srcset="blob:http://localhost/generated-image 1x" alt="First generated image">
<img src="blob:http://localhost/generated-image" alt="Second generated image">
<img src="data:image/png;base64,existing" alt="Existing data image">
`
const fetchMock = vi.fn(async () => new Response(new Blob(['image'], { type: 'image/png' })))
vi.stubGlobal('fetch', fetchMock)
vi.stubGlobal('FileReader', class {
result: string | ArrayBuffer | null = null
onload: ((this: FileReader, event: ProgressEvent<FileReader>) => void) | null = null
onerror: ((this: FileReader, event: ProgressEvent<FileReader>) => void) | null = null
readAsDataURL() {
this.result = 'data:image/png;base64,aW1hZ2U='
this.onload?.call(this as unknown as FileReader, new ProgressEvent('load'))
}
})
await inlineBlobImageSources(root)
const images = Array.from(root.querySelectorAll('img'))
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(images[0].src).toBe('data:image/png;base64,aW1hZ2U=')
expect(images[0].hasAttribute('srcset')).toBe(false)
expect(images[1].src).toBe('data:image/png;base64,aW1hZ2U=')
expect(images[2].src).toBe('data:image/png;base64,existing')
})
it('keeps the original blob source when inlining fails', async () => {
const root = document.createElement('div')
root.innerHTML = '<img src="blob:http://localhost/generated-image" alt="Generated image">'
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 })))
await inlineBlobImageSources(root)
expect(root.querySelector('img')?.src).toBe('blob:http://localhost/generated-image')
})
})
@@ -493,6 +493,54 @@ function copyLoadedStyleSheets(source: Document, target: Document): void {
}
}
function readBlobAsDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result)
return
}
reject(new Error('Failed to inline shared image'))
}
reader.onerror = () => reject(reader.error ?? new Error('Failed to inline shared image'))
reader.readAsDataURL(blob)
})
}
/**
* html2canvas-pro's foreign-object renderer omits blob-backed images even
* after they load. Keep that renderer for KaTeX and wrapped inline code, but
* inline the image bytes in the export clone first.
*/
export async function inlineBlobImageSources(root: HTMLElement): Promise<void> {
const dataUrls = new Map<string, Promise<string>>()
const images = Array.from(root.querySelectorAll<HTMLImageElement>('img'))
await Promise.all(images.map(async (image) => {
const source = image.currentSrc || image.src
if (!/^blob:/i.test(source)) return
let dataUrl = dataUrls.get(source)
if (!dataUrl) {
dataUrl = fetch(source)
.then((response) => {
if (!response.ok) throw new Error(`Failed to inline shared image: ${response.status}`)
return response.blob()
})
.then(readBlobAsDataUrl)
dataUrls.set(source, dataUrl)
}
try {
image.removeAttribute('srcset')
image.removeAttribute('sizes')
image.src = await dataUrl
} catch {
// Keep the original source so the normal image fallback still applies.
}
}))
}
async function waitForImages(root: HTMLElement): Promise<void> {
const images = Array.from(root.querySelectorAll('img'))
await Promise.all(images.map(async (image) => {
@@ -584,6 +632,7 @@ async function elementToPngBlob(
frameDocument.body.appendChild(captureElement)
let canvas: HTMLCanvasElement
try {
await inlineBlobImageSources(captureElement)
await waitForExportReady(captureElement)
const captureWidth = captureElement.scrollWidth
const captureHeight = captureElement.scrollHeight