From f80c23f5575e47c610ae7c062df064829c9c61da Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 16:23:12 +0800 Subject: [PATCH 1/4] fix(flowchat): prevent blank conversation image exports --- .../components/modern/ExportImageButton.tsx | 189 ++++-------------- .../modern/FLOWCHAT_VERIFICATION.md | 1 + .../modern/FLOWCHAT_VIRTUALIZATION.md | 9 + .../modern/exportImageCapture.test.ts | 108 ++++++++++ .../components/modern/exportImageCapture.ts | 81 ++++++++ 5 files changed, 239 insertions(+), 149 deletions(-) create mode 100644 src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts create mode 100644 src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts diff --git a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx index b0cbb8c8ea..12bb96bd3f 100644 --- a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx @@ -23,16 +23,11 @@ import { writeFile } from '@tauri-apps/plugin-fs'; import { ModelThinkingDisplay } from '../../tool-cards/ModelThinkingDisplay'; import { hasComposerPresentationReferences, parseComposerPresentation } from '../../utils/composerPresentation'; import { UserMessagePresentationContent, UserMessageTextContent } from './UserMessagePresentationContent'; +import { captureExportCanvas } from './exportImageCapture'; import './ExportImageButton.scss'; const log = createLogger('ExportImageButton'); -// Lazy-load modern-screenshot. -const loadModernScreenshot = () => import('modern-screenshot'); - -/** Maximum time to wait for capture before aborting (ms). */ -const CAPTURE_TIMEOUT_MS = 15_000; - /** Minimum time to wait for React render before capture (ms). */ const MIN_RENDER_WAIT_MS = 300; @@ -62,13 +57,6 @@ function collectAllCssVariables(): Record { return vars; } -/** Validate that a data-URL is not blank/corrupt. */ -function validateDataUrl(dataUrl: string): void { - if (!dataUrl || dataUrl === 'data:,' || dataUrl.length < 100) { - throw new Error('Capture returned empty or corrupt image data'); - } -} - interface ExportImageButtonProps { turnId: string; className?: string; @@ -330,7 +318,7 @@ export const ExportImageButton: React.FC = ({ } // Create hidden wrapper for rendering. - // Use left: -9999px (not z-index: -9999) so elements remain visible to capture. + // Keep the staging tree laid out without covering the conversation. wrapper = document.createElement('div'); wrapper.id = 'export-image-wrapper'; wrapper.className = 'export-image-wrapper'; @@ -344,7 +332,6 @@ export const ExportImageButton: React.FC = ({ position: absolute; left: -9999px; top: 0; - z-index: -9999; pointer-events: none; background: ${bgColor}; visibility: visible; @@ -374,17 +361,17 @@ export const ExportImageButton: React.FC = ({ await new Promise(resolve => setTimeout(resolve, renderWait)); // Find rendered container. - const container = wrapper.querySelector('.export-content') as HTMLElement; + const container = wrapper.querySelector('.export-content'); + + if (!container) { + throw new Error(i18nService.t('flow-chat:exportImage.containerNotFound')); + } // Match the export width exactly to the live chat pane so text wrapping // is identical. SCSS sets a fixed width; override it here dynamically. container.style.width = `${chatWidth}px`; container.style.maxWidth = 'none'; - if (!container) { - throw new Error(i18nService.t('flow-chat:exportImage.containerNotFound')); - } - // Yield to the main thread so the browser can finish layout/paint. await new Promise(resolve => setTimeout(resolve, 0)); @@ -407,13 +394,6 @@ export const ExportImageButton: React.FC = ({ }; } - // Generate image via modern-screenshot with timeout guard. - const modernScreenshot = await loadModernScreenshot(); - - // Yield again before capture. - await new Promise(resolve => setTimeout(resolve, 0)); - - const pixelRatio = 2; const captureFilter = (node: Node) => { // Filter out action buttons and other non-export elements. if (node instanceof HTMLElement) { @@ -430,131 +410,42 @@ export const ExportImageButton: React.FC = ({ return true; }; - const captureOptions = { - quality: 1, - scale: pixelRatio, - backgroundColor: bgColor, - fetch: { - bypassingCache: true, - } as const, - filter: captureFilter, - // Disable font embedding to avoid cross-origin stylesheet issues; - // the offscreen DOM already has system fonts available. - font: false as const, - features: { - removeControlCharacter: true, - fixSvgXmlDecode: true, - } as const, - }; - - let baseDataUrl: string; - - // Strategy 1: domToPng (primary) - try { - baseDataUrl = await withTimeout( - modernScreenshot.domToPng(container, captureOptions), - CAPTURE_TIMEOUT_MS, - 'domToPng capture', - cleanupDom, - ); - validateDataUrl(baseDataUrl); - } catch (e1) { - log.warn('domToPng failed, trying domToBlob fallback', e1); - // Ensure DOM is still alive for fallback. - if (!wrapper || !wrapper.parentNode) { - throw new Error('DOM was cleaned up before fallback could run'); - } + const canvas = await captureExportCanvas(container, bgColor, captureFilter); + cleanupDom(); - // Strategy 2: domToBlob (fallback) - try { - const fallbackBlob = await withTimeout( - modernScreenshot.domToBlob(container, { ...captureOptions, type: 'image/png' }), - CAPTURE_TIMEOUT_MS, - 'domToBlob capture', - cleanupDom, - ); - if (!fallbackBlob) throw new Error(i18nService.t('flow-chat:exportImage.generateFailed')); - baseDataUrl = await new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result as string); - reader.onerror = reject; - reader.readAsDataURL(fallbackBlob); - }); - validateDataUrl(baseDataUrl); - } catch (e2) { - log.warn('domToBlob fallback also failed, trying reduced scale', e2); - // Ensure DOM is still alive for second fallback. - if (!wrapper || !wrapper.parentNode) { - throw new Error('DOM was cleaned up before reduced-scale fallback could run'); - } - - // Strategy 3: domToPng with scale=1 (reduced memory for large DOMs) - const reducedOptions = { ...captureOptions, scale: 1 }; - baseDataUrl = await withTimeout( - modernScreenshot.domToPng(container, reducedOptions), - CAPTURE_TIMEOUT_MS, - 'domToPng reduced-scale capture', - cleanupDom, - ); - validateDataUrl(baseDataUrl); + // Reuse the verified raster instead of PNG -> Image -> second canvas. + // The actual dimensions also keep the logo aligned after a scale fallback. + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('No canvas context for compositing'); + if (logoImage && logoBox) { + const scaleX = canvas.width / containerRect.width; + const scaleY = canvas.height / containerRect.height; + ctx.save(); + ctx.scale(scaleX, scaleY); + const { x, y, w, h, radius } = logoBox; + if (radius > 0) { + const path = new Path2D(); + const r = Math.min(radius, w / 2, h / 2); + path.moveTo(x + r, y); + path.lineTo(x + w - r, y); + path.quadraticCurveTo(x + w, y, x + w, y + r); + path.lineTo(x + w, y + h - r); + path.quadraticCurveTo(x + w, y + h, x + w - r, y + h); + path.lineTo(x + r, y + h); + path.quadraticCurveTo(x, y + h, x, y + h - r); + path.lineTo(x, y + r); + path.quadraticCurveTo(x, y, x + r, y); + path.closePath(); + ctx.clip(path); } + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = 'high'; + ctx.drawImage(logoImage, x, y, w, h); + ctx.restore(); + } else { + log.warn('Logo overlay skipped', { hasLogo: !!logoImage, hasBox: !!logoBox }); } - - // Cleanup the offscreen DOM as soon as we have the base capture. - cleanupDom(); - - // Composite the logo onto the captured image so it always appears, - // regardless of capture library behavior with elements. - const blob: Blob | null = await new Promise((resolve, reject) => { - const baseImg = new window.Image(); - baseImg.onload = () => { - try { - const canvas = document.createElement('canvas'); - canvas.width = baseImg.naturalWidth; - canvas.height = baseImg.naturalHeight; - const ctx = canvas.getContext('2d'); - if (!ctx) { reject(new Error('no canvas ctx for compositing')); return; } - ctx.drawImage(baseImg, 0, 0); - - if (logoImage && logoBox) { - const dx = logoBox.x * pixelRatio; - const dy = logoBox.y * pixelRatio; - const dw = logoBox.w * pixelRatio; - const dh = logoBox.h * pixelRatio; - const dr = logoBox.radius * pixelRatio; - - ctx.save(); - if (dr > 0) { - const path = new Path2D(); - const r = Math.min(dr, dw / 2, dh / 2); - path.moveTo(dx + r, dy); - path.lineTo(dx + dw - r, dy); - path.quadraticCurveTo(dx + dw, dy, dx + dw, dy + r); - path.lineTo(dx + dw, dy + dh - r); - path.quadraticCurveTo(dx + dw, dy + dh, dx + dw - r, dy + dh); - path.lineTo(dx + r, dy + dh); - path.quadraticCurveTo(dx, dy + dh, dx, dy + dh - r); - path.lineTo(dx, dy + r); - path.quadraticCurveTo(dx, dy, dx + r, dy); - path.closePath(); - ctx.clip(path); - } - ctx.imageSmoothingEnabled = true; - ctx.imageSmoothingQuality = 'high'; - ctx.drawImage(logoImage, dx, dy, dw, dh); - ctx.restore(); - } else { - log.warn('Logo overlay skipped', { hasLogo: !!logoImage, hasBox: !!logoBox }); - } - - canvas.toBlob((b) => resolve(b), 'image/png'); - } catch (err) { - reject(err); - } - }; - baseImg.onerror = reject; - baseImg.src = baseDataUrl; - }); + const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png')); if (!blob) { throw new Error(i18nService.t('flow-chat:exportImage.generateFailed')); diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index 160b779e9a..ccedf46e6f 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -19,6 +19,7 @@ each missing what the other had. | `../../timeline/hostQueueProjection.test.ts`, `../../timeline/useHostQueueTimeline.test.tsx`, `../HostPendingQueuePanel.test.tsx` | host-accepted preview, canonical handoff/event ordering, stable keys, blocked recovery, old-host fallback, history-window visibility and device lease cleanup; fixtures only, no live remote transport evidence | | `TurnFooter.test.tsx`, `modelRoundItemMemo.test.ts` | latest-turn identity, hover/focus across virtual rows, lease cleanup, no projection churn and the existing completion reveal gate; behavior only, not visual proof | | `MessageExportControls.test.tsx` | flat copy/export menu, illustrated checkbox-card selection by pointer and keyboard, complete user text/reference rendering, omission or expansion of thinking, minimal branding, confirmation, pending/error feedback, cancel/Escape/outside dismissal and resident-trigger focus restoration; local DOM behavior, not image fidelity or remote-host validation | +| `exportImageCapture.test.ts` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery and timeout handling; rasterizer fixtures, not native WebView or remote-host validation | | `../../../shared/ui/Tooltip.test.tsx` | shared metric click opening, immediate scroll dismissal, delayed-open cancellation, viewport-exit observer cleanup and no automatic reopening; DOM/observer behavior only, not native scrolling or visual proof | | `../../utils/turnUsageMetrics.test.ts`, `TurnUsageMetrics.test.tsx`, `../../store/modernFlowChatStore.test.ts`, `../../../features/dispatch/DispatchJobObserver.test.ts` | separate request TTFT, effective-output rate excluding waiting and tools, complete multi-round timing, controller setup-row exclusion, legacy/missing/zero telemetry, speed boundaries and projection | | `../../services/flow-chat-manager/EventHandlerModule.test.ts`, `../../services/flow-chat-manager/PersistenceModule.test.ts`, `../../store/FlowChatStore.test.ts` | live cache aggregation, optional-field persistence and legacy/current hydration; no remote-host claim | diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index e510542595..eb350bbbe9 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -75,6 +75,15 @@ live message's content renderer. Compact output omits thinking items entirely, including their icons; the other output renders expanded thinking in item order. The small brand/date header and muted attribution footer use semantic typography, spacing and divider tokens, without an assistant slogan or subtitle. +The image capture copies resolved CSS properties, including browser-prefixed +paint properties, but excludes inherited custom properties from the cloned SVG. +The staging DOM still receives the active theme variables for layout. Repeating +the full theme catalog on every cloned node makes long transcripts expensive to +serialize and rasterize. Capture validates the canvas before adding the logo: +uniform or transparent output is a failure even when PNG encoding would succeed. +A failed raster retries at reduced scale; a timeout stops the export. Logo +compositing reuses the validated canvas and its actual scale, avoiding a second +full-size bitmap and keeping reduced-resolution exports aligned. Each number has its own hover/focus/click capsule and details card. Clicking opens immediately and keeps the card open until another trigger click, an outside press, Escape, or scrolling; native button triggers also support keyboard activation. `FlowChatMetric` diff --git a/src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts b/src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts new file mode 100644 index 0000000000..714fe73907 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts @@ -0,0 +1,108 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + assertExportCanvasHasContent, + captureExportCanvas, + getExportCaptureStyleProperties, +} from './exportImageCapture'; + +const { domToCanvas } = vi.hoisted(() => ({ domToCanvas: vi.fn() })); +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(() => { + 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.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, includeStyleProperties: expect.any(Array), + })); + }); + + 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(); + domToCanvas.mockReturnValue(new Promise(() => {})); + 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); + }); +}); diff --git a/src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts b/src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts new file mode 100644 index 0000000000..fbc9c3582e --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts @@ -0,0 +1,81 @@ +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 (data[i + 3] === 0) continue; + if (!reference) { + reference = [data[i], data[i + 1], data[i + 2]]; + } else if (reference.some((channel, index) => Math.abs(channel - data[i + index]) > 2)) { + return; + } + } + } + throw new Error('Capture returned a blank image'); +} + +export async function captureExportCanvas( + container: HTMLElement, + backgroundColor: string, + filter: NonNullable, +): Promise { + const { domToCanvas } = await import('modern-screenshot'); + const options: Options = { + backgroundColor, + filter, + includeStyleProperties: getExportCaptureStyleProperties(container), + fetch: { bypassingCache: true }, + font: false, + 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 }), + 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'); +} From e01462400b7eec2e0a699446799d58f441ce98d4 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 16:30:13 +0800 Subject: [PATCH 2/4] fix(flowchat): guard widget image exports with shared capture --- .../components/modern/ExportImageButton.tsx | 2 +- .../modern/FLOWCHAT_VERIFICATION.md | 2 +- .../modern/FLOWCHAT_VIRTUALIZATION.md | 3 + .../captureElementToDownloadsPng.test.tsx | 82 +++++++++++++++++++ .../utils/captureElementToDownloadsPng.tsx | 61 ++------------ .../exportImageCapture.test.ts | 16 +++- .../modern => utils}/exportImageCapture.ts | 24 ++++-- 7 files changed, 127 insertions(+), 63 deletions(-) create mode 100644 src/web-ui/src/flow_chat/utils/captureElementToDownloadsPng.test.tsx rename src/web-ui/src/flow_chat/{components/modern => utils}/exportImageCapture.test.ts (86%) rename src/web-ui/src/flow_chat/{components/modern => utils}/exportImageCapture.ts (81%) diff --git a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx index 12bb96bd3f..5daf40c573 100644 --- a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx @@ -23,7 +23,7 @@ import { writeFile } from '@tauri-apps/plugin-fs'; import { ModelThinkingDisplay } from '../../tool-cards/ModelThinkingDisplay'; import { hasComposerPresentationReferences, parseComposerPresentation } from '../../utils/composerPresentation'; import { UserMessagePresentationContent, UserMessageTextContent } from './UserMessagePresentationContent'; -import { captureExportCanvas } from './exportImageCapture'; +import { captureExportCanvas } from '../../utils/exportImageCapture'; import './ExportImageButton.scss'; const log = createLogger('ExportImageButton'); diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index ccedf46e6f..86c988d25a 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -19,7 +19,7 @@ each missing what the other had. | `../../timeline/hostQueueProjection.test.ts`, `../../timeline/useHostQueueTimeline.test.tsx`, `../HostPendingQueuePanel.test.tsx` | host-accepted preview, canonical handoff/event ordering, stable keys, blocked recovery, old-host fallback, history-window visibility and device lease cleanup; fixtures only, no live remote transport evidence | | `TurnFooter.test.tsx`, `modelRoundItemMemo.test.ts` | latest-turn identity, hover/focus across virtual rows, lease cleanup, no projection churn and the existing completion reveal gate; behavior only, not visual proof | | `MessageExportControls.test.tsx` | flat copy/export menu, illustrated checkbox-card selection by pointer and keyboard, complete user text/reference rendering, omission or expansion of thinking, minimal branding, confirmation, pending/error feedback, cancel/Escape/outside dismissal and resident-trigger focus restoration; local DOM behavior, not image fidelity or remote-host validation | -| `exportImageCapture.test.ts` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery and timeout handling; rasterizer fixtures, not native WebView or remote-host validation | +| `../../utils/exportImageCapture.test.ts`, `../../utils/captureElementToDownloadsPng.test.tsx` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery, timeout cleanup, and widget export save/error handling; rasterizer fixtures, not native WebView or remote-host validation | | `../../../shared/ui/Tooltip.test.tsx` | shared metric click opening, immediate scroll dismissal, delayed-open cancellation, viewport-exit observer cleanup and no automatic reopening; DOM/observer behavior only, not native scrolling or visual proof | | `../../utils/turnUsageMetrics.test.ts`, `TurnUsageMetrics.test.tsx`, `../../store/modernFlowChatStore.test.ts`, `../../../features/dispatch/DispatchJobObserver.test.ts` | separate request TTFT, effective-output rate excluding waiting and tools, complete multi-round timing, controller setup-row exclusion, legacy/missing/zero telemetry, speed boundaries and projection | | `../../services/flow-chat-manager/EventHandlerModule.test.ts`, `../../services/flow-chat-manager/PersistenceModule.test.ts`, `../../store/FlowChatStore.test.ts` | live cache aggregation, optional-field persistence and legacy/current hydration; no remote-host claim | diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index eb350bbbe9..995f6307fb 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -84,6 +84,9 @@ uniform or transparent output is a failure even when PNG encoding would succeed. A failed raster retries at reduced scale; a timeout stops the export. Logo compositing reuses the validated canvas and its actual scale, avoiding a second full-size bitmap and keeping reduced-resolution exports aligned. +Generative UI card PNG exports use the same capture helper, including blank-image +rejection and reduced-scale recovery. Encoding failures must not write files or +show success. Timed-out captures release any raster that completes late. Each number has its own hover/focus/click capsule and details card. Clicking opens immediately and keeps the card open until another trigger click, an outside press, Escape, or scrolling; native button triggers also support keyboard activation. `FlowChatMetric` 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/components/modern/exportImageCapture.test.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts similarity index 86% rename from src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts rename to src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts index 714fe73907..f53fd1ae05 100644 --- a/src/web-ui/src/flow_chat/components/modern/exportImageCapture.test.ts +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts @@ -43,6 +43,15 @@ describe('conversation image raster validation', () => { 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(); @@ -98,11 +107,16 @@ describe('conversation image capture', () => { it('does not start a concurrent retry after the capture times out', async () => { vi.useFakeTimers(); - domToCanvas.mockReturnValue(new Promise(() => {})); + 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/components/modern/exportImageCapture.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts similarity index 81% rename from src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts rename to src/web-ui/src/flow_chat/utils/exportImageCapture.ts index fbc9c3582e..cc4bc7f5ac 100644 --- a/src/web-ui/src/flow_chat/components/modern/exportImageCapture.ts +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts @@ -26,10 +26,16 @@ export function assertExportCanvasHasContent(canvas: HTMLCanvasElement): void { 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 (data[i + 3] === 0) continue; if (!reference) { - reference = [data[i], data[i + 1], data[i + 2]]; - } else if (reference.some((channel, index) => Math.abs(channel - data[i + index]) > 2)) { + 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; } } @@ -40,7 +46,7 @@ export function assertExportCanvasHasContent(canvas: HTMLCanvasElement): void { export async function captureExportCanvas( container: HTMLElement, backgroundColor: string, - filter: NonNullable, + filter?: NonNullable, ): Promise { const { domToCanvas } = await import('modern-screenshot'); const options: Options = { @@ -58,8 +64,14 @@ export async function captureExportCanvas( let timedOut = false; let canvas: HTMLCanvasElement | undefined; try { - canvas = await withTimeout( - domToCanvas(container, { ...options, scale }), + 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; }, From 7ac125616e5d17050f3655b32bb1fc27beff426c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 16:49:39 +0800 Subject: [PATCH 3/4] fix(flowchat): match exported image width to the transcript column --- .../components/modern/ExportImageButton.scss | 32 +++-------- .../components/modern/ExportImageButton.tsx | 42 +++----------- .../modern/FLOWCHAT_VERIFICATION.md | 1 + .../modern/FLOWCHAT_VIRTUALIZATION.md | 6 +- .../modern/exportImageLayout.test.ts | 57 +++++++++++++++++++ .../components/modern/exportImageLayout.ts | 19 +++++++ 6 files changed, 97 insertions(+), 60 deletions(-) create mode 100644 src/web-ui/src/flow_chat/components/modern/exportImageLayout.test.ts create mode 100644 src/web-ui/src/flow_chat/components/modern/exportImageLayout.ts 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..7936cf54fa 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,14 +68,17 @@ // Export content container .export-content { + @include transcriptLayout.reading-column; @include transcriptLayout.content-column; // Preserve the transcript inset while adding quiet framing above/below. 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 */ @@ -89,28 +95,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 }; +} From 80d57dabfba5247cf8c2d9a566b1bf4808675c67 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 17:18:02 +0800 Subject: [PATCH 4/4] fix(flowchat): preserve export spacing and bundled fonts --- .../components/modern/ExportImageButton.scss | 16 +++++--- .../components/modern/ExportImageButton.tsx | 38 +++++++++---------- .../modern/FLOWCHAT_VERIFICATION.md | 7 +++- .../modern/FLOWCHAT_VIRTUALIZATION.md | 12 +++++- .../utils/exportImageCapture.test.ts | 33 +++++++++++++++- .../src/flow_chat/utils/exportImageCapture.ts | 11 +++++- 6 files changed, 86 insertions(+), 31 deletions(-) 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 7936cf54fa..621e8ffe5c 100644 --- a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss +++ b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.scss @@ -69,9 +69,9 @@ // Export content container .export-content { @include transcriptLayout.reading-column; - @include transcriptLayout.content-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; @@ -85,8 +85,6 @@ .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, @@ -172,6 +170,10 @@ } &__model-round { + // The rasterizer freezes computed heights. Contain child margins before + // measurement so cloning cannot move inter-round gaps inside fixed boxes + // and accumulate that missing space below the final response. + display: flow-root; } &__text-item { @@ -210,6 +212,8 @@ &__tool-item { margin-bottom: var(--openbitfun-control-flow-chat-flow-item-gap); + // Long command summaries must respect the image's trailing inset. + overflow: hidden; // Hide tool card action buttons and expanded content. .tool-card__actions, @@ -221,8 +225,8 @@ // ===== Footer ===== &__footer { - margin-block-start: var(--openbitfun-space-8); - padding-block-start: var(--openbitfun-space-4); + margin-block-start: var(--openbitfun-space-4); + padding-block-start: var(--openbitfun-space-3); border-block-start: var(--openbitfun-border-width-default) solid var(--openbitfun-color-border-subtle); display: flex; align-items: center; diff --git a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx index c116644c0b..7d0b534c8e 100644 --- a/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ExportImageButton.tsx @@ -347,25 +347,6 @@ export const ExportImageButton: React.FC = ({ // Yield to the main thread so the browser can finish layout/paint. await new Promise(resolve => setTimeout(resolve, 0)); - // Capture the logo placeholder position (relative to the container) - // BEFORE the DOM is torn down, so we can composite the logo precisely - // onto the final image. - const containerRect = container.getBoundingClientRect(); - const placeholderEl = container.querySelector(`.${LOGO_PLACEHOLDER_CLASS}`) as HTMLElement | null; - let logoBox: { x: number; y: number; w: number; h: number; radius: number } | null = null; - if (placeholderEl) { - const r = placeholderEl.getBoundingClientRect(); - const radiusStr = getComputedStyle(placeholderEl).getPropertyValue('border-radius'); - const radius = parseFloat(radiusStr) || 0; - logoBox = { - x: r.left - containerRect.left, - y: r.top - containerRect.top, - w: r.width, - h: r.height, - radius, - }; - } - const captureFilter = (node: Node) => { // Filter out action buttons and other non-export elements. if (node instanceof HTMLElement) { @@ -383,6 +364,25 @@ export const ExportImageButton: React.FC = ({ }; const canvas = await captureExportCanvas(container, bgColor, captureFilter); + + // Capture has settled fonts. Measure the logo against that same layout + // before removing the staging DOM. + const containerRect = container.getBoundingClientRect(); + const placeholderEl = container.querySelector(`.${LOGO_PLACEHOLDER_CLASS}`) as HTMLElement | null; + let logoBox: { x: number; y: number; w: number; h: number; radius: number } | null = null; + if (placeholderEl) { + const r = placeholderEl.getBoundingClientRect(); + const radiusStr = getComputedStyle(placeholderEl).getPropertyValue('border-radius'); + const radius = parseFloat(radiusStr) || 0; + logoBox = { + x: r.left - containerRect.left, + y: r.top - containerRect.top, + w: r.width, + h: r.height, + radius, + }; + } + cleanupDom(); // Reuse the verified raster instead of PNG -> Image -> second canvas. diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index d7c2dbd8ad..b03a3f234b 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -20,7 +20,7 @@ each missing what the other had. | `TurnFooter.test.tsx`, `modelRoundItemMemo.test.ts` | latest-turn identity, hover/focus across virtual rows, lease cleanup, no projection churn and the existing completion reveal gate; behavior only, not visual proof | | `MessageExportControls.test.tsx` | flat copy/export menu, illustrated checkbox-card selection by pointer and keyboard, complete user text/reference rendering, omission or expansion of thinking, minimal branding, confirmation, pending/error feedback, cancel/Escape/outside dismissal and resident-trigger focus restoration; local DOM behavior, not image fidelity or remote-host validation | | `exportImageLayout.test.ts` | initiating reading-column width and font settings across wide/narrow panes, hidden sibling sessions, and unmounted source rows; measured DOM fixtures, not native visual or remote-host validation | -| `../../utils/exportImageCapture.test.ts`, `../../utils/captureElementToDownloadsPng.test.tsx` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery, timeout cleanup, and widget export save/error handling; rasterizer fixtures, not native WebView or remote-host validation | +| `../../utils/exportImageCapture.test.ts`, `../../utils/captureElementToDownloadsPng.test.tsx` | resolved-style selection without duplicated theme variables, opaque/transparent blank-raster rejection before logo compositing, bounded pixel reads, reduced-scale recovery, font readiness/embedding, timeout cleanup, and widget export save/error handling; rasterizer fixtures, not native WebView or remote-host validation | | `../../../shared/ui/Tooltip.test.tsx` | shared metric click opening, immediate scroll dismissal, delayed-open cancellation, viewport-exit observer cleanup and no automatic reopening; DOM/observer behavior only, not native scrolling or visual proof | | `../../utils/turnUsageMetrics.test.ts`, `TurnUsageMetrics.test.tsx`, `../../store/modernFlowChatStore.test.ts`, `../../../features/dispatch/DispatchJobObserver.test.ts` | separate request TTFT, effective-output rate excluding waiting and tools, complete multi-round timing, controller setup-row exclusion, legacy/missing/zero telemetry, speed boundaries and projection | | `../../services/flow-chat-manager/EventHandlerModule.test.ts`, `../../services/flow-chat-manager/PersistenceModule.test.ts`, `../../store/FlowChatStore.test.ts` | live cache aggregation, optional-field persistence and legacy/current hydration; no remote-host claim | @@ -103,7 +103,10 @@ without changing size or selection; only the checkbox indicates the selected output. Check reduced motion and touch input separately. Check the captured image's user bubble against the live message, full long text/reference labels, minimal brand/date header and attribution footer, and absence of all thinking items/icons -in compact output. The same presentation +in compact output. Verify that many model rounds retain their inter-item gaps +without accumulating empty space above the footer, and that long tool summaries +respect the horizontal inset. Exercise both system and bundled font profiles on +macOS, Windows, and Linux. The same presentation on remote-workspace and peer-host sessions remains a real-host check. **Agents must not perform UI interaction verification.** Report these as pending diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index 8ac7fec54f..53962ba64d 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -68,13 +68,18 @@ keys select an output without starting capture. Export requires confirmation. Ca transcript untouched and restore focus to the resident trigger. The trigger shows export progress and stays disabled until capture finishes; the exporter stays mounted when the menu and Dialog close. There is no separate image action in the footer. -The capture uses the same transcript inset and user-bubble tokens as the live -message, with right alignment, borderless quiet fill and complete text rather +The capture keeps the live transcript column width and typography, with a +standalone image inset that grows from space-4 to space-8. It uses the live +user-bubble tokens, with right alignment, borderless quiet fill and complete text rather than the live view's three-line clamp. Persisted reference capsules reuse the live message's content renderer. Compact output omits thinking items entirely, including their icons; the other output renders expanded thinking in item order. The small brand/date header and muted attribution footer use semantic typography, spacing and divider tokens, without an assistant slogan or subtitle. +Round wrappers contain their child margins with `flow-root`: the rasterizer +freezes computed heights, so collapsing those margins outside a round before +cloning loses each inter-round gap in the SVG and leaves their sum above the +footer. Tool summaries remain inside the image inset. The image capture copies resolved CSS properties, including browser-prefixed paint properties, but excludes inherited custom properties from the cloned SVG. The staging DOM receives the initiating transcript column's measured width and @@ -88,6 +93,9 @@ uniform or transparent output is a failure even when PNG encoding would succeed. A failed raster retries at reduced scale; a timeout stops the export. Logo compositing reuses the validated canvas and its actual scale, avoiding a second full-size bitmap and keeping reduced-resolution exports aligned. +Capture waits for web fonts before measurement and embeds used faces, preserving +the bundled HarmonyOS/Fira metrics on Windows/Linux as well as system fonts on +macOS. Logo geometry is read after fonts settle, before staging DOM cleanup. Generative UI card PNG exports use the same capture helper, including blank-image rejection and reduced-scale recovery. Encoding failures must not write files or show success. Timed-out captures release any raster that completes late. diff --git a/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts index f53fd1ae05..bd85c7b465 100644 --- a/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.test.ts @@ -8,6 +8,7 @@ import { } 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() }) })); @@ -29,6 +30,8 @@ function raster(background: number, content = false, height = 65, transparent = } afterEach(() => { + if (originalFonts) Object.defineProperty(document, 'fonts', originalFonts); + else Reflect.deleteProperty(document, 'fonts'); vi.restoreAllMocks(); domToCanvas.mockReset(); vi.useRealTimers(); @@ -83,10 +86,38 @@ describe('conversation image capture', () => { const filter = vi.fn(() => true); expect(await captureExportCanvas(container, 'white', filter)).toBe(canvas); expect(domToCanvas).toHaveBeenCalledExactlyOnceWith(container, expect.objectContaining({ - scale: 2, backgroundColor: 'white', filter, includeStyleProperties: expect.any(Array), + 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); diff --git a/src/web-ui/src/flow_chat/utils/exportImageCapture.ts b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts index cc4bc7f5ac..660df7c70c 100644 --- a/src/web-ui/src/flow_chat/utils/exportImageCapture.ts +++ b/src/web-ui/src/flow_chat/utils/exportImageCapture.ts @@ -48,13 +48,22 @@ export async function captureExportCanvas( 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 }, - font: false, + // 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 }, };