diff --git a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss index 680a4137ad..621e8ffe5c 100644 --- a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss +++ b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss @@ -4,6 +4,9 @@ // Export wrapper .export-image-wrapper { overflow: visible; + // Also bound captures whose source row has been virtualized away. + width: 100vw; + max-width: var(--openbitfun-control-flow-chat-transcript-max-width); } .export-image-options { @@ -65,22 +68,23 @@ // Export content container .export-content { - @include transcriptLayout.content-column; + @include transcriptLayout.reading-column; - // Preserve the transcript inset while adding quiet framing above/below. + // Keep the live column and typography, with room for a standalone image frame. + padding-inline: clamp(var(--openbitfun-space-4), 4%, var(--openbitfun-space-8)); padding-block: var(--openbitfun-space-6); background: var(--openbitfun-color-surface-scene); box-sizing: border-box; - font-family: var(--openbitfun-type-body-sm-font-family); - // The capture wrapper sets the live pane width for container-aware text layout. + font-family: var(--openbitfun-type-flow-body-font-family); + font-size: var(--openbitfun-type-flow-body-font-size); + line-height: var(--openbitfun-type-flow-body-line-height); + // The capture wrapper sets the live reading-column width. container-type: inline-size; /* Prevent unwanted wrapping of short inline text */ .thinking-label, .thinking-collapsed-header, [data-openbitfun-component='flow-chat-tool-card'][data-openbitfun-part='action'], - [data-openbitfun-component='flow-chat-tool-card'][data-openbitfun-part='content'], - [data-openbitfun-component='flow-chat-tool-card'][data-openbitfun-part='extra'], .export-content__title, .export-content__timestamp, .export-content__footer span, @@ -89,28 +93,6 @@ flex-shrink: 0 !important; } - /* modern-screenshot does not have the last-character wrapping bug that - html-to-image had, so links can stay display:inline for natural line - breaking. We keep padding-right to give inline elements a tiny buffer. */ - a, code, strong, em, u, .file-mention { - padding-right: 2px; - } - - /* Keep font rendering as close to the live chat as possible so text - wrapping is identical. Do NOT override letter-spacing or ligatures - globally — those can change word widths and cause line-break deltas. */ - * { - -webkit-font-smoothing: antialiased; - text-rendering: geometricPrecision; - } - - /* Prevent links from being broken across lines inside the exported image. - FileLink is a '; + const column = pane.firstElementChild as HTMLElement; + column.dataset.turnId = turnId; + vi.spyOn(pane, 'getBoundingClientRect').mockReturnValue({ width: 1600 } as DOMRect); + vi.spyOn(column, 'getBoundingClientRect').mockReturnValue({ width } as DOMRect); + document.body.append(pane); + return { column, trigger: column.querySelector('button')! }; +} + +afterEach(() => { + document.body.replaceChildren(); + document.documentElement.removeAttribute('style'); + vi.restoreAllMocks(); +}); + +describe('conversation image layout', () => { + it.each([900, 420.5])('preserves the %s px reading column instead of the full pane', width => { + const { trigger } = makeColumn(width); + expect(readExportImageLayout('turn-1', trigger).width).toBe(width); + }); + + it('uses the initiating column and its local font settings with multiple transcripts', () => { + makeColumn(900); + const { column, trigger } = makeColumn(560); + column.style.setProperty('--openbitfun-type-flow-body-font-size', '18px'); + column.style.setProperty('--openbitfun-type-flow-body-line-height', '1.7'); + const layout = readExportImageLayout('turn-1', trigger); + expect(layout.width).toBe(560); + expect(layout.variables).toMatchObject({ + '--openbitfun-type-flow-body-font-size': '18px', + '--openbitfun-type-flow-body-line-height': '1.7', + }); + }); + + it('finds the visible target turn when its trigger is unavailable', () => { + makeColumn(900, 'another-turn'); + makeColumn(0); + makeColumn(620); + expect(readExportImageLayout('turn-1', null).width).toBe(620); + }); + + it('leaves missing-row sizing to the shared CSS limit and retains root appearance', () => { + makeColumn(900, 'another-turn'); + document.documentElement.style.setProperty('--openbitfun-type-flow-body-font-size', '16px'); + const layout = readExportImageLayout('missing-turn', null); + expect(layout.width).toBeUndefined(); + expect(layout.variables['--openbitfun-type-flow-body-font-size']).toBe('16px'); + }); +}); diff --git a/src/web-ui/src/flow_chat/components/modern/exportImageLayout.ts b/src/web-ui/src/flow_chat/components/modern/exportImageLayout.ts new file mode 100644 index 0000000000..c894ad4521 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/exportImageLayout.ts @@ -0,0 +1,19 @@ +/** Read the initiating transcript column, not the full chat pane (or a hidden + * sibling session). Its inherited variables include pane-local typography. */ +export function readExportImageLayout(turnId: string, trigger: HTMLElement | null) { + const triggerRow = trigger?.closest('.virtual-item-wrapper'); + const rows = Array.from(document.querySelectorAll('.virtual-item-wrapper')); + const column = [triggerRow, ...rows].find(row => ( + row?.dataset.turnId === turnId && row.getBoundingClientRect().width > 0 + )); + const source = column ?? document.documentElement; + const computedStyle = getComputedStyle(source); + const variables: Record = {}; + for (const name of Array.from(computedStyle)) { + if (name.startsWith('--')) { + const value = computedStyle.getPropertyValue(name).trim(); + if (value) variables[name] = value; + } + } + return { width: column?.getBoundingClientRect().width, variables }; +} diff --git a/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.test.tsx b/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.test.tsx new file mode 100644 index 0000000000..4d4600589b --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { captureElementToDownloadsPng } from './captureElementToDownloadsPng'; + +const mocks = vi.hoisted(() => ({ + capture: vi.fn(), + write: vi.fn(), + success: vi.fn(), + downloads: vi.fn(async () => '/downloads'), +})); +vi.mock('./exportImageCapture', () => ({ captureExportCanvas: mocks.capture })); +vi.mock('@tauri-apps/api/path', () => ({ + downloadDir: mocks.downloads, + join: async (directory: string, name: string) => `${directory}/${name}`, +})); +vi.mock('@tauri-apps/plugin-fs', () => ({ writeFile: mocks.write })); +vi.mock('@openbitfun/ui', () => ({ Button: () => null })); +vi.mock('@/shared/notification-system', () => ({ notificationService: { success: mocks.success } })); +vi.mock('@/infrastructure/i18n', () => ({ + i18nService: { t: (key: string) => key, formatDate: () => 'export-date' }, +})); +vi.mock('@/infrastructure/api', () => ({ workspaceAPI: {} })); +vi.mock('@/infrastructure/appearance/builtins/catalog', () => ({ getBuiltinAppearanceThemeToken: () => 'white' })); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.capture.mockReset(); + mocks.write.mockReset().mockResolvedValue(undefined); +}); + +afterEach(() => vi.restoreAllMocks()); + +function encodedCanvas(blob: Blob | null) { + const canvas = document.createElement('canvas'); + canvas.width = 200; + canvas.height = 100; + vi.spyOn(canvas, 'toBlob').mockImplementation(callback => callback(blob)); + mocks.capture.mockResolvedValue(canvas); + return canvas; +} + +describe('widget image download', () => { + it('writes the verified raster and reports success after saving', async () => { + const bytes = new Uint8Array([1, 2, 3]); + const canvas = encodedCanvas({ arrayBuffer: async () => bytes.buffer } as Blob); + const element = document.createElement('div'); + await captureElementToDownloadsPng(element, 'Widget'); + expect(mocks.capture).toHaveBeenCalledExactlyOnceWith(element, 'white'); + expect(canvas.toBlob).toHaveBeenCalledWith(expect.any(Function), 'image/png'); + expect([canvas.width, canvas.height]).toEqual([0, 0]); + expect(mocks.write).toHaveBeenCalledExactlyOnceWith('/downloads/Widget_export-date.png', bytes); + expect(mocks.success).toHaveBeenCalledTimes(1); + }); + + it('propagates blank capture failure without creating a download or success notification', async () => { + mocks.capture.mockRejectedValue(new Error('Capture returned a blank image')); + await expect(captureElementToDownloadsPng(document.createElement('div'), 'Widget')) + .rejects.toThrow('blank image'); + expect(mocks.downloads).not.toHaveBeenCalled(); + expect(mocks.write).not.toHaveBeenCalled(); + expect(mocks.success).not.toHaveBeenCalled(); + }); + + it.each(['null', 'throw'])('releases the raster and does not save after %s encoding failure', async failure => { + const canvas = encodedCanvas(null); + if (failure === 'throw') vi.mocked(canvas.toBlob).mockImplementation(() => { throw new Error('Encoding failed'); }); + await expect(captureElementToDownloadsPng(document.createElement('div'), 'Widget')).rejects.toThrow(); + expect([canvas.width, canvas.height]).toEqual([0, 0]); + expect(mocks.downloads).not.toHaveBeenCalled(); + expect(mocks.write).not.toHaveBeenCalled(); + expect(mocks.success).not.toHaveBeenCalled(); + }); + + it('does not report success when saving fails', async () => { + encodedCanvas({ arrayBuffer: async () => new ArrayBuffer(1) } as Blob); + mocks.write.mockRejectedValue(new Error('Disk full')); + await expect(captureElementToDownloadsPng(document.createElement('div'), 'Widget')) + .rejects.toThrow('Disk full'); + expect(mocks.success).not.toHaveBeenCalled(); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.tsx b/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.tsx index 94612285f4..fe3bc18c01 100644 --- a/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.tsx +++ b/src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.tsx @@ -6,15 +6,10 @@ import { i18nService } from '@/infrastructure/i18n'; import { workspaceAPI } from '@/infrastructure/api'; import { createLogger } from '@/shared/utils/logger'; import { getBuiltinAppearanceThemeToken } from '@/infrastructure/appearance/builtins/catalog'; -import { withTimeout } from '@/shared/utils/timing'; +import { captureExportCanvas } from './exportImageCapture'; const log = createLogger('captureElementToDownloadsPng'); -const loadModernScreenshot = () => import('modern-screenshot'); - -/** Maximum time to wait for capture before aborting (ms). */ -const CAPTURE_TIMEOUT_MS = 15_000; - export async function captureElementToDownloadsPng( element: HTMLElement, fileNamePrefix: string, @@ -25,55 +20,13 @@ export async function captureElementToDownloadsPng( await new Promise((resolve) => setTimeout(resolve, 0)); - const modernScreenshot = await loadModernScreenshot(); - let blob: Blob | null = null; - - const captureOptions = { - quality: 1, - scale: 2, - backgroundColor: bgColor, - fetch: { - bypassingCache: true, - } as const, - font: false as const, - features: { - removeControlCharacter: true, - fixSvgXmlDecode: true, - } as const, - }; - - // Strategy 1: domToBlob (primary — avoids data-URL overhead) + const canvas = await captureExportCanvas(element, bgColor); + let blob: Blob | null; try { - blob = await withTimeout( - modernScreenshot.domToBlob(element, { ...captureOptions, type: 'image/png' }), - CAPTURE_TIMEOUT_MS, - 'domToBlob capture', - ); - } catch (e) { - log.warn('domToBlob failed, trying domToPng', e); - - // Strategy 2: domToPng (fallback) - try { - const dataUrl = await withTimeout( - modernScreenshot.domToPng(element, captureOptions), - CAPTURE_TIMEOUT_MS, - 'domToPng capture', - ); - if (!dataUrl || dataUrl === 'data:,' || dataUrl.length < 100) { - throw new Error('domToPng returned empty or corrupt image data'); - } - const response = await fetch(dataUrl); - blob = await response.blob(); - } catch (e2) { - log.warn('domToPng also failed, trying reduced scale', e2); - - // Strategy 3: domToBlob with scale=1 (reduced memory) - blob = await withTimeout( - modernScreenshot.domToBlob(element, { ...captureOptions, scale: 1, type: 'image/png' }), - CAPTURE_TIMEOUT_MS, - 'domToBlob reduced-scale capture', - ); - } + blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png')); + } finally { + canvas.width = 0; + canvas.height = 0; } if (!blob) { diff --git a/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts new file mode 100644 index 0000000000..bd85c7b465 --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts @@ -0,0 +1,153 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + assertExportCanvasHasContent, + captureExportCanvas, + getExportCaptureStyleProperties, +} from './exportImageCapture'; + +const { domToCanvas } = vi.hoisted(() => ({ domToCanvas: vi.fn() })); +const originalFonts = Object.getOwnPropertyDescriptor(document, 'fonts'); +vi.mock('modern-screenshot', () => ({ domToCanvas })); +vi.mock('@/shared/utils/logger', () => ({ createLogger: () => ({ warn: vi.fn() }) })); + +function raster(background: number, content = false, height = 65, transparent = false) { + const canvas = document.createElement('canvas'); + canvas.width = 8; + canvas.height = height; + const getImageData = vi.fn((_x: number, y: number, width: number, rows: number) => { + const data = new Uint8ClampedArray(width * rows * 4); + for (let i = 0; i < data.length; i += 4) { + data.set([background, background, background, transparent ? 0 : 255], i); + } + // Put content in the final strip to catch sparse sampling regressions. + if (content && y + rows === height) data[data.length - 4] = background === 255 ? 0 : 255; + return { data }; + }); + vi.spyOn(canvas, 'getContext').mockReturnValue({ getImageData } as unknown as CanvasRenderingContext2D); + return { canvas, getImageData }; +} + +afterEach(() => { + if (originalFonts) Object.defineProperty(document, 'fonts', originalFonts); + else Reflect.deleteProperty(document, 'fonts'); + vi.restoreAllMocks(); + domToCanvas.mockReset(); + vi.useRealTimers(); +}); + +describe('conversation image raster validation', () => { + it.each([0, 28, 255])('rejects an opaque background-only capture (%s)', background => { + expect(() => assertExportCanvasHasContent(raster(background).canvas)).toThrow('blank image'); + }); + + it('rejects a transparent capture even when hidden RGB channels differ', () => { + expect(() => assertExportCanvasHasContent(raster(0, true, 65, true).canvas)).toThrow('blank image'); + }); + + it('accepts monochrome artwork with a transparent background', () => { + const { canvas } = raster(255); + const context = canvas.getContext('2d')!; + vi.mocked(context.getImageData).mockReturnValue({ + data: new Uint8ClampedArray([255, 255, 255, 0, 255, 255, 255, 255]), + } as ImageData); + expect(() => assertExportCanvasHasContent(canvas)).not.toThrow(); + }); + + it.each([0, 28, 255])('finds text contrast without reading a full long-image buffer (%s)', background => { + const { canvas, getImageData } = raster(background, true); + expect(() => assertExportCanvasHasContent(canvas)).not.toThrow(); + expect(getImageData.mock.calls.map(call => call[3])).toEqual([32, 32, 1]); + }); + + it('rejects zero-sized canvases', () => { + const { canvas } = raster(0); + canvas.width = 0; + expect(() => assertExportCanvasHasContent(canvas)).toThrow('empty canvas'); + }); +}); + +describe('conversation image capture', () => { + it('keeps resolved paint/layout properties without serializing inherited theme variables', () => { + const container = document.createElement('div'); + vi.spyOn(globalThis, 'getComputedStyle').mockReturnValue([ + 'color', 'font-family', 'width', 'fill', '-webkit-text-fill-color', '--theme-color', '--theme-font', + ] as unknown as CSSStyleDeclaration); + expect(getExportCaptureStyleProperties(container)).toEqual([ + 'color', 'font-family', 'width', 'fill', '-webkit-text-fill-color', + ]); + }); + + it('validates before returning the canvas and passes the export filter to the rasterizer', async () => { + const { canvas } = raster(255, true); + domToCanvas.mockResolvedValue(canvas); + const container = document.createElement('div'); + const filter = vi.fn(() => true); + expect(await captureExportCanvas(container, 'white', filter)).toBe(canvas); + expect(domToCanvas).toHaveBeenCalledExactlyOnceWith(container, expect.objectContaining({ + scale: 2, backgroundColor: 'white', filter, font: {}, includeStyleProperties: expect.any(Array), + })); + }); + + it('waits for bundled fonts before the rasterizer measures and clones text', async () => { + let finishFonts!: () => void; + Object.defineProperty(document, 'fonts', { + configurable: true, + value: { ready: new Promise(resolve => { finishFonts = resolve; }) }, + }); + const { canvas } = raster(255, true); + domToCanvas.mockResolvedValue(canvas); + const capture = captureExportCanvas(document.createElement('div'), 'white'); + await Promise.resolve(); + expect(domToCanvas).not.toHaveBeenCalled(); + finishFonts(); + expect(await capture).toBe(canvas); + }); + + it('reports stalled font loading without capturing fallback text', async () => { + vi.useFakeTimers(); + Object.defineProperty(document, 'fonts', { + configurable: true, + value: { ready: new Promise(() => {}) }, + }); + const capture = captureExportCanvas(document.createElement('div'), 'white'); + const rejection = expect(capture).rejects.toThrow('Image export fonts timed out'); + await vi.advanceTimersByTimeAsync(15_000); + await rejection; + expect(domToCanvas).not.toHaveBeenCalled(); + }); + + it.each(['blank', 'error'])('retries a %s capture at lower resolution', async failure => { + const failed = raster(0).canvas; + if (failure === 'blank') domToCanvas.mockResolvedValueOnce(failed); + else domToCanvas.mockRejectedValueOnce(new Error('Raster allocation failed')); + const recovered = raster(0, true).canvas; + domToCanvas.mockResolvedValueOnce(recovered); + expect(await captureExportCanvas(document.createElement('div'), 'black', () => true)).toBe(recovered); + expect(domToCanvas.mock.calls.map(call => call[1].scale)).toEqual([2, 1]); + if (failure === 'blank') expect([failed.width, failed.height]).toEqual([0, 0]); + }); + + it('rejects repeated blank output instead of returning a savable image', async () => { + domToCanvas.mockImplementation(async () => raster(255).canvas); + await expect(captureExportCanvas(document.createElement('div'), 'white', () => true)) + .rejects.toThrow('blank image'); + expect(domToCanvas).toHaveBeenCalledTimes(2); + }); + + it('does not start a concurrent retry after the capture times out', async () => { + vi.useFakeTimers(); + let finishCapture!: (canvas: HTMLCanvasElement) => void; + domToCanvas.mockReturnValue(new Promise(resolve => { finishCapture = resolve; })); + const capture = captureExportCanvas(document.createElement('div'), 'white', () => true); + const rejection = expect(capture).rejects.toThrow('timed out'); + await vi.advanceTimersByTimeAsync(15_000); + await rejection; + expect(domToCanvas).toHaveBeenCalledTimes(1); + const lateCanvas = raster(255, true).canvas; + finishCapture(lateCanvas); + await vi.advanceTimersByTimeAsync(0); + expect([lateCanvas.width, lateCanvas.height]).toEqual([0, 0]); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/exportImageCapture.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts new file mode 100644 index 0000000000..660df7c70c --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts @@ -0,0 +1,102 @@ +import type { Options } from 'modern-screenshot'; +import { withTimeout } from '@/shared/utils/timing'; +import { createLogger } from '@/shared/utils/logger'; + +const log = createLogger('ExportImageCapture'); +const CAPTURE_TIMEOUT_MS = 15_000; + +/** Computed CSS already resolves var(). Copying inherited custom properties onto + * every cloned element bloats a transcript SVG by tens of MB and can prevent + * WebKit from decoding it. Keep every browser-supported paint/layout property, + * including vendor-prefixed ones, without serializing the theme catalog. */ +export function getExportCaptureStyleProperties(container: HTMLElement): string[] { + return Array.from(getComputedStyle(container)).filter(name => !name.startsWith('--')); +} + +/** Check the raster before adding the logo: an SVG decode/draw failure can + * produce a valid, nonempty PNG containing only the requested background. */ +export function assertExportCanvasHasContent(canvas: HTMLCanvasElement): void { + const context = canvas.getContext('2d'); + if (!context || !canvas.width || !canvas.height) { + throw new Error('Capture returned an empty canvas'); + } + + let reference: number[] | undefined; + // Read bounded strips instead of allocating another full long-image buffer. + for (let y = 0; y < canvas.height; y += 32) { + const { data } = context.getImageData(0, y, canvas.width, Math.min(32, canvas.height - y)); + for (let i = 0; i < data.length; i += 4) { + if (!reference) { + reference = [data[i], data[i + 1], data[i + 2], data[i + 3]]; + } else if ( + Math.abs(reference[3] - data[i + 3]) > 2 + || (reference[3] > 0 && data[i + 3] > 0 && ( + Math.abs(reference[0] - data[i]) > 2 + || Math.abs(reference[1] - data[i + 1]) > 2 + || Math.abs(reference[2] - data[i + 2]) > 2 + )) + ) { + return; + } + } + } + throw new Error('Capture returned a blank image'); +} + +export async function captureExportCanvas( + container: HTMLElement, + backgroundColor: string, + filter?: NonNullable, +): Promise { + // Measure after web fonts settle; otherwise the SVG can embed the right face + // into boxes that were sized with fallback glyphs. + await withTimeout( + container.ownerDocument.fonts?.ready ?? Promise.resolve(), + CAPTURE_TIMEOUT_MS, + 'Image export fonts', + ); + const { domToCanvas } = await import('modern-screenshot'); + const options: Options = { + backgroundColor, + filter, + includeStyleProperties: getExportCaptureStyleProperties(container), + fetch: { bypassingCache: true }, + // Windows/Linux ship web fonts. Embed the used faces so the standalone SVG + // keeps the same glyph metrics instead of silently switching to a fallback. + font: {}, + features: { removeControlCharacter: true, fixSvgXmlDecode: true }, + }; + + // PNG and Blob use the same SVG rasterizer; changing the encoding is not a + // recovery strategy. Retry at a lower resolution to reduce raster memory. + for (const scale of [2, 1]) { + let timedOut = false; + let canvas: HTMLCanvasElement | undefined; + try { + canvas = await withTimeout( + domToCanvas(container, { ...options, scale }).then(result => { + if (timedOut) { + result.width = 0; + result.height = 0; + } + return result; + }), + CAPTURE_TIMEOUT_MS, + 'Conversation image capture', + () => { timedOut = true; }, + ); + assertExportCanvasHasContent(canvas); + return canvas; + } catch (error) { + if (canvas) { + canvas.width = 0; + canvas.height = 0; + } + // A timeout does not cancel the library's work. Do not start a concurrent + // capture against the same DOM; let the caller clean up and report it. + if (timedOut || scale === 1) throw error; + log.warn('Capture failed; retrying at reduced scale', { error }); + } + } + throw new Error('Conversation image capture failed'); +}