Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复长聊天记录分享图片失败 (#2438)

Dash5682002ab41b
diff --git a/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts
index 76ab8a48d6..85917daa23 100644
--- a/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts
@@ -178,19 +178,37 @@ describe('inlineCloneImages', () => {
});
describe('assertShareImageReadableSize', () => {
- it('保留至少 1x 的可读导出尺寸', () => {
+ it('窄长聊天记录超过 4096px 仍可保持至少 1x', () => {
const el = root('');
Object.defineProperties(el, {
scrollWidth: { value: 800 },
- scrollHeight: { value: 4096 },
+ scrollHeight: { value: 10_000 },
});
expect(() => assertShareImageReadableSize(el)).not.toThrow();
});
- it('需要缩到 1x 以下时拒绝生成不可读缩略图', () => {
+ it('达到分享长图单边上限时仍允许 1x', () => {
const el = root('');
Object.defineProperties(el, {
scrollWidth: { value: 800 },
+ scrollHeight: { value: 16_384 },
+ });
+ expect(() => assertShareImageReadableSize(el)).not.toThrow();
+ });
+
+ it('超过分享长图单边上限时拒绝生成不可读缩略图', () => {
+ const el = root('');
+ Object.defineProperties(el, {
+ scrollWidth: { value: 800 },
+ scrollHeight: { value: 16_385 },
+ });
+ expect(() => assertShareImageReadableSize(el)).toThrow(ShareImageTooLargeError);
+ });
+
+ it('单边未超限但输出像素超过预算时仍拒绝', () => {
+ const el = root('');
+ Object.defineProperties(el, {
+ scrollWidth: { value: 4096 },
scrollHeight: { value: 4097 },
});
expect(() => assertShareImageReadableSize(el)).toThrow(ShareImageTooLargeError);
diff --git a/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts b/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
index 59114e642c..16d620cf2e 100644
--- a/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
@@ -2,15 +2,16 @@
/**
* rasterizeToImage — 导出倍率收敛与 SVG 固有尺寸解析的单测。
*
- * 这两段纯计算是「复制为图片」大图内存保护的核心(4096 边长上限对齐手机版
- * mermaidWebViewHtml 的收敛逻辑);canvas / clipboard 等浏览器 API 行为不在
- * jsdom 里模拟,由运行时验证覆盖。
+ * 这两段纯计算是「复制为图片」大图内存保护的核心(默认 4096 边长 + 4096²
+ * 输出像素预算);canvas / clipboard 等浏览器 API 行为不在 jsdom 里模拟,
+ * 由运行时验证覆盖。
*/
import { describe, expect, it } from 'vitest';
import {
EXPORT_MAX_EDGE_PX,
+ EXPORT_MAX_OUTPUT_PIXELS,
EXPORT_PNG_SCALE,
computeExportScale,
parseSvgIntrinsicSize,
@@ -32,9 +33,7 @@ describe('computeExportScale', () => {
expect(computeExportScale(8192, 100)).toBe(EXPORT_MAX_EDGE_PX / 8192);
// 超长内容(>40960px)不得为可读性抬倍率突破边长上限(review P1)
expect(computeExportScale(1_000_000, 100)).toBe(EXPORT_MAX_EDGE_PX / 1_000_000);
- expect(1_000_000 * computeExportScale(1_000_000, 100)).toBeLessThanOrEqual(
- EXPORT_MAX_EDGE_PX,
- );
+ expect(1_000_000 * computeExportScale(1_000_000, 100)).toBeLessThanOrEqual(EXPORT_MAX_EDGE_PX);
});
it('非法尺寸回退 1', () => {
@@ -47,6 +46,16 @@ describe('computeExportScale', () => {
expect(computeExportScale(400, 300, 2)).toBe(2);
expect(computeExportScale(4000, 300, 2)).toBeCloseTo(4096 / 4000);
});
+
+ it('自定义长边允许窄长图超过 4096,同时守住同一输出像素预算', () => {
+ const width = 800;
+ const height = 10_000;
+ const scale = computeExportScale(width, height, 2, 16_384, EXPORT_MAX_OUTPUT_PIXELS);
+
+ expect(scale).toBeGreaterThan(1);
+ expect(Math.max(width, height) * scale).toBeLessThanOrEqual(16_384);
+ expect(width * height * scale * scale).toBeCloseTo(EXPORT_MAX_OUTPUT_PIXELS);
+ });
});
describe('parseSvgIntrinsicSize', () => {
diff --git a/apps/desktop/src/renderer/lib/rasterizeToImage.ts b/apps/desktop/src/renderer/lib/rasterizeToImage.ts
index 78c00b1dd3..c162b026b5 100644
--- a/apps/desktop/src/renderer/lib/rasterizeToImage.ts
+++ b/apps/desktop/src/renderer/lib/rasterizeToImage.ts
@@ -29,38 +29,45 @@ export const EXPORT_PNG_SCALE = 3;
*/
export const EXPORT_MAX_EDGE_PX = 4096;
+/** 输出像素总量上限:与 4096×4096 位图保持同一约 64MB 内存预算。 */
+export const EXPORT_MAX_OUTPUT_PIXELS = EXPORT_MAX_EDGE_PX * EXPORT_MAX_EDGE_PX;
+
/**
- * 倍率收敛(纯函数,单测覆盖):目标倍率对 4096 边长上限取 min。maxEdge 是
- * **硬上限**(内存保护是第一目标):内容本身超长时倍率允许任意小,产物是
- * 一张有界的整体缩略图——绝不为可读性抬高倍率突破上限(review P1:钳 0.1
- * 下界会让 50000px 内容导出 5000px 位图,内存峰值超设计值)。
+ * 倍率收敛(纯函数,单测覆盖):目标倍率同时受最长边与输出像素总量约束。
+ * 两个限制都是**硬上限**(内存保护是第一目标):内容本身超长时倍率允许任意小,
+ * 产物是一张有界的整体缩略图——绝不为可读性抬高倍率突破上限(review P1:
+ * 钳 0.1 下界会让 50000px 内容导出 5000px 位图,内存峰值超设计值)。
*/
export function computeExportScale(
width: number,
height: number,
desiredScale: number = EXPORT_PNG_SCALE,
maxEdge: number = EXPORT_MAX_EDGE_PX,
+ maxOutputPixels: number = EXPORT_MAX_OUTPUT_PIXELS,
): number {
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
return 1;
}
- return Math.min(desiredScale, maxEdge / Math.max(width, height));
+ const edgeScale = maxEdge / Math.max(width, height);
+ const pixelScale = Math.sqrt(maxOutputPixels / (width * height));
+ return Math.min(desiredScale, edgeScale, pixelScale);
}
/**
* 从 SVG 字符串解析固有尺寸(纯函数,单测覆盖):viewBox 优先(与显示期
* CSS 收缩无关),缺 viewBox 时回退 width/height 属性(剥掉 px 单位)。
*/
-export function parseSvgIntrinsicSize(
- svgText: string,
-): { width: number; height: number } | null {
+export function parseSvgIntrinsicSize(svgText: string): { width: number; height: number } | null {
const container = document.createElement('div');
container.innerHTML = svgText;
const el = container.querySelector('svg');
if (!el) return null;
const vb = el.getAttribute('viewBox');
if (vb) {
- const parts = vb.trim().split(/[\s,]+/).map(Number);
+ const parts = vb
+ .trim()
+ .split(/[\s,]+/)
+ .map(Number);
if (parts.length === 4 && parts[2] > 0 && parts[3] > 0) {
return { width: parts[2], height: parts[3] };
}
@@ -125,9 +132,7 @@ export async function svgToPngBlob(
ctx.fillRect(0, 0, outW, outH);
ctx.drawImage(image, 0, 0, outW, outH);
- const blob = await new Promise<Blob | null>((resolve) =>
- canvas.toBlob(resolve, 'image/png'),
- );
+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));
if (!blob) throw new Error('png encode failed');
return blob;
}
@@ -156,18 +161,29 @@ function getCachedFontEmbedCss(node: HTMLElement): Promise<string> {
/**
* HTML DOM 节点 → PNG Blob(表格 / 块级公式路径)。
* - 尺寸取 `scrollWidth/scrollHeight`(宽表格取完整内容宽,不被可视口截断);
- * - 倍率经 computeExportScale 收敛(默认 2x——DOM 块以文字为主,2x 已够
- * 清晰,比 3x 省一半以上内存);
+ * - 倍率经 computeExportScale 按最长边与输出像素预算收敛(默认 2x——DOM 块以
+ * 文字为主,2x 已够清晰,比 3x 省一半以上内存);
* - `await document.fonts.ready` + 内联 @font-face,保证 KaTeX 字形不回退。
*/
export async function domToPngBlob(
node: HTMLElement,
- opts?: { scale?: number; background?: string },
+ opts?: {
+ scale?: number;
+ background?: string;
+ maxEdge?: number;
+ maxOutputPixels?: number;
+ },
): Promise<Blob> {
const width = node.scrollWidth;
const height = node.scrollHeight;
if (width <= 0 || height <= 0) throw new Error('node has no size');
- const scale = computeExportScale(width, height, opts?.scale ?? 2);
+ const scale = computeExportScale(
+ width,
+ height,
+ opts?.scale ?? 2,
+ opts?.maxEdge,
+ opts?.maxOutputPixels,
+ );
await document.fonts.ready;
const fontEmbedCSS = await getCachedFontEmbedCss(node);
@@ -192,10 +208,7 @@ export async function domToPngBlob(
* 表示:粘贴目标按自己的偏好取格式——飞书/文档吃图片,代码编辑器/输入框吃
* 源码(mermaid 源码 / 表格 TSV / 公式 LaTeX),一次复制两头可用。
*/
-export async function copyPngBlobToClipboard(
- blob: Blob,
- plainText?: string,
-): Promise<void> {
+export async function copyPngBlobToClipboard(blob: Blob, plainText?: string): Promise<void> {
const representations: Record<string, Blob> = { 'image/png': blob };
if (plainText) {
representations['text/plain'] = new Blob([plainText], { type: 'text/plain' });
diff --git a/apps/desktop/src/renderer/lib/shareConversationImage.ts b/apps/desktop/src/renderer/lib/shareConversationImage.ts
index a31269f91d..0017d18188 100644
--- a/apps/desktop/src/renderer/lib/shareConversationImage.ts
+++ b/apps/desktop/src/renderer/lib/shareConversationImage.ts
@@ -20,10 +20,21 @@ import { diffChars } from 'diff';
import { isImageBytesReachable, loadImageSourceBase64 } from '@/lib/annotationBurnIn';
import { createLogger } from '@/lib/logger';
-import { computeExportScale, domToPngBlob, resolveExportBackground } from '@/lib/rasterizeToImage';
+import {
+ computeExportScale,
+ domToPngBlob,
+ EXPORT_MAX_OUTPUT_PIXELS,
+ resolveExportBackground,
+} from '@/lib/rasterizeToImage';
const log = createLogger('ShareConversationImage');
+/**
+ * Desktop 长图可安全使用比共享默认值更长的单边;像素总量仍沿用 4096² 预算,
+ * 所以窄长聊天记录不会因“塞不进正方形”被误拒绝,也不会放大位图内存峰值。
+ */
+const SHARE_IMAGE_MAX_EDGE_PX = 16_384;
+
/** 消息行挂的定位属性 —— 与 MessageStream 的 wrapper 保持一致。 */
export const SHARE_SESSION_ATTR = 'data-share-session-id';
export const SHARE_MESSAGE_ATTR = 'data-share-message-id';
@@ -279,11 +290,19 @@ export async function inlineCloneImages(root: HTMLElement): Promise<void> {
}
/**
- * 分享图至少保留 1x CSS 像素密度。共享光栅化层的 4096 单边上限是内存硬边界,
- * 继续缩小虽能成功导出,但正文会退化成不可读缩略图;这里宁可明确拒绝。
+ * 分享图至少保留 1x CSS 像素密度。聊天记录使用更长的单边上限,但输出像素总量
+ * 仍受共享 4096² 预算约束;任一限制要求缩到 1x 以下时,宁可明确拒绝不可读缩略图。
*/
export function assertShareImageReadableSize(root: HTMLElement): void {
- if (computeExportScale(root.scrollWidth, root.scrollHeight, 2) < 1) {
+ if (
+ computeExportScale(
+ root.scrollWidth,
+ root.scrollHeight,
+ 2,
+ SHARE_IMAGE_MAX_EDGE_PX,
+ EXPORT_MAX_OUTPUT_PIXELS,
+ ) < 1
+ ) {
throw new ShareImageTooLargeError();
}
}
@@ -535,7 +554,11 @@ export async function buildShareImageBlob({
);
assertShareImageReadableSize(stage);
- return await domToPngBlob(stage, { background });
+ return await domToPngBlob(stage, {
+ background,
+ maxEdge: SHARE_IMAGE_MAX_EDGE_PX,
+ maxOutputPixels: EXPORT_MAX_OUTPUT_PIXELS,
+ });
} finally {
host.remove();
}