Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 复制聊天图片时去掉插件标注行,气泡与普通消息一致 (#5885)
Dash1d6997782e51
diff --git a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsxindex 73fa8babd6..ae0b620d1e 100644--- a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx+++ b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx@@ -18,6 +18,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import '@/i18n';import i18n from '@/i18n';import { GhostFulfillmentContext, GhostSummonCard } from '@/components/chat/GhostSummonCard';+import { expandCollapsedMessages, stripMessageSources } from '@/lib/shareConversationImage';import type { GhostDirectiveDisplay } from '@/cindy-brain/ghostCommand';import type { HostCapabilityDirectiveDisplay } from '@/cindy-brain/hostCapabilityInvocation';import type { InstalledGhost } from '../../shared/ghost';@@ -384,4 +385,23 @@ describe('GhostSummonCard(chip 形态)', () => {// 胶囊形态没有法阵。expect(document.querySelector('circle.summon-seal-arc')).toBeNull();});++ it('leaves no empty annotation row or divider in share images', () => {+ const { container } = render(+ <div>+ <GhostSummonCard+ directive={commandDirective}+ messageClientId="m1"+ className="mb-2.5 border-b pb-2.5"+ />+ <GhostSummonCard directive={mentionDirective} messageClientId="m1" />+ <p>正文</p>+ </div>,+ );+ const clone = container.cloneNode(true) as HTMLElement;+ stripMessageSources(clone);+ expandCollapsedMessages(clone);+ expect(clone.textContent).toBe('正文');+ expect(clone.querySelector('.border-b')).toBeNull();+ });});diff --git a/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.tsindex d0edc3c7e3..7aff4850fa 100644--- a/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts+++ b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts@@ -16,10 +16,12 @@ const {SHARE_SESSION_ATTR,SHARE_SOURCE_ATTR,ShareImageTooLargeError,+ appendShareMessages,assertShareImageReadableSize,buildShareImageFooter,expandScrollableBlocks,inlineCloneImages,+ prepareShareMessageClone,queryShareableMessageIds,redactTextNodes,stripCloneAnchors,@@ -78,6 +80,114 @@ describe('stripMessageSources', () => {});});+describe('prepareShareMessageClone', () => {+ // 只发 $指令 的用户消息:气泡内只有插件标注行,气泡本身也打了来源标记。+ const chipOnlyMessage = () =>+ root(`+ <div ${SHARE_MESSAGE_ATTR}="m1" data-user-msg-id="m1">+ <div class="bubble" ${SHARE_SOURCE_ATTR}>+ <div ${SHARE_SOURCE_ATTR}><button aria-expanded="false">GitHub 已调用</button></div>+ </div>+ <div ${SHARE_EXCLUDE_ATTR}><button>复制</button></div>+ </div>+ `).firstElementChild as HTMLElement;++ it('清洗后没有内容的消息返回 null,不在图里留空白或空图', () => {+ expect(prepareShareMessageClone(chipOnlyMessage())).toBeNull();+ });++ it('插件标注去掉后保留正文,且不改动原节点', () => {+ const node = root(`+ <div ${SHARE_MESSAGE_ATTR}="m1">+ <div class="bubble">+ <div ${SHARE_SOURCE_ATTR} class="border-b"><button aria-expanded="false">GitHub</button></div>+ <div>帮我过审这个 PR</div>+ </div>+ </div>+ `).firstElementChild as HTMLElement;+ const clone = prepareShareMessageClone(node);+ expect(clone?.textContent?.trim()).toBe('帮我过审这个 PR');+ expect(clone?.querySelector('.border-b')).toBeNull();+ expect(clone?.hasAttribute(SHARE_MESSAGE_ATTR)).toBe(false);+ expect(node.querySelector(`[${SHARE_SOURCE_ATTR}]`)).not.toBeNull();+ });++ it('只有音频播放器或分隔线等非文字内容的消息照常保留', () => {+ for (const html of [+ '<div><p><audio controls src="xdt-audio://a.mp3"></audio></p></div>',+ '<div><div class="markdown"><hr /></div></div>',+ ]) {+ expect(prepareShareMessageClone(root(html).firstElementChild as HTMLElement)).not.toBeNull();+ }+ });++ it('只有图片附件的消息照常保留', () => {+ const node = root(`<div><img src="data:image/png;base64,AAAA" alt="" /></div>`)+ .firstElementChild as HTMLElement;+ expect(prepareShareMessageClone(node)).not.toBeNull();+ });+});++describe('appendShareMessages', () => {+ const message = (text: string | null) =>+ root(+ text === null+ ? `<div><div ${SHARE_SOURCE_ATTR}><button aria-expanded="false">GitHub</button></div></div>`+ : `<div><p>${text}</p></div>`,+ ).firstElementChild as HTMLElement;+ // 序列里每项 = [消息在可选序列中的位置, 正文(null = 只剩插件标注)]+ const assemble = (items: Array<[number, string | null]>) => {+ const stage = document.createElement('div');+ const ids = items.map(([index]) => `m${index}`);+ const order = new Map(ids.map((id, i) => [id, items[i][0]]));+ const count = appendShareMessages(+ stage,+ items.map(([, text]) => message(text)),+ ids,+ order,+ );+ const layout = Array.from(stage.children).map((child) =>+ child.hasAttribute('data-share-gap') ? '⋯' : (child.textContent ?? '').trim(),+ );+ return { count, layout };+ };++ it('跳过空消息时,它之前的跳选断点延续到下一条有内容的消息', () => {+ expect(+ assemble([+ [1, 'A'],+ [5, null],+ [6, 'B'],+ ]),+ ).toEqual({ count: 2, layout: ['A', '⋯', 'B'] });+ });++ it('相邻选中、中间只是一条空消息时不加断点', () => {+ expect(+ assemble([+ [1, 'A'],+ [2, null],+ [3, 'B'],+ ]),+ ).toEqual({ count: 2, layout: ['A', 'B'] });+ });++ it('图首不放断点;全空时返回 0', () => {+ expect(+ assemble([+ [1, null],+ [5, 'B'],+ ]).layout,+ ).toEqual(['B']);+ expect(+ assemble([+ [1, null],+ [2, null],+ ]),+ ).toEqual({ count: 0, layout: [] });+ });+});+describe('stripCloneAnchors', () => {it('清掉会污染全局 querySelector 的锚点属性(含根节点自身)', () => {const el = document.createElement('div');diff --git a/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts b/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.tsindex 3f7b4c1c4e..33bb162df7 100644--- a/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts+++ b/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts@@ -30,6 +30,13 @@ describe('UserMessage source labels', () => {);});+ it('marks a bubble holding only the plugin annotation as a share-image source', () => {+ // 只发 $指令 时气泡里只有插件标注行;分享图剥掉标注后整泡也要去掉,不留空壳。+ expect(userMessageSource).toMatch(+ /\{\.\.\.\(inlineQuoteCount === 0 && !displayBubbleBody\.trim\(\)\s*\? \{ \[SHARE_SOURCE_ATTR\]: '' \}\s*: \{\}\)\}/,+ );+ });+it('shows the shared-task member id on hover, like the other source labels', () => {expect(userMessageSource).toContain("t('chat.userMessage.sourceIds.member', { id: sharedAuthorMemberId })",diff --git a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsxindex 0835b57609..8c397753cb 100644--- a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx@@ -35,6 +35,7 @@ import { createContext, useContext, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, Ghost } from 'lucide-react';import { cn } from '@/lib/utils';+import { SHARE_SOURCE_ATTR } from '@/lib/shareConversationImage';import { Collapse } from '@/components/ui/collapse';import {commandDirectiveSegments,@@ -320,7 +321,7 @@ export function GhostSummonCard({directive.ghosts.length === 1 ? iconByGhostId(directive.ghosts[0].ghostId) : null;const names = directive.ghosts.map((g) => g.name).join(t('chat.ghostSummon.listSeparator'));return (- <div className="flex max-w-full flex-col items-end gap-1.5">+ <div {...{ [SHARE_SOURCE_ATTR]: '' }} className="flex max-w-full flex-col items-end gap-1.5"><buttontype="button"aria-expanded={expanded}@@ -429,8 +430,9 @@ export function GhostSummonCard({? t('chat.ghostSummon.status.called'): t('chat.ghostSummon.status.done');+ // 分享图不带插件标注(同来源标签):整行连同分隔线一起移除,气泡与普通消息一致。return (- <div className={cn('max-w-full', className)}>+ <div {...{ [SHARE_SOURCE_ATTR]: '' }} className={cn('max-w-full', className)}><buttontype="button"aria-expanded={expanded}diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex cccad55539..3668fff8cd 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -1502,6 +1502,10 @@ export function UserMessage({无余文时气泡只剩标注行。 */}{(inlineQuoteCount > 0 || displayBubbleBody.trim() || ghostChipDisplay) && (<div+ // 只剩插件标注行的气泡:分享图会剥掉标注,整泡一起去掉,不留空壳。+ {...(inlineQuoteCount === 0 && !displayBubbleBody.trim()+ ? { [SHARE_SOURCE_ATTR]: '' }+ : {})}className={cn(// overflow-wrap:anywhere(不是 break-words)才能让超长无空格序列// 在任意字符处断行,并把内容的 min-content 缩小到一个字符宽。diff --git a/apps/desktop/src/renderer/lib/shareConversationImage.ts b/apps/desktop/src/renderer/lib/shareConversationImage.tsindex 43421dc5f9..af434aad97 100644--- a/apps/desktop/src/renderer/lib/shareConversationImage.ts+++ b/apps/desktop/src/renderer/lib/shareConversationImage.ts@@ -135,6 +135,31 @@ export function stripCloneAnchors(root: HTMLElement): void {}}+/**+ * 纯布局容器标签:清洗后若只剩这些且没有文字,就是空壳。判空用「只剩容器」而不是+ * 「有某几种媒体」—— 音频播放器、分隔线等非文字元素种类多且会增加,白名单漏一种+ * 就会把整条有内容的消息误删。+ */+const SHARE_LAYOUT_ONLY_TAGS = new Set(['DIV', 'SPAN', 'P', 'SECTION', 'BR']);++/**+ * 克隆一条消息并做完全部清洗(交互件、来源标注、收起态、锚点)。清洗后没有文字、+ * 也只剩纯布局容器时返回 null:例如只发了 `$指令` 的消息,插件标注被剥掉后只剩+ * 空壳,留着会在图里占一段空白,单独分享时更会生成只有页脚的空图。+ */+export function prepareShareMessageClone(node: HTMLElement): HTMLElement | null {+ const clone = node.cloneNode(true) as HTMLElement;+ stripInteractiveElements(clone);+ stripMessageSources(clone);+ expandCollapsedMessages(clone);+ stripCloneAnchors(clone);+ if ((clone.textContent ?? '').trim().length > 0) return clone;+ const hasNonLayoutElement = Array.from(clone.querySelectorAll('*')).some(+ (el) => !SHARE_LAYOUT_ONLY_TAGS.has(el.tagName),+ );+ return hasNonLayoutElement ? clone : null;+}+const REDACTION_SCOPE_TAGS = new Set(['ADDRESS','ARTICLE',@@ -387,6 +412,38 @@ export function expandCollapsedMessages(root: HTMLElement): void {root.querySelectorAll('button[aria-expanded]').forEach((element) => element.remove());}+/**+ * 按选中顺序把清洗后的消息放进 stage,返回实际放入的条数。+ *+ * 跳选断点按「选中序列」判定(orderInAll 为当前已渲染可选序列的位置);清洗后为空的+ * 消息(本身是选中项)不放进图里,但它之前出现的断点要延续到下一条实际放进图里的+ * 消息,不能被吞掉。图首不放断点标记:前面没有内容可与之区隔。+ */+export function appendShareMessages(+ stage: HTMLElement,+ sourceNodes: readonly HTMLElement[],+ orderedSelectedIds: readonly string[],+ orderInAll: ReadonlyMap<string, number>,+): number {+ let prevIndex: number | null = null;+ let appendedCount = 0;+ let gapPending = false;+ for (const [i, node] of sourceNodes.entries()) {+ const currentIndex = orderInAll.get(orderedSelectedIds[i]) ?? null;+ if (prevIndex !== null && currentIndex !== null && currentIndex - prevIndex > 1) {+ gapPending = true;+ }+ prevIndex = currentIndex;+ const clone = prepareShareMessageClone(node);+ if (!clone) continue;+ if (gapPending && appendedCount > 0) stage.appendChild(buildShareImageGapMarker());+ gapPending = false;+ stage.appendChild(clone);+ appendedCount += 1;+ }+ return appendedCount;+}+/*** 跳选断点处的省略标记。*@@ -541,19 +598,8 @@ export async function buildShareImageBlob({const orderInAll = new Map(allIds.map((id, index) => [id, index]));try {- let prevIndex: number | null = null;- for (const [i, node] of sourceNodes.entries()) {- const currentIndex = orderInAll.get(orderedSelectedIds[i]) ?? null;- if (prevIndex !== null && currentIndex !== null && currentIndex - prevIndex > 1) {- stage.appendChild(buildShareImageGapMarker());- }- stage.appendChild(node.cloneNode(true) as HTMLElement);- prevIndex = currentIndex;- }- stripInteractiveElements(stage);- stripMessageSources(stage);- expandCollapsedMessages(stage);- stripCloneAnchors(stage);+ const appendedCount = appendShareMessages(stage, sourceNodes, orderedSelectedIds, orderInAll);+ if (appendedCount === 0) throw new ShareImageNoContentError();redactTextNodes(stage);// 品牌素材是同源打包资源,html-to-image 本可自行内联;预先转掉是为了把