Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 增加对话分享为图片 (#1879)
Dash04524188be7a
diff --git a/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.tsnew file mode 100644index 0000000000..d879b3a42f--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/shareConversationImage.test.ts@@ -0,0 +1,322 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from 'vitest';++const loadImageSourceBase64 = vi.fn();+const isImageBytesReachable = vi.fn();++vi.mock('@/lib/annotationBurnIn', () => ({+ loadImageSourceBase64: (src: string) => loadImageSourceBase64(src),+ isImageBytesReachable: (src: string) => isImageBytesReachable(src),+ blobToDataUrl: vi.fn(),+}));++const {+ SHARE_EXCLUDE_ATTR,+ SHARE_MESSAGE_ATTR,+ SHARE_SESSION_ATTR,+ ShareImageTooLargeError,+ assertShareImageReadableSize,+ buildShareImageFooter,+ expandScrollableBlocks,+ inlineCloneImages,+ queryShareableMessageIds,+ redactTextNodes,+ stripCloneAnchors,+ stripInteractiveElements,+ websiteHost,+} = await import('@/lib/shareConversationImage');++beforeEach(() => {+ vi.clearAllMocks();+ document.body.innerHTML = '';+});++function root(html: string): HTMLElement {+ const el = document.createElement('div');+ el.innerHTML = html;+ return el;+}++describe('stripInteractiveElements', () => {+ it('删掉所有打了排除标记的元素,保留正文', () => {+ const el = root(`+ <div class="body">正文内容</div>+ <div ${SHARE_EXCLUDE_ATTR}><button>复制</button></div>+ <p>段落<span ${SHARE_EXCLUDE_ATTR}>hover 工具栏</span></p>+ `);+ stripInteractiveElements(el);+ expect(el.querySelectorAll(`[${SHARE_EXCLUDE_ATTR}]`)).toHaveLength(0);+ expect(el.querySelector('button')).toBeNull();+ expect(el.textContent).toContain('正文内容');+ expect(el.textContent).toContain('段落');+ expect(el.textContent).not.toContain('hover 工具栏');+ });+});++describe('stripCloneAnchors', () => {+ it('清掉会污染全局 querySelector 的锚点属性(含根节点自身)', () => {+ const el = document.createElement('div');+ el.setAttribute(SHARE_SESSION_ATTR, 's1');+ el.setAttribute(SHARE_MESSAGE_ATTR, 'm1');+ el.setAttribute('data-message-client-id', 'client-root');+ el.innerHTML = `<div data-user-msg-id="m1" data-message-client-ids="client-a client-b"><span ${SHARE_MESSAGE_ATTR}="m2">x</span></div>`;++ stripCloneAnchors(el);++ expect(el.hasAttribute(SHARE_SESSION_ATTR)).toBe(false);+ expect(el.hasAttribute(SHARE_MESSAGE_ATTR)).toBe(false);+ expect(el.hasAttribute('data-message-client-id')).toBe(false);+ expect(el.querySelectorAll('[data-user-msg-id]')).toHaveLength(0);+ expect(el.querySelectorAll('[data-message-client-ids]')).toHaveLength(0);+ expect(el.querySelectorAll(`[${SHARE_MESSAGE_ATTR}]`)).toHaveLength(0);+ });++ it('保留 id —— mermaid / KaTeX 产物内部有 url(#id) 自引用', () => {+ const el = root('<svg><clipPath id="mmd-clip-1"></clipPath></svg>');+ stripCloneAnchors(el);+ expect(el.querySelector('#mmd-clip-1')).not.toBeNull();+ });+});++describe('redactTextNodes', () => {+ it('脱掉裸 Bearer token,保留其余正文', () => {+ const el = root('<p>调用失败,令牌 Bearer sk-abc123456789 已过期</p>');+ redactTextNodes(el);+ expect(el.textContent).not.toContain('sk-abc123456789');+ expect(el.textContent).toContain('[REDACTED]');+ expect(el.textContent).toContain('已过期');+ });++ it('header 形式的凭证连同该行剩余内容一起吞掉(既有实现的保守策略)', () => {+ const el = root('<p>Authorization: Bearer sk-abc123456789 trailing</p>');+ redactTextNodes(el);+ expect(el.textContent).not.toContain('sk-abc123456789');+ expect(el.textContent).not.toContain('trailing');+ });++ it('脱掉 key 形式的凭证', () => {+ const el = root('<code>api_key=sk-livesecretvalue123</code>');+ redactTextNodes(el);+ expect(el.textContent).not.toContain('sk-livesecretvalue123');+ });++ it('不改变 DOM 结构(代码高亮的 span 切分必须原样保留)', () => {+ const el = root(+ '<pre><code><span class="a">const t = </span><span class="b">"Bearer sk-zzzzzzzzzz"</span></code></pre>',+ );+ redactTextNodes(el);+ expect(el.querySelectorAll('span')).toHaveLength(2);+ expect(el.querySelector('span.a')?.textContent).toBe('const t = ');+ expect(el.querySelector('span.b')?.textContent).not.toContain('sk-zzzzzzzzzz');+ });++ it('普通正文不被改动', () => {+ const el = root('<p>今天天气不错,我们来聊聊架构设计。</p>');+ const before = el.innerHTML;+ redactTextNodes(el);+ expect(el.innerHTML).toBe(before);+ });+});++describe('inlineCloneImages', () => {+ it('自定义协议图换成 data URL(否则 canvas 会被 taint)', async () => {+ isImageBytesReachable.mockReturnValue(true);+ loadImageSourceBase64.mockResolvedValue({ base64: 'AAAA', mimeType: 'image/png' });++ const el = root('<img src="cindy-media://blobs/abc.png" srcset="x 2x" loading="lazy" />');+ await inlineCloneImages(el);++ const img = el.querySelector('img');+ expect(img?.getAttribute('src')).toBe('data:image/png;base64,AAAA');+ expect(img?.getAttribute('loading')).toBe('eager');+ expect(img?.hasAttribute('srcset')).toBe(false);+ });++ it('已是 data URL 的图也走统一字节层,执行大小限制并归一化', async () => {+ isImageBytesReachable.mockReturnValue(true);+ loadImageSourceBase64.mockResolvedValue({ base64: 'BBBB', mimeType: 'image/png' });+ const el = root('<img src="data:image/png;base64,BBBB" loading="lazy" />');+ await inlineCloneImages(el);++ expect(loadImageSourceBase64).toHaveBeenCalledWith('data:image/png;base64,BBBB');+ expect(el.querySelector('img')?.getAttribute('src')).toBe('data:image/png;base64,BBBB');+ expect(el.querySelector('img')?.getAttribute('loading')).toBe('eager');+ });++ it('data URL 超出统一字节层上限时移除,不进入 decode / 光栅化', async () => {+ isImageBytesReachable.mockReturnValue(true);+ loadImageSourceBase64.mockRejectedValue(new Error('图片过大'));+ const el = root('<img src="data:image/png;base64,TOO-LARGE" />');++ await inlineCloneImages(el);++ expect(el.querySelector('img')).toBeNull();+ });++ it('字节不可达的图直接移除(留着会渲染成 broken 图标)', async () => {+ isImageBytesReachable.mockReturnValue(false);+ const el = root('<img src="weird-scheme://nope" />');+ await inlineCloneImages(el);+ expect(el.querySelector('img')).toBeNull();+ });++ it('取字节失败时移除该图,不让整张图失败', async () => {+ isImageBytesReachable.mockReturnValue(true);+ loadImageSourceBase64.mockRejectedValue(new Error('read failed'));++ const el = root('<img src="cindy-media://blobs/gone.png" /><p>正文</p>');+ await inlineCloneImages(el);++ expect(el.querySelector('img')).toBeNull();+ expect(el.textContent).toContain('正文');+ });++ it('没有 src 的 img 被移除', async () => {+ const el = root('<img alt="" />');+ await inlineCloneImages(el);+ expect(el.querySelector('img')).toBeNull();+ });+});++describe('assertShareImageReadableSize', () => {+ it('保留至少 1x 的可读导出尺寸', () => {+ const el = root('');+ Object.defineProperties(el, {+ scrollWidth: { value: 800 },+ scrollHeight: { value: 4096 },+ });+ expect(() => assertShareImageReadableSize(el)).not.toThrow();+ });++ it('需要缩到 1x 以下时拒绝生成不可读缩略图', () => {+ const el = root('');+ Object.defineProperties(el, {+ scrollWidth: { value: 800 },+ scrollHeight: { value: 4097 },+ });+ expect(() => assertShareImageReadableSize(el)).toThrow(ShareImageTooLargeError);+ });+});++describe('expandScrollableBlocks', () => {+ it('只对实际溢出的候选读取样式并展开', () => {+ const el = root('<div class="fits"></div><div class="wide"></div>');+ const fits = el.querySelector<HTMLElement>('.fits')!;+ const wide = el.querySelector<HTMLElement>('.wide')!;+ Object.defineProperties(fits, {+ scrollWidth: { value: 100 },+ clientWidth: { value: 100 },+ scrollHeight: { value: 20 },+ clientHeight: { value: 20 },+ });+ Object.defineProperties(wide, {+ scrollWidth: { value: 200 },+ clientWidth: { value: 100 },+ scrollHeight: { value: 20 },+ clientHeight: { value: 20 },+ });+ const getComputedStyle = vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ overflowX: 'auto',+ overflowY: 'visible',+ } as CSSStyleDeclaration);++ try {+ expandScrollableBlocks(el);+ expect(getComputedStyle).toHaveBeenCalledTimes(1);+ } finally {+ getComputedStyle.mockRestore();+ }++ expect(fits.style.overflowX).toBe('');+ expect(wide.style.overflowX).toBe('visible');+ expect(wide.style.width).toBe('max-content');+ expect(wide.style.maxWidth).toBe('none');+ });+});++describe('queryShareableMessageIds', () => {+ it('按文档顺序返回本会话已渲染的可选消息 id', () => {+ document.body.innerHTML = `+ <div ${SHARE_SESSION_ATTR}="s1" ${SHARE_MESSAGE_ATTR}="m1"></div>+ <div ${SHARE_SESSION_ATTR}="s1" ${SHARE_MESSAGE_ATTR}="m2"></div>+ <div ${SHARE_SESSION_ATTR}="s1" ${SHARE_MESSAGE_ATTR}="m3"></div>+ `;+ expect(queryShareableMessageIds('s1')).toEqual(['m1', 'm2', 'm3']);+ });++ it('不串到另一个会话的内嵌消息流', () => {+ document.body.innerHTML = `+ <div ${SHARE_SESSION_ATTR}="s1" ${SHARE_MESSAGE_ATTR}="mine"></div>+ <div ${SHARE_SESSION_ATTR}="s2" ${SHARE_MESSAGE_ATTR}="theirs"></div>+ `;+ expect(queryShareableMessageIds('s1')).toEqual(['mine']);+ expect(queryShareableMessageIds('s2')).toEqual(['theirs']);+ });++ it('没有已渲染消息时返回空数组', () => {+ expect(queryShareableMessageIds('s1')).toEqual([]);+ });++ it('完整转义引号、反斜杠与控制字符', () => {+ const sessionId = 's"\\\n\r\f\u0001';+ const message = document.createElement('div');+ message.setAttribute(SHARE_SESSION_ATTR, sessionId);+ message.setAttribute(SHARE_MESSAGE_ATTR, 'escaped');+ document.body.appendChild(message);++ expect(queryShareableMessageIds(sessionId)).toEqual(['escaped']);+ });+});++describe('websiteHost', () => {+ it('取 host,去掉协议与路径', () => {+ expect(websiteHost('https://cindy.app')).toBe('cindy.app');+ expect(websiteHost('https://cindy.com.cn/download')).toBe('cindy.com.cn');+ });++ it('解析不了就原样返回,空值返回空串', () => {+ expect(websiteHost('not a url')).toBe('not a url');+ expect(websiteHost(undefined)).toBe('');+ });+});++describe('buildShareImageFooter', () => {+ it('形象与 logo 横向锁定,网址在下一行', () => {+ const footer = buildShareImageFooter({+ logoSrc: 'logo.png',+ characterSrc: 'character.jpg',+ siteHost: 'cindy.app',+ });+ const imgs = Array.from(footer.querySelectorAll('img'));+ expect(imgs.map((el) => el.getAttribute('src'))).toEqual(['character.jpg', 'logo.png']);+ expect(imgs[0].parentElement).toBe(imgs[1].parentElement);+ expect(footer.textContent).toBe('cindy.app');+ });++ it('角色图标小尺寸、圆角并弱化色彩', () => {+ const footer = buildShareImageFooter({+ logoSrc: 'logo.png',+ characterSrc: 'character.jpg',+ siteHost: 'cindy.app',+ });+ const character = footer.querySelector('img');+ expect(character?.style.width).toBe('40px');+ expect(character?.style.height).toBe('40px');+ expect(character?.style.borderRadius).toBe('8px');+ expect(character?.style.objectFit).toBe('cover');+ expect(character?.style.filter).toBe('saturate(0.72) contrast(0.94)');+ expect(character?.style.opacity).toBe('0.9');+ });++ it('没有形象时只放 logo', () => {+ const footer = buildShareImageFooter({ logoSrc: 'logo.png', siteHost: 'cindy.app' });+ const imgs = Array.from(footer.querySelectorAll('img'));+ expect(imgs.map((el) => el.getAttribute('src'))).toEqual(['logo.png']);+ });++ it('没有 host 时不渲染网址行', () => {+ const footer = buildShareImageFooter({ logoSrc: 'logo.png', siteHost: '' });+ expect(footer.querySelector('img')).not.toBeNull();+ expect(footer.textContent).toBe('');+ });+});diff --git a/apps/desktop/src/renderer/assets/cindy-share-character.jpg b/apps/desktop/src/renderer/assets/cindy-share-character.jpgnew file mode 100644index 0000000000..da6ebbef20Binary files /dev/null and b/apps/desktop/src/renderer/assets/cindy-share-character.jpg differdiff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex 4b0c3f73ca..81b7b69adc 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -56,6 +56,7 @@ import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrimport { insertSessionLinkIntoComposer } from '@/lib/composerActionsBus';import { MarkdownRenderer } from './MarkdownRenderer';import { MessageActionBar } from './MessageActionBar';+import { shareSelectionStore } from './shareSelectionStore';import { useForkAtMessage } from './useForkAtMessage';import { useDeleteMessage } from './useDeleteMessage';import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';@@ -263,6 +264,14 @@ export const AssistantMessage = memo(function AssistantMessage({deviceId: getStickySessionDeviceId(currentSessionId),}): undefined;+ // 分享为图片:进入选择模式并预选本条(入口那条天然该已勾选,省一次点击)。+ const handleShareAsImage = useMemo(+ () =>+ currentSessionId && messageClientId+ ? () => shareSelectionStore.enter(currentSessionId, messageClientId)+ : undefined,+ [currentSessionId, messageClientId],+ );const handleAddToChat = useCallback(() => {if (!currentSessionId || !messageDeepLink) return;insertSessionLinkIntoComposer({@@ -372,6 +381,7 @@ export const AssistantMessage = memo(function AssistantMessage({hovered={hovered}onFork={canFork ? handleFork : undefined}onAddToChat={messageDeepLink ? handleAddToChat : undefined}+ onShareAsImage={handleShareAsImage}onDelete={currentSessionId && messageClientId ? handleDelete : undefined}turnMoney={turnMoney}turnCostUsd={turnCostUsd}diff --git a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsxindex dc0276eed9..f87ea095bf 100644--- a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx@@ -34,6 +34,7 @@ import {Link2,MessageSquarePlus,Pencil,+ Share,Split,Trash2,Undo2,@@ -51,6 +52,7 @@ import {} from '@/components/ui/dropdown-menu';import { toast } from '@/lib/toast';import { formatAbsolute, useRelativeTime } from '@/hooks/useRelativeTime';+import { SHARE_EXCLUDE_ATTR } from '@/lib/shareConversationImage';import { formatCompactTokens, formatTurnCostMoney } from '@/lib/usageFormat';import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';@@ -80,6 +82,8 @@ interface MessageActionBarProps {onFork?: () => Promise<void>;/** Insert this message's anchored conversation link into the active composer. */onAddToChat?: () => void;+ /** 进入「分享为图片」选择模式并预选本条。放在复制按钮右边(产品指定位置)。 */+ onShareAsImage?: () => void;/** When provided, the More menu exposes single-message deletion. The* parent owns confirmation + persistence; the promise keeps the action* bar disabled until the flow resolves. */@@ -120,6 +124,7 @@ export function MessageActionBar({hovered,onFork,onAddToChat,+ onShareAsImage,onDelete,onEdit,onRewind,@@ -276,6 +281,42 @@ export function MessageActionBar({</button>);+ // 分享为图片 — 紧贴复制右侧。点击进入选择模式并预选本条,后续勾选与出口都在+ // 底部操作条上完成(ShareSelectionBar),所以这里是纯 fire-and-forget。+ const shareBtn = onShareAsImage && (+ <Tooltip.Root key="share">+ <Tooltip.Trigger asChild>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onShareAsImage();+ }}+ disabled={inFlight}+ className={cn(+ 'group flex h-[24px] w-[24px] items-center justify-center',+ 'rounded-full border-none bg-transparent outline-none cursor-pointer',+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors disabled:cursor-default',+ )}+ aria-label={t('chat.shareImage.entry')}+ >+ {/* iOS 同款分享形状(托盘 + 上箭头,对应 SF Symbols 的+ square.and.arrow.up);lucide 的 Share2 是三点连线的通用款,不用。 */}+ <Share+ size={14}+ strokeWidth={2}+ className={cn(+ 'text-[var(--cmd-palette-item-meta)]',+ 'group-hover:text-[var(--msg-assistant-text)]',+ 'transition-colors duration-150',+ )}+ />+ </button>+ </Tooltip.Trigger>+ <Tooltip.Content>{t('chat.shareImage.entry')}</Tooltip.Content>+ </Tooltip.Root>+ );+const forkBtn = onFork && (<Tooltip.Root key="fork"><Tooltip.Trigger asChild>@@ -586,15 +627,17 @@ export function MessageActionBar({</DropdownMenu>);- // align='left' → [copy][fork][more][time][cost] (assistant)- // align='right' → [time][copy][fork][edit][more] (user)+ // align='left' → [copy][share][fork][more][time][cost] (assistant)+ // align='right' → [time][copy][share][fork][edit][more] (user)const items =align === 'left'- ? [copyBtn, forkBtn, moreMenu, timeText, costText || tokensText]- : [timeText, copyBtn, forkBtn, editBtn, moreMenu];+ ? [copyBtn, shareBtn, forkBtn, moreMenu, timeText, costText || tokensText]+ : [timeText, copyBtn, shareBtn, forkBtn, editBtn, moreMenu];return (<div+ // 操作栏是纯交互件:分享图片的光栅化会按这个标记整条剔除,不进产物。+ {...{ [SHARE_EXCLUDE_ATTR]: '' }}className={cn('flex items-center gap-0.5',align === 'right' ? 'justify-end' : 'justify-start',diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex dd8bdecdf2..c3477fe68a 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -31,10 +31,7 @@ import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';import { SelectionQuoteButton } from './SelectionQuoteButton';import { useTranslation } from 'react-i18next';-import {- isAgentPlanToolName,- isDeliveryProseText,-} from '@cindy/maker-shared/message-render';+import { isAgentPlanToolName, isDeliveryProseText } from '@cindy/maker-shared/message-render';// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';@@ -53,13 +50,18 @@ import {isRemoteSessionSticky,subscribeTurnChangeSetUpdated,} from '@/lib/makerTransport';+import { isEditableKeyboardTarget } from '@/lib/editableKeyboardTarget';import { createLogger } from '@/lib/logger';import { stopAllMedia } from '@/lib/mediaPlaybackBus';+import { cn } from '@/lib/utils';import {readSessionScroll,saveSessionScroll,type SessionScrollSnapshot,} from '@/lib/sessionScrollStore';+import { SHARE_MESSAGE_ATTR, SHARE_SESSION_ATTR } from '@/lib/shareConversationImage';+import { ShareMessageCheckbox } from './ShareMessageCheckbox';+import { isShareableMessage, useShareSelectionActive } from './shareSelectionStore';// perf-baseline: 大 session 切换 first-paint 性能基线,保留用于回归监测。// 历史:commit ffff3603 (render-window 首引入) 因 687 条 session first-paint@@ -112,17 +114,6 @@ export const RENDER_WINDOW_FIRST_PAINT_ITEMS = 30;const RENDER_WINDOW_GROWTH_ITEMS = 80;const RENDER_WINDOW_BOUNDARY_LOOKBACK_ITEMS = 24;-function isEditableKeyboardTarget(target: EventTarget | null): boolean {- if (!(target instanceof HTMLElement)) return false;- const tagName = target.tagName;- return (- tagName === 'INPUT' ||- tagName === 'TEXTAREA' ||- tagName === 'SELECT' ||- target.isContentEditable- );-}-function eventTargetElement(target: EventTarget | null): HTMLElement | null {if (target instanceof HTMLElement) return target;if (target instanceof Node) return target.parentElement;@@ -2328,6 +2319,9 @@ export function MessageStream({// (见 sessionImageSrcs 处注释)。const sessionFileValue = useChatSessionFileValue(sessionId, workingDir, remoteHostId);+ /** 分享选择模式:只驱动整列缩进(低频)。逐条的选中态由每个复选框自己订阅。 */+ const shareSelectionActive = useShareSelectionActive(sessionId);+// 滚动容器:原生 div + overflow-y-auto,样式由全局 .is-scrolling 体系接管// (lib/scrollbarAutoHide.ts 自动加/撤 .is-scrolling 类,globals.css 控制// thumb 显隐)。data-scroll-container 给 ImageLightbox 等四个 lightbox@@ -3624,7 +3618,14 @@ export function MessageStream({}const id = window.setTimeout(run, 300);return () => window.clearTimeout(id);- }, [sessionId, navRailEnabled, navRailEntries.length, hasMoreMessages, isLoadingMore, onLoadMore]);+ }, [+ sessionId,+ navRailEnabled,+ navRailEntries.length,+ hasMoreMessages,+ isLoadingMore,+ onLoadMore,+ ]);const railJumpSeqRef = useRef(0);const [railJumpRequest, setRailJumpRequest] = useState<{ id: string; seq: number } | null>(null);@@ -3783,7 +3784,17 @@ export function MessageStream({React `key` 一律取 item.key — stable across builds(派生约定见RenderItem 类型注释 / buildRenderItems),复用 DOM 节点避免折叠态丢失 / 滚动锚点漂走。 */}- <div ref={itemsRef} className="flex flex-col gap-3.5">+ <div+ ref={itemsRef}+ className={cn(+ 'flex flex-col gap-3.5',+ // 分享选择模式:整列内容右移,左侧让出复选框那一列。缩进加在+ // 容器上(不是逐条消息),工具卡等不可选的 item 也跟着移,+ // 左边缘保持对齐。+ shareSelectionActive && 'pl-10',+ 'transition-[padding] duration-[var(--motion-base)] ease-[var(--motion-ease-move)] motion-reduce:transition-none',+ )}+ >{visibleRenderItems.map((item) => {if (item.type === 'fork_origin') {return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;@@ -3976,16 +3987,32 @@ export function MessageStream({);}+ // 分享选择:复选框与光栅化定位属性都挂在这个**既有** wrapper 上,+ // 不新增 DOM 层级 —— 多包一层会让 AssistantMessage 子树在进出+ // 选择模式时 remount(mermaid 重渲、GhostToolCard iframe 重载)。+ const shareable =+ Boolean(sessionId) && Boolean(msg.clientId) && isShareableMessage(msg);+return (<divkey={item.key}data-message-client-id={msg.clientId}- className={- highlightMessageClientId === msg.clientId- ? 'scroll-mt-20 rounded-xl bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)] transition-colors'- : 'scroll-mt-20 transition-colors'- }+ {...(shareable+ ? {+ [SHARE_SESSION_ATTR]: sessionId,+ [SHARE_MESSAGE_ATTR]: msg.clientId,+ }+ : {})}+ className={cn(+ 'scroll-mt-20 transition-colors',+ shareable && 'relative',+ highlightMessageClientId === msg.clientId &&+ 'rounded-xl bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',+ )}>+ {shareable && shareSelectionActive ? (+ <ShareMessageCheckbox clientId={msg.clientId} />+ ) : null}<MessageItemmessage={msg}toolResult={singleResultMap.get(msg.clientId)}diff --git a/apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx b/apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsxnew file mode 100644index 0000000000..1af2f3e28e--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx@@ -0,0 +1,53 @@+/**+ * ShareMessageCheckbox — 分享选择模式下挂在消息左侧的圆形选择框。+ *+ * 位置:绝对定位到消息行左外侧,落在 MessageStream 选择模式下让出的那条左缩进+ * 空白里(见 MessageStream 的 SHARE_SELECTION_INDENT_CLASS)。+ *+ * 只订阅自己那一条的选中态(useIsMessageSelected):勾选是高频动作,细粒度订阅让+ * 一次点击只重渲染这一个按钮,而不是整条消息流(见 shareSelectionStore 文件头)。+ *+ * 圆形不违反§5 三档圆角 —— 它是 pill 档(9999px)。自带 `data-share-exclude`,+ * 光栅化时会被清洗掉,不会出现在产物图片里。+ */++import { Check } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import { SHARE_EXCLUDE_ATTR } from '@/lib/shareConversationImage';+import { shareSelectionStore, useIsMessageSelected } from './shareSelectionStore';++export function ShareMessageCheckbox({ clientId }: { clientId: string }) {+ const { t } = useTranslation();+ const selected = useIsMessageSelected(clientId);++ return (+ <button+ type="button"+ role="checkbox"+ aria-checked={selected}+ aria-label={t('chat.shareImage.checkboxLabel')}+ {...{ [SHARE_EXCLUDE_ATTR]: '' }}+ onClick={(e) => {+ e.stopPropagation();+ shareSelectionStore.toggle(clientId);+ }}+ className={cn(+ // 落在 MessageStream 让出的 40px 缩进里(左 8px / 右 12px,20px 框居中偏左);+ // top 微调让圆心对齐消息首行的视觉中线。+ 'absolute -left-8 top-[2px] z-10 flex h-5 w-5 shrink-0 items-center justify-center',+ 'rounded-full transition-colors cursor-pointer',+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] outline-none',+ selected+ ? 'bg-[var(--accent-cta-bg-pure)] text-[var(--accent-pure-cta-fg)]'+ : cn(+ 'border border-[var(--border-default)] bg-transparent',+ 'hover:border-[var(--text-secondary)]',+ ),+ )}+ >+ {selected ? <Check size={12} strokeWidth={2.5} aria-hidden /> : null}+ </button>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx b/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsxnew file mode 100644index 0000000000..8eb1f8dfd8--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx@@ -0,0 +1,289 @@+/**+ * ShareSelectionBar — 分享选择模式的底部操作条。+ *+ * 选择模式下**替换 ChatInput** 占据输入区(CCAgentSessionView):正在挑消息时不该+ * 还能发消息,两者互斥比并存更清楚。+ *+ * 与页面同底、只用 1px hairline 与上方内容分隔(§2 layer rule:分隔靠边框不靠背景+ * 色差)。三个出口按钮走§4 的 pill 档:取消 / 下载到本地是 button/primary(灰 pill),+ * 复制为图片是 button/cta —— **不照抄参考图的品牌绿**,CTA 一律走 Cindy 自己的+ * --accent-cta-bg-pure。+ *+ * 键盘监听挂在 window 上而不是某个容器:用户此刻的焦点可能在消息流任意位置,+ * Esc / ⌘A 都应生效。本组件只在选择模式挂载,所以无需额外的 active 判断。+ */++import { useCallback, useEffect, useRef, useState } from 'react';+import { Check } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Spinner } from '@/components/ui/spinner';+import { blobToDataUrl } from '@/lib/annotationBurnIn';+import { isEditableKeyboardTarget } from '@/lib/editableKeyboardTarget';+import { createLogger } from '@/lib/logger';+import { copyPngBlobToClipboard } from '@/lib/rasterizeToImage';+import {+ buildShareImageBlob,+ queryShareableMessageIds,+ SHARE_EXCLUDE_ATTR,+ ShareImageSelectionNotMountedError,+ ShareImageTooLargeError,+ shareSiteHostForRegion,+} from '@/lib/shareConversationImage';+import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';+import { useBrandLogo } from '@/hooks/useBrandLogo';+import shareCharacterSrc from '@/assets/cindy-share-character.jpg';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import { shareSelectionStore, useShareSelectionCount } from './shareSelectionStore';++const log = createLogger('ShareSelectionBar');++interface ShareSelectionBarProps {+ sessionId: string;+ /** 聊天内容宽度,透传给光栅化以保证换行与流里一致。 */+ contentWidth: number;+ /** 操作条自身宽度,与 ChatInput 对齐。 */+ barWidth: number;+}++type BusyKind = 'copy' | 'download';++export function ShareSelectionBar({ sessionId, contentWidth, barWidth }: ShareSelectionBarProps) {+ const { t } = useTranslation();+ const count = useShareSelectionCount();+ const [busy, setBusy] = useState<BusyKind | null>(null);+ const mountedRef = useRef(true);+ const selectionBeforeSelectAllRef = useRef<string[] | null>(null);+ // 页脚使用产品指定的 Cindy 主视觉;wordmark 仍跟随当前主题。+ const logoSrc = useBrandLogo();+ // 不缓存:render-window 会随滚动变化,缓存会让按钮状态与当前可选消息错位;+ // 导出 / 全选动作仍会当场复查 DOM,这里仅派生当前复选框显示状态。+ const shareableMessageIds = queryShareableMessageIds(sessionId);+ const selectedVisibleCount =+ shareSelectionStore.getSelectedIdsInOrder(shareableMessageIds).length;+ const allSelected =+ shareableMessageIds.length > 0 &&+ selectedVisibleCount === shareableMessageIds.length &&+ selectedVisibleCount === count;+ const compactLayout = barWidth < 640;++ // 全选与产物顺序都以「已渲染的消息」为准(见 queryShareableMessageIds 注释:+ // render-window 外的消息克隆不到,按 messages 全集全选会静默丢内容)。+ // 每次动作时当场查 DOM —— 唯一事实源,不维护第二份可能过期的列表。+ const toggleAll = useCallback(() => {+ const messageIds = queryShareableMessageIds(sessionId);+ const selectedCount = shareSelectionStore.getSelectedIdsInOrder(messageIds).length;+ const isAllSelected =+ messageIds.length > 0 &&+ selectedCount === messageIds.length &&+ selectedCount === shareSelectionStore.count();+ if (isAllSelected) {+ shareSelectionStore.setSelection(selectionBeforeSelectAllRef.current ?? []);+ selectionBeforeSelectAllRef.current = null;+ return;+ }+ selectionBeforeSelectAllRef.current = shareSelectionStore.getSelectedIds();+ shareSelectionStore.setSelection(messageIds);+ }, [sessionId]);++ const buildBlob = useCallback(async () => {+ const orderedSelectedIds = shareSelectionStore.getSelectedIdsInOrder(+ queryShareableMessageIds(sessionId),+ );+ if (orderedSelectedIds.length !== shareSelectionStore.count()) {+ throw new ShareImageSelectionNotMountedError();+ }+ return buildShareImageBlob({+ sessionId,+ orderedSelectedIds,+ contentWidth,+ logoSrc,+ characterSrc: shareCharacterSrc,+ siteHost: shareSiteHostForRegion(CURRENT_CINDY_REGION),+ });+ }, [contentWidth, logoSrc, sessionId]);++ const run = useCallback(+ async (kind: BusyKind) => {+ if (busy || count === 0) return;+ setBusy(kind);+ try {+ const blob = await buildBlob();+ if (kind === 'copy') {+ if (!shareSelectionStore.isActive(sessionId)) return;+ await copyPngBlobToClipboard(blob);+ toast.success(t('chat.shareImage.copied'));+ } else {+ const url = await blobToDataUrl(blob);+ if (!shareSelectionStore.isActive(sessionId)) return;+ const res = await window.electronAPI.saveMediaAs({+ url,+ });+ // 用户在原生对话框里取消:不是失败,不 toast、不退出选择模式。+ if (res.canceled) return;+ toast.success(t('chat.shareImage.saved'));+ }+ shareSelectionStore.exit();+ } catch (err) {+ log.warn('share image failed', {+ kind,+ error: err instanceof Error ? err.message : String(err),+ });+ if (!shareSelectionStore.isActive(sessionId)) return;+ toast.error(+ err instanceof ShareImageSelectionNotMountedError+ ? t('chat.shareImage.notMounted')+ : err instanceof ShareImageTooLargeError+ ? t('chat.shareImage.tooLarge')+ : t('chat.shareImage.failed'),+ );+ } finally {+ if (mountedRef.current) setBusy(null);+ }+ },+ [buildBlob, busy, count, sessionId, t],+ );++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ useEffect(() => {+ function onKeyDown(e: KeyboardEvent) {+ if (e.defaultPrevented) return;+ if (isEditableKeyboardTarget(e.target)) return;+ if (busy) return;+ if (e.key === 'Escape') {+ e.preventDefault();+ shareSelectionStore.exit();+ return;+ }+ if ((e.metaKey || e.ctrlKey) && (e.key === 'a' || e.key === 'A')) {+ e.preventDefault();+ toggleAll();+ }+ }+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [busy, toggleAll]);++ const disabled = count === 0 || busy !== null;++ return (+ <div+ {...{ [SHARE_EXCLUDE_ATTR]: '' }}+ style={{ width: barWidth }}+ className={cn(+ 'border-t border-[var(--border-default)] pt-3',+ compactLayout+ ? 'grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-3 gap-y-2'+ : 'flex items-center gap-3',+ )}+ >+ {/* 部分勾选不等于全选:按钮仍显示未选中,点击后临时补齐全部;只有当前+ 可选项全部勾上时才显示选中态,再次点击恢复全选前的用户选择。 */}+ <button+ type="button"+ role="checkbox"+ aria-checked={allSelected}+ aria-label={t('chat.shareImage.selectAll')}+ onClick={toggleAll}+ disabled={busy !== null || shareableMessageIds.length === 0}+ className={cn(+ 'inline-flex h-8 shrink-0 items-center gap-2 rounded-full border px-3 text-[13px] font-medium transition-colors',+ 'outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ 'border-[var(--border-default)] bg-[var(--surface-chip)] text-[var(--text-primary)]',+ 'hover:bg-[var(--surface-hover)] disabled:cursor-default disabled:opacity-50',+ )}+ >+ <span+ className={cn(+ 'flex h-4 w-4 items-center justify-center rounded-full border transition-colors',+ allSelected+ ? 'border-[var(--accent-cta-bg-pure)] bg-[var(--accent-cta-bg-pure)] text-[var(--accent-pure-cta-fg)]'+ : 'border-[var(--text-tertiary)] bg-transparent',+ )}+ >+ {allSelected ? <Check size={11} strokeWidth={2.5} aria-hidden /> : null}+ </span>+ <span>{t('chat.shareImage.selectAll')}</span>+ </button>++ <div className="min-w-0 flex-1">+ <div className="text-[14px] font-medium leading-tight text-[var(--text-primary)]">+ {t('chat.shareImage.title')}+ </div>+ <div className="mt-0.5 truncate text-[12px] leading-tight text-[var(--text-secondary)]">+ {t('chat.shareImage.subtitle', { count })}+ </div>+ </div>++ <div+ className={cn(+ 'flex items-center gap-2',+ compactLayout ? 'col-span-2 flex-wrap justify-end' : 'shrink-0',+ )}+ >+ <button+ type="button"+ onClick={() => shareSelectionStore.exit()}+ disabled={busy !== null}+ className={cn(+ 'rounded-full px-6 py-2.5 text-[13px] font-medium transition-colors',+ 'bg-[var(--surface-chip)] text-[var(--text-primary)]',+ 'hover:bg-[var(--surface-hover)]',+ 'outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ busy && 'cursor-default opacity-50 hover:bg-[var(--surface-chip)]',+ )}+ >+ {t('chat.shareImage.cancel')}+ </button>+ <button+ type="button"+ onClick={() => void run('download')}+ disabled={disabled}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full px-6 py-2.5 text-[13px] font-medium transition-colors',+ 'bg-[var(--surface-chip)] text-[var(--text-primary)]',+ 'hover:bg-[var(--surface-hover)]',+ 'outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ disabled && 'cursor-default opacity-50 hover:bg-[var(--surface-chip)]',+ )}+ >+ {busy === 'download' ? (+ <>+ <Spinner size={13} strokeWidth={2} />+ {t('chat.shareImage.generating')}+ </>+ ) : (+ t('chat.shareImage.download')+ )}+ </button>+ <button+ type="button"+ onClick={() => void run('copy')}+ disabled={disabled}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full px-6 py-2.5 text-[13px] font-medium transition-opacity',+ 'bg-[var(--accent-cta-bg-pure)] text-[var(--accent-pure-cta-fg)]',+ 'outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ disabled ? 'cursor-default opacity-50' : 'hover:opacity-90',+ )}+ >+ {busy === 'copy' ? (+ <>+ <Spinner size={13} strokeWidth={2} />+ {t('chat.shareImage.generating')}+ </>+ ) : (+ t('chat.shareImage.copy')+ )}+ </button>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex f475fca81c..0a3343c747 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -70,6 +70,7 @@ import { ChatImageView } from './ChatImageView';import { TextLightbox } from './TextLightbox';import { ToolPayloadLightbox } from './ToolPayloadLightbox';import { MessageActionBar } from './MessageActionBar';+import { shareSelectionStore } from './shareSelectionStore';import { ErrorMessageCard } from './ErrorMessageCard';import { useForkAtMessage, textToTiptapDoc } from './useForkAtMessage';import { useDeleteMessage } from './useDeleteMessage';@@ -1125,6 +1126,15 @@ export function UserMessage({insertSessionLinkIntoComposer({ targetSessionId: sessionId, href: messageDeepLink });}, [messageDeepLink, sessionId]);+ // 分享为图片:进入选择模式并预选本条(入口那条天然该已勾选,省一次点击)。+ const handleShareAsImage = useMemo(+ () =>+ sessionId && messageClientId+ ? () => shareSelectionStore.enter(sessionId, messageClientId)+ : undefined,+ [messageClientId, sessionId],+ );+// fork-from-here: only wire when both sessionId + messageClientId are// present (older code paths that render UserMessage without these props// simply won't show the Fork button). 流程收敛在 useForkAtMessage —@@ -1256,6 +1266,17 @@ export function UserMessage({// 重渲都重建,连带"等待停止接力" effect 无谓重跑(bot review 指出)。const exitEditing = useCallback(() => setEditing(false), []);+ // 分享选择模式只克隆已发送消息的只读 DOM。仅在本条实际处于编辑态时订阅+ // share store,避免让所有 user 消息都因选择模式切换而重渲染。+ useEffect(() => {+ if (!editing || !sessionId) return;+ const exitWhenSharing = () => {+ if (shareSelectionStore.isActive(sessionId)) exitEditing();+ };+ exitWhenSharing();+ return shareSelectionStore.subscribe(exitWhenSharing);+ }, [editing, exitEditing, sessionId]);+// 编辑期间会话来了新消息(自动化任务注入等) → 本条不再是最后一条,继续// 发送会把那条新消息一起回退掉。直接退出编辑态(文本是从原消息预填的,// 退出无内容损失风险 —— 用户改到一半的文本被放弃,但这是极罕见路径,@@ -1693,6 +1714,7 @@ export function UserMessage({hovered={hovered}onFork={!isBlocked && canFork ? handleFork : undefined}onAddToChat={!isBlocked && messageDeepLink ? handleAddToChat : undefined}+ onShareAsImage={handleShareAsImage}onDelete={!isBlocked && sessionId && messageClientId ? handleDelete : undefined}onEdit={canEdit ? handleEdit : undefined}onRewind={!isBlocked && canRewind ? handleRewind : undefined}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/shareSelectionStore.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/shareSelectionStore.test.tsnew file mode 100644index 0000000000..e92a5efad6--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/shareSelectionStore.test.ts@@ -0,0 +1,180 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { isShareableMessage, shareSelectionStore } from '../shareSelectionStore';++beforeEach(() => {+ shareSelectionStore.reset();+});++describe('isShareableMessage', () => {+ it('只认正文对话:user / assistant', () => {+ expect(isShareableMessage({ role: 'user', clientId: 'x' })).toBe(true);+ expect(isShareableMessage({ role: 'assistant', clientId: 'x' })).toBe(true);+ });++ it('思考 / 工具 / 错误 / 计划 / 提问卡都不可选', () => {+ for (const role of [+ 'thinking',+ 'tool_use',+ 'tool_result',+ 'error',+ 'plan_review',+ 'ask_user',+ ]) {+ expect(isShareableMessage({ role, clientId: 'x' })).toBe(false);+ }+ });++ it('SystemCard 行与合成指令行不可选(没有可克隆的正文气泡)', () => {+ expect(isShareableMessage({ role: 'user', clientId: 'x', systemCardType: 'auto-resume' })).toBe(+ false,+ );+ expect(+ isShareableMessage({ role: 'assistant', clientId: 'x', systemCardType: 'handoff' }),+ ).toBe(false);+ expect(isShareableMessage({ role: 'user', clientId: 'x', isSyntheticTrigger: true })).toBe(+ false,+ );+ });++ it('默认折叠的 Orca communication 用户卡不可选', () => {+ expect(+ isShareableMessage({+ role: 'user',+ clientId: 'x',+ content: JSON.stringify({ orcaSource: 'lead', content: '分派任务' }),+ }),+ ).toBe(false);+ });+});++describe('shareSelectionStore', () => {+ it('默认未进入选择模式', () => {+ expect(shareSelectionStore.getActiveSessionId()).toBeNull();+ expect(shareSelectionStore.isActive('s1')).toBe(false);+ expect(shareSelectionStore.count()).toBe(0);+ });++ it('enter 预选入口那条消息', () => {+ shareSelectionStore.enter('s1', 'm1');+ expect(shareSelectionStore.isActive('s1')).toBe(true);+ expect(shareSelectionStore.isSelected('m1')).toBe(true);+ expect(shareSelectionStore.count()).toBe(1);+ });++ it('enter 不带预选时进入空选状态', () => {+ shareSelectionStore.enter('s1');+ expect(shareSelectionStore.isActive('s1')).toBe(true);+ expect(shareSelectionStore.count()).toBe(0);+ });++ it('isActive 只认当前会话', () => {+ shareSelectionStore.enter('s1', 'm1');+ expect(shareSelectionStore.isActive('s2')).toBe(false);+ expect(shareSelectionStore.isActive(undefined)).toBe(false);+ });++ it('toggle 双向切换', () => {+ shareSelectionStore.enter('s1');+ shareSelectionStore.toggle('m1');+ expect(shareSelectionStore.isSelected('m1')).toBe(true);+ shareSelectionStore.toggle('m1');+ expect(shareSelectionStore.isSelected('m1')).toBe(false);+ expect(shareSelectionStore.count()).toBe(0);+ });++ it('切到另一个会话时清空旧选中态', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.toggle('m2');+ expect(shareSelectionStore.count()).toBe(2);++ shareSelectionStore.enter('s2', 'x1');+ expect(shareSelectionStore.isActive('s2')).toBe(true);+ expect(shareSelectionStore.isSelected('m1')).toBe(false);+ expect(shareSelectionStore.isSelected('m2')).toBe(false);+ expect(shareSelectionStore.count()).toBe(1);+ });++ it('对同一会话再次 enter 保留已选,只补上预选那条', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.toggle('m2');+ shareSelectionStore.enter('s1', 'm3');+ expect(shareSelectionStore.count()).toBe(3);+ expect(shareSelectionStore.isSelected('m1')).toBe(true);+ });++ it('exit 清空模式与选中态', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.exit();+ expect(shareSelectionStore.getActiveSessionId()).toBeNull();+ expect(shareSelectionStore.count()).toBe(0);+ expect(shareSelectionStore.isSelected('m1')).toBe(false);+ });++ it('setSelection 覆盖式全选,clearSelection 只清选中不退出模式', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.setSelection(['a', 'b', 'c']);+ expect(shareSelectionStore.count()).toBe(3);+ expect(shareSelectionStore.isSelected('m1')).toBe(false);++ shareSelectionStore.clearSelection();+ expect(shareSelectionStore.count()).toBe(0);+ expect(shareSelectionStore.isActive('s1')).toBe(true);+ });++ it('getSelectedIds 返回可用于恢复的独立快照', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.toggle('m2');+ const snapshot = shareSelectionStore.getSelectedIds();++ shareSelectionStore.setSelection(['all-1', 'all-2']);+ expect(snapshot).toEqual(['m1', 'm2']);+ expect(shareSelectionStore.getSelectedIds()).toEqual(['all-1', 'all-2']);+ });++ it('getSelectedIdsInOrder 按消息流顺序返回,而不是点击顺序', () => {+ shareSelectionStore.enter('s1');+ // 倒序勾选+ shareSelectionStore.toggle('m3');+ shareSelectionStore.toggle('m1');+ shareSelectionStore.toggle('m2');+ expect(shareSelectionStore.getSelectedIdsInOrder(['m1', 'm2', 'm3', 'm4'])).toEqual([+ 'm1',+ 'm2',+ 'm3',+ ]);+ });++ it('getSelectedIdsInOrder 忽略不在有序全集里的残留 id', () => {+ shareSelectionStore.enter('s1');+ shareSelectionStore.setSelection(['gone', 'm1']);+ expect(shareSelectionStore.getSelectedIdsInOrder(['m1', 'm2'])).toEqual(['m1']);+ });++ it('exitIfNotSession 只在会话不匹配时退出', () => {+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.exitIfNotSession('s1');+ expect(shareSelectionStore.isActive('s1')).toBe(true);++ shareSelectionStore.exitIfNotSession('s2');+ expect(shareSelectionStore.getActiveSessionId()).toBeNull();+ });++ it('未进入选择模式时 exitIfNotSession 是 no-op', () => {+ shareSelectionStore.exitIfNotSession('s1');+ expect(shareSelectionStore.getActiveSessionId()).toBeNull();+ });++ it('订阅者在状态变化时收到通知', () => {+ let calls = 0;+ const unsubscribe = shareSelectionStore.subscribe(() => {+ calls += 1;+ });+ shareSelectionStore.enter('s1', 'm1');+ shareSelectionStore.toggle('m2');+ expect(calls).toBe(2);+ unsubscribe();+ shareSelectionStore.toggle('m3');+ expect(calls).toBe(2);+ });+});diff --git a/apps/desktop/src/renderer/components/chat/shareSelectionStore.ts b/apps/desktop/src/renderer/components/chat/shareSelectionStore.tsnew file mode 100644index 0000000000..61791fb9ed--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/shareSelectionStore.ts@@ -0,0 +1,188 @@+/**+ * shareSelectionStore — 「分享对话为图片」的选择模式状态(session-keyed)+ * ---------------------------------------------------------------------------+ * 为什么是模块级 store 而不是 context:消息侧的消费链是+ * MessageStream → MessageRow → AssistantMessage/UserMessage → MessageActionBar+ * 四层,且 MessageRow 是 memo。选中态放进 context 会让每次勾选都重渲染全部消息行+ * (大 session 有数百条),而勾选是高频动作。改成模块级 store + 细粒度订阅后:+ * - 进出选择模式(低频)才让消息行重渲染(useShareSelectionActive);+ * - 勾选(高频)只重渲染那一个复选框(useIsMessageSelected 按 clientId 自筛)。+ *+ * getSnapshot 一律返回原始值(boolean / number)。**不要**导出返回 Set / 数组的+ * hook —— useSyncExternalStore 会因每次新引用而无限重渲染。选中集合只在事件处理时+ * 用 `getSelectedIds` / `getSelectedIdsInOrder` 一次性读取。+ *+ * 不持久:纯 in-memory,切会话 / 刷新即清空(分享是一次性动作,没有恢复语义)。+ */++import { useSyncExternalStore } from 'react';+import { parseOrcaCommunicationContent } from './userMessageDisplayText';++/** 参与选择的消息最小结构 —— 只取判据用到的字段,不耦合完整 ChatMessage。 */+interface ShareableMessageLike {+ role: string;+ clientId?: string | undefined;+ content?: string | undefined;+ systemCardType?: unknown;+ isSyntheticTrigger?: boolean | undefined;+}++/**+ * 哪条消息可被勾选:仅正文对话(产品口径 —— 工具卡 / 思考 / 计划 / 错误卡不进图)。+ * - role 只认 user / assistant;+ * - 带 systemCardType 的行渲染成 SystemCard(自愈记录、分隔线),不是正文;+ * - isSyntheticTrigger 行根本不渲染气泡。+ * - Orca communication user 行渲染成默认折叠的任务卡,不是正文气泡。+ * 任一不满足就没有可克隆的正文 DOM。+ *+ * 「当前可选的全集」不在这里派生 —— 它以已渲染的 DOM 为准+ * (见 shareConversationImage.queryShareableMessageIds)。+ */+export function isShareableMessage(message: ShareableMessageLike): boolean {+ if (message.role !== 'user' && message.role !== 'assistant') return false;+ if (message.systemCardType) return false;+ if (message.isSyntheticTrigger) return false;+ if (message.role === 'user' && parseOrcaCommunicationContent(message.content ?? '')) return false;+ return true;+}++/** 选择模式所属会话;null = 未进入选择模式。 */+let activeSessionId: string | null = null;+const selected = new Set<string>();+const listeners = new Set<() => void>();++function notify(): void {+ for (const fn of listeners) {+ try {+ fn();+ } catch {+ /* 静默:listener 抛错不应影响其它订阅者 */+ }+ }+}++function subscribe(fn: () => void): () => void {+ listeners.add(fn);+ return () => {+ listeners.delete(fn);+ };+}++export const shareSelectionStore = {+ subscribe,++ /** 当前处于选择模式的会话 id(null = 未进入)。 */+ getActiveSessionId(): string | null {+ return activeSessionId;+ },++ isActive(sessionId: string | undefined): boolean {+ return Boolean(sessionId) && activeSessionId === sessionId;+ },++ isSelected(clientId: string | undefined): boolean {+ return clientId ? selected.has(clientId) : false;+ },++ count(): number {+ return selected.size;+ },++ /** 当前完整选中集合的快照;用于「全选」临时覆盖后恢复用户原选择。 */+ getSelectedIds(): string[] {+ return Array.from(selected);+ },++ /**+ * 进入选择模式。`preselectClientId` 是入口那条消息 —— 用户从某条消息的操作栏+ * 点进来,那条天然应该已勾选(少一次点击)。切到另一个会话时清空旧选中态。+ */+ enter(sessionId: string, preselectClientId?: string): void {+ if (!sessionId) return;+ if (activeSessionId !== sessionId) selected.clear();+ activeSessionId = sessionId;+ if (preselectClientId) selected.add(preselectClientId);+ notify();+ },++ exit(): void {+ if (activeSessionId === null && selected.size === 0) return;+ activeSessionId = null;+ selected.clear();+ notify();+ },++ toggle(clientId: string): void {+ if (!clientId) return;+ if (selected.has(clientId)) selected.delete(clientId);+ else selected.add(clientId);+ notify();+ },++ /** 全选 / 覆盖式设置(⌘A)。 */+ setSelection(clientIds: readonly string[]): void {+ selected.clear();+ for (const id of clientIds) {+ if (id) selected.add(id);+ }+ notify();+ },++ clearSelection(): void {+ if (selected.size === 0) return;+ selected.clear();+ notify();+ },++ /**+ * 按**消息流顺序**返回已选 id。Set 的迭代顺序是点击顺序,直接用会让图片里的+ * 消息乱序;所以以调用方传入的有序全集为准过滤。+ */+ getSelectedIdsInOrder(orderedIds: readonly string[]): string[] {+ return orderedIds.filter((id) => selected.has(id));+ },++ /**+ * 会话切换时的收口:当前选择模式属于别的会话就退出。+ * (会话视图 remount 时调用 —— 选择态不跨会话保留。)+ */+ exitIfNotSession(sessionId: string | undefined): void {+ if (activeSessionId === null) return;+ if (activeSessionId === sessionId) return;+ shareSelectionStore.exit();+ },++ /** 仅供测试。 */+ reset(): void {+ activeSessionId = null;+ selected.clear();+ listeners.clear();+ },+};++/** 该会话是否处于选择模式(低频变化 —— 消息行订阅这个)。 */+export function useShareSelectionActive(sessionId: string | undefined): boolean {+ return useSyncExternalStore(+ subscribe,+ () => shareSelectionStore.isActive(sessionId),+ () => false,+ );+}++/** 单条消息是否已勾选(高频变化 —— 只有那一个复选框重渲染)。 */+export function useIsMessageSelected(clientId: string | undefined): boolean {+ return useSyncExternalStore(+ subscribe,+ () => shareSelectionStore.isSelected(clientId),+ () => false,+ );+}++/** 已选条数(底部操作条订阅)。 */+export function useShareSelectionCount(): number {+ return useSyncExternalStore(+ subscribe,+ () => shareSelectionStore.count(),+ () => 0,+ );+}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex fa5ac9e3af..27c9aac909 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -71,6 +71,11 @@ import { PlanViewerCard } from '@/components/new-chat/PlanViewerCard';import { PlanActionCard } from '@/components/new-chat/PlanActionCard';import { InteractionPromptHost } from '@/components/interaction-portal';import { MessageStream } from '@/components/chat/MessageStream';+import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';+import {+ shareSelectionStore,+ useShareSelectionActive,+} from '@/components/chat/shareSelectionStore';import { ErrorBanner } from '@/components/chat/ErrorBanner';import {ErrorTailErrorBanner,@@ -3144,6 +3149,33 @@ export function CCAgentSessionView({</>);+ // ── 分享为图片:选择模式 ──+ // 底部操作条与 ChatInput 互斥(挑消息时不该还能发消息),所以状态在这里读一次,+ // 供下方输入区的 ternary 链分流。+ const shareSelectionActive = useShareSelectionActive(sessionId);+ // 输入区被更高优先级的态占走(远程接管 / 会话准备中 / 任何 pending 交互)时,+ // 底部操作条会随之卸载 —— 那样用户就失去了退出选择模式的入口(Esc 监听在条上)。+ // 所以这些态一出现就主动退出:分享是轻量的一次性动作,重新点一次即可。+ const shareSelectionBlocked =+ Boolean(sessionBinding.attached) ||+ worktreePreparing ||+ Boolean(+ pendingPlanReview ||+ pendingPermission ||+ pendingAskUser ||+ pendingPluginSetup ||+ pendingIssueConfirm ||+ pendingRenameSessionsConfirm ||+ pendingGhostGrantConfirm,+ );+ useEffect(() => {+ if (shareSelectionActive && shareSelectionBlocked) shareSelectionStore.exit();+ }, [shareSelectionActive, shareSelectionBlocked]);+ // 切会话不保留选择态(分享没有跨会话恢复语义)。+ useEffect(() => {+ shareSelectionStore.exitIfNotSession(sessionId);+ }, [sessionId]);+// MessageStream 提成变量:perf/session-switch 的 <Profiler> 是纯诊断,只在 DEV// 包裹(见下方渲染处),生产直接渲染此 el,不引入多余 Profiler fiber。const messageStreamEl = (@@ -3730,6 +3762,12 @@ export function CCAgentSessionView({/>) : worktreePreparing && smoothedBranchName ? (<WorktreeCreatingOverlay branchName={smoothedBranchName} />+ ) : shareSelectionActive && sessionId ? (+ <ShareSelectionBar+ sessionId={sessionId}+ contentWidth={messageWidth}+ barWidth={inputWidth}+ />) : (<ChatInputonSend={handleSend}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 84e86307e1..3fbef85ace 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5674,6 +5674,24 @@"turnTokens": "{{tokens}} tokens","userTurnCostDetailsTitle": "Request details"},+ "shareImage": {+ "entry": "Share as Image",+ "title": "Share Conversation",+ "subtitle_one": "{{count}} message selected",+ "subtitle_other": "{{count}} messages selected",+ "selectAll": "Select All",+ "clearAll": "Deselect All",+ "checkboxLabel": "Select this message",+ "cancel": "Cancel",+ "download": "Save Image",+ "copy": "Copy Image",+ "generating": "Generating…",+ "copied": "Image copied",+ "saved": "Image saved",+ "notMounted": "Some selected messages are not currently visible. Scroll back to show them, then try again",+ "tooLarge": "The selection is too long or wide. Select less content and try again",+ "failed": "Couldn't generate the image — try again"+ },"errorBanner": {"retryTitle": "Resend the last message","cancelTitle": "Dismiss error",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 46c2c2e8bf..0f52e84b30 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5672,6 +5672,23 @@"turnTokens": "{{tokens}} tokens","userTurnCostDetailsTitle": "リクエストの明細"},+ "shareImage": {+ "entry": "画像として共有",+ "title": "会話を共有",+ "subtitle_other": "{{count}} 件のメッセージを選択中",+ "selectAll": "すべて選択",+ "clearAll": "選択を解除",+ "checkboxLabel": "このメッセージを選択",+ "cancel": "キャンセル",+ "download": "画像を保存",+ "copy": "画像をコピー",+ "generating": "生成中…",+ "copied": "画像をコピーしました",+ "saved": "画像を保存しました",+ "notMounted": "選択したメッセージの一部が表示されていません。上へスクロールして表示してから再試行してください",+ "tooLarge": "選択内容が長すぎるか幅が広すぎます。選択を減らして再試行してください",+ "failed": "画像を生成できませんでした。もう一度お試しください"+ },"errorBanner": {"retryTitle": "最後のメッセージを再送信","cancelTitle": "エラーを閉じる",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7a58558685..a628824af2 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5672,6 +5672,23 @@"turnTokens": "{{tokens}} tokens","userTurnCostDetailsTitle": "이번 요청 상세"},+ "shareImage": {+ "entry": "이미지로 공유",+ "title": "대화 공유",+ "subtitle_other": "메시지 {{count}}개 선택",+ "selectAll": "전체 선택",+ "clearAll": "선택 해제",+ "checkboxLabel": "이 메시지 선택",+ "cancel": "취소",+ "download": "이미지 저장",+ "copy": "이미지 복사",+ "generating": "생성 중…",+ "copied": "이미지를 복사했습니다",+ "saved": "이미지를 저장했습니다",+ "notMounted": "선택한 메시지 중 일부가 표시되지 않았습니다. 위로 스크롤해 표시한 후 다시 시도하세요",+ "tooLarge": "선택한 내용이 너무 길거나 넓습니다. 선택을 줄인 후 다시 시도하세요",+ "failed": "이미지를 생성하지 못했습니다. 다시 시도해 주세요"+ },"errorBanner": {"retryTitle": "마지막 메시지 다시 보내기","cancelTitle": "오류 알림 닫기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 85ad8aa591..3d3645c7b4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5672,6 +5672,23 @@"turnTokens": "{{tokens}} tokens","userTurnCostDetailsTitle": "本轮明细"},+ "shareImage": {+ "entry": "分享为图片",+ "title": "分享对话",+ "subtitle_other": "已选 {{count}} 条消息",+ "selectAll": "全选",+ "clearAll": "取消全选",+ "checkboxLabel": "选择这条消息",+ "cancel": "取消",+ "download": "下载到本地",+ "copy": "复制为图片",+ "generating": "正在生成…",+ "copied": "图片已复制",+ "saved": "图片已保存",+ "notMounted": "有些已选消息暂未显示,请滚动回去让它们显示后重试",+ "tooLarge": "所选内容过长或过宽,请减少选择后重试",+ "failed": "图片生成失败,请重试"+ },"errorBanner": {"retryTitle": "重新发送最后一条消息","cancelTitle": "关闭错误提示",diff --git a/apps/desktop/src/renderer/lib/editableKeyboardTarget.ts b/apps/desktop/src/renderer/lib/editableKeyboardTarget.tsnew file mode 100644index 0000000000..d0c43af18a--- /dev/null+++ b/apps/desktop/src/renderer/lib/editableKeyboardTarget.ts@@ -0,0 +1,17 @@+/**+ * 键盘快捷键的「让位」判据:焦点落在可编辑控件里时,全局快捷键不该抢走按键。+ *+ * 独立成模块而不是各处自己写一份:MessageStream(历史导航键)与+ * ShareSelectionBar(⌘A / Esc)共用同一判据,同一语义只留一个实现;也让+ * 依赖它的小组件不必为了一个工具函数 import 整个 MessageStream。+ */+export function isEditableKeyboardTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ const tagName = target.tagName;+ return (+ tagName === 'INPUT' ||+ tagName === 'TEXTAREA' ||+ tagName === 'SELECT' ||+ target.isContentEditable+ );+}diff --git a/apps/desktop/src/renderer/lib/shareConversationImage.ts b/apps/desktop/src/renderer/lib/shareConversationImage.tsnew file mode 100644index 0000000000..814ba1eb78--- /dev/null+++ b/apps/desktop/src/renderer/lib/shareConversationImage.ts@@ -0,0 +1,594 @@+/**+ * shareConversationImage — 「把选中的对话生成一张图」的光栅化管线(renderer)。+ *+ * 做法是**克隆聊天流里已渲染好的消息 DOM**,而不是拿消息数据重新渲染一遍 React。+ * 理由:正文里的 mermaid(懒加载 + 异步 render)、KaTeX、代码高亮、已 decode 的图片+ * 在流里都已是最终形态,克隆即可拿到;重新渲染要自己判定「什么时候算渲染完」,+ * 风险和代码量都高得多。被勾选的消息一定是用户当时看得见的,所以它的 DOM 必然在+ * MessageStream 的 render-window 内。+ *+ * 关键一步是**图片必须先转 data URL**:自定义协议(cindy-media:// 等)的图打进+ * canvas 会 taint,随后 toBlob 被跨源拦截 —— 这条教训已记录在 annotationBurnIn.ts+ * 文件头,那里的 `loadImageSourceBase64` 正是为此存在,这里直接复用。+ *+ * 脱敏只做凭证(产品口径):复用 maker-shared 的 redactSensitiveText,逐 text node+ * 改写,不碰 DOM 结构。+ */++import type { CindyRegion } from '@cindy/maker-shared/brand-identity';+import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';+import { diffChars } from 'diff';++import { isImageBytesReachable, loadImageSourceBase64 } from '@/lib/annotationBurnIn';+import { createLogger } from '@/lib/logger';+import { computeExportScale, domToPngBlob, resolveExportBackground } from '@/lib/rasterizeToImage';++const log = createLogger('ShareConversationImage');++/** 消息行挂的定位属性 —— 与 MessageStream 的 wrapper 保持一致。 */+export const SHARE_SESSION_ATTR = 'data-share-session-id';+export const SHARE_MESSAGE_ATTR = 'data-share-message-id';+/** 打了这个标记的元素是纯交互件(操作栏、复选框、hover 工具栏),不进图。 */+export const SHARE_EXCLUDE_ATTR = 'data-share-exclude';++/** 分享图片页脚使用的品牌域名。dev 的行为语义归 cn 系。 */+export const SHARE_SITE_HOST_BY_REGION: Readonly<Record<CindyRegion, string>> = Object.freeze({+ cn: 'cindy.cn',+ dev: 'cindy.cn',+ global: 'cindy.app',+});++export function shareSiteHostForRegion(region: CindyRegion): string {+ return SHARE_SITE_HOST_BY_REGION[region];+}++/**+ * 克隆体里必须清掉的锚点属性:离屏容器挂在 document 内,这些 data 属性会让+ * 全局 querySelector(PrevMessageJumpChip 的 data-user-msg-id、消息导航的+ * data-message-client-id(s)、本模块自己的定位属性)命中克隆节点,干扰真实+ * 聊天流的滚动/跳转逻辑。+ * 注意**不清 `id`** —— mermaid / KaTeX 产物内部有 `url(#…)` 自引用,清掉会破图。+ */+const CLONE_STRIPPED_ATTRS = [+ 'data-user-msg-id',+ 'data-message-client-id',+ 'data-message-client-ids',+ SHARE_SESSION_ATTR,+ SHARE_MESSAGE_ATTR,+] as const;++export interface BuildShareImageOptions {+ /** 会话 id —— 与 sessionId 一起定位,避免命中内嵌的第二个 MessageStream。 */+ sessionId: string;+ /** 已选 clientId,**必须按消息流顺序**传入(顺序即图片里的顺序)。 */+ orderedSelectedIds: readonly string[];+ /** 内容宽度(px),与聊天流同宽,保证换行与流里所见一致。 */+ contentWidth: number;+ /** 页脚品牌 logo 的 URL(打包资源,同源)。 */+ logoSrc: string;+ /** 页脚 Cindy 角色主视觉的 URL(打包资源,同源)。 */+ characterSrc?: string;+ /** 页脚网址文字(host,如 cindy.app)。 */+ siteHost: string;+}++/** 找不到任何选中消息的 DOM 时抛这个 —— 调用方据此 toast。 */+export class ShareImageNoContentError extends Error {+ constructor() {+ super('no selected message nodes found');+ this.name = 'ShareImageNoContentError';+ }+}++/** 找不到仍挂载的已选消息时抛这个 —— 调用方应引导用户滚回后重试。 */+export class ShareImageSelectionNotMountedError extends Error {+ constructor() {+ super('one or more selected message nodes are not mounted');+ this.name = 'ShareImageSelectionNotMountedError';+ }+}++/** 选区过长或过宽、只能缩成低于 1x 的不可读缩略图时抛这个。 */+export class ShareImageTooLargeError extends Error {+ constructor() {+ super('selected content exceeds the readable share image size');+ this.name = 'ShareImageTooLargeError';+ }+}++/**+ * 当前**已渲染**的可选消息 id,按文档顺序(= 消息流顺序)。+ *+ * 为什么以 DOM 而不是 messages 数组为事实源:MessageStream 有 render-window,+ * 长会话里较早的消息还没 mount。若「全选」按 messages 全集来,窗口外那些消息会被+ * 选上却克隆不到,产物图静默缺内容 —— 用户看不出少了东西。而选择框本身也只长在+ * 已渲染的消息上(看不见的消息点不到),所以「可选 = 已渲染」本就是用户看到的语义。+ */+export function queryShareableMessageIds(sessionId: string): string[] {+ const selector = `[${SHARE_SESSION_ATTR}="${cssAttrValue(sessionId)}"][${SHARE_MESSAGE_ATTR}]`;+ return Array.from(document.querySelectorAll<HTMLElement>(selector))+ .map((el) => el.getAttribute(SHARE_MESSAGE_ATTR) ?? '')+ .filter(Boolean);+}++/**+ * 删掉纯交互件。给元素打 `data-share-exclude` 比在这里靠 class 名猜稳:+ * 组件改样式不会让清洗失效。+ */+export function stripInteractiveElements(root: HTMLElement): void {+ root.querySelectorAll(`[${SHARE_EXCLUDE_ATTR}]`).forEach((el) => el.remove());+}++/** 清掉会污染全局 querySelector 的锚点属性(见 CLONE_STRIPPED_ATTRS 注释)。 */+export function stripCloneAnchors(root: HTMLElement): void {+ for (const attr of CLONE_STRIPPED_ATTRS) {+ if (root.hasAttribute(attr)) root.removeAttribute(attr);+ root.querySelectorAll(`[${attr}]`).forEach((el) => el.removeAttribute(attr));+ }+}++const REDACTION_SCOPE_TAGS = new Set([+ 'ADDRESS',+ 'ARTICLE',+ 'ASIDE',+ 'BLOCKQUOTE',+ 'DIV',+ 'DL',+ 'FIELDSET',+ 'FIGURE',+ 'FOOTER',+ 'FORM',+ 'H1',+ 'H2',+ 'H3',+ 'H4',+ 'H5',+ 'H6',+ 'HEADER',+ 'LI',+ 'MAIN',+ 'NAV',+ 'OL',+ 'P',+ 'PRE',+ 'SECTION',+ 'TABLE',+ 'TD',+ 'TH',+ 'TR',+ 'UL',+]);++interface TextNodeRange {+ node: Text;+ start: number;+ end: number;+}++function redactionScopeFor(node: Text, root: HTMLElement): Element {+ let current = node.parentElement;+ while (current && current !== root) {+ if (REDACTION_SCOPE_TAGS.has(current.tagName)) return current;+ current = current.parentElement;+ }+ return root;+}++function textNodeRanges(nodes: readonly Text[]): TextNodeRange[] {+ let offset = 0;+ return nodes.map((node) => {+ const text = node.nodeValue ?? '';+ const range = { node, start: offset, end: offset + text.length };+ offset = range.end;+ return range;+ });+}++function textNodeIndexAtOffset(ranges: readonly TextNodeRange[], offset: number): number {+ for (let index = 0; index < ranges.length; index += 1) {+ const range = ranges[index];+ if (offset < range.end || (offset === range.end && index === ranges.length - 1)) {+ return index;+ }+ }+ return Math.max(0, ranges.length - 1);+}++function projectRedactedText(nodes: readonly Text[], redactedText: string): void {+ const ranges = textNodeRanges(nodes);+ const projected = nodes.map(() => '');+ const originalText = ranges.map((range) => range.node.nodeValue ?? '').join('');+ let originalOffset = 0;++ for (const change of diffChars(originalText, redactedText)) {+ if (change.added) {+ const index = textNodeIndexAtOffset(ranges, originalOffset);+ projected[index] += change.value;+ continue;+ }++ if (change.removed) {+ originalOffset += change.value.length;+ continue;+ }++ let valueOffset = 0;+ while (valueOffset < change.value.length) {+ const index = textNodeIndexAtOffset(ranges, originalOffset + valueOffset);+ const range = ranges[index];+ const available = range.end - (originalOffset + valueOffset);+ const chunkLength = Math.min(available, change.value.length - valueOffset);+ projected[index] += change.value.slice(valueOffset, valueOffset + chunkLength);+ valueOffset += chunkLength;+ }+ originalOffset += change.value.length;+ }++ nodes.forEach((node, index) => {+ node.nodeValue = projected[index];+ });+}++/**+ * 按逻辑连续文本段脱敏,再把结果投影回原有 text node。只改 nodeValue,不动结构 ——+ * 已渲染的 markdown(代码高亮的 span 切分、KaTeX 的字形节点)必须原样保留。+ * 不能逐 node 调用:JSON 高亮会把 key、分隔符、value 拆到多个 span,逐段脱敏会+ * 看不到完整的 assignment,从而把 opaque secret 原样带进图片。+ */+export function redactTextNodes(root: HTMLElement): void {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const runs = new Map<Element, Text[]>();+ let node = walker.nextNode();+ while (node) {+ const textNode = node as Text;+ if (textNode.nodeValue) {+ const scope = redactionScopeFor(textNode, root);+ const run = runs.get(scope);+ if (run) run.push(textNode);+ else runs.set(scope, [textNode]);+ }+ node = walker.nextNode();+ }++ for (const run of runs.values()) {+ const originalText = run.map((textNode) => textNode.nodeValue ?? '').join('');+ const redactedText = redactSensitiveText(originalText);+ if (redactedText !== originalText) projectRedactedText(run, redactedText);+ }+}++/**+ * 把克隆体里的图片换成 data URL。自定义协议图不转就会 taint canvas(见文件头)。+ * 字节不可达的图直接移除:留着会在产物里渲染成 broken 图标,比缺图更难看。+ */+export async function inlineCloneImages(root: HTMLElement): Promise<void> {+ const images = Array.from(root.querySelectorAll('img'));+ await Promise.all(+ images.map(async (img) => {+ const src = img.getAttribute('src');+ if (!src) {+ img.remove();+ return;+ }+ if (!isImageBytesReachable(src)) {+ log.warn('share image: unreachable image source, dropping', {+ scheme: src.slice(0, 16),+ });+ img.remove();+ return;+ }+ try {+ const { base64, mimeType } = await loadImageSourceBase64(src);+ img.setAttribute('src', `data:${mimeType};base64,${base64}`);+ img.setAttribute('loading', 'eager');+ img.removeAttribute('srcset');+ } catch (err) {+ log.warn('share image: failed to inline image, dropping', {+ error: err instanceof Error ? err.message : String(err),+ });+ img.remove();+ }+ }),+ );+}++/**+ * 分享图至少保留 1x CSS 像素密度。共享光栅化层的 4096 单边上限是内存硬边界,+ * 继续缩小虽能成功导出,但正文会退化成不可读缩略图;这里宁可明确拒绝。+ */+export function assertShareImageReadableSize(root: HTMLElement): void {+ if (computeExportScale(root.scrollWidth, root.scrollHeight, 2) < 1) {+ throw new ShareImageTooLargeError();+ }+}++/**+ * 让横向/纵向可滚动的块在产物里完整展开。+ *+ * 流内的宽表格、长代码行是 `overflow-x:auto` —— 用户能滚动看全。克隆进图片后+ * 滚动条不存在,右侧内容会被**静默裁掉**:接收方既看不到也不知道被裁了。所以+ * 导出时把这些容器改成按内容宽度展开,图会变宽但信息完整+ * (html-to-image 的画布宽取 `scrollWidth`,底色铺满整张画布,溢出区不会透明)。+ *+ * 必须在克隆体挂进 document **之后**调用 —— getComputedStyle 对游离节点无效。+ */+export function expandScrollableBlocks(root: HTMLElement): void {+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {+ const overflowsX = el.scrollWidth > el.clientWidth;+ const overflowsY = el.scrollHeight > el.clientHeight;+ if (!overflowsX && !overflowsY) continue;++ const style = window.getComputedStyle(el);+ if (overflowsX && (style.overflowX === 'auto' || style.overflowX === 'scroll')) {+ el.style.overflowX = 'visible';+ // 只解除 overflow 不够:容器仍被父级宽度约束,内容照旧在边界处截断。+ el.style.width = 'max-content';+ el.style.maxWidth = 'none';+ }+ if (overflowsY && (style.overflowY === 'auto' || style.overflowY === 'scroll')) {+ el.style.overflowY = 'visible';+ el.style.maxHeight = 'none';+ }+ }+}++/**+ * 把克隆体里的消息恢复到完整可读状态。用户消息可能由 line-clamp-3/10 收起,+ * 克隆时正文其实已经在 DOM 中,但 clamp 会让图片只包含前几行;展开按钮也没有可用+ * 的交互,所以两者都必须在光栅化前移除。+ */+export function expandCollapsedMessages(root: HTMLElement): void {+ root.querySelectorAll<HTMLElement>('[class]').forEach((element) => {+ for (const className of Array.from(element.classList)) {+ if (/^line-clamp-\d+$/.test(className)) element.classList.remove(className);+ }+ });+ root.querySelectorAll('button[aria-expanded]').forEach((element) => element.remove());+}++/**+ * 跳选断点处的省略标记。+ *+ * 选了第 1、第 5 条时,两条在图里直接相邻 —— 接收方看不出中间还有对话被跳过,+ * 读起来像一段连续的完整记录。这是诚实性问题,所以断点必须可见。+ */+export function buildShareImageGapMarker(): HTMLElement {+ const marker = document.createElement('div');+ marker.textContent = '⋯';+ marker.style.textAlign = 'center';+ marker.style.fontSize = '14px';+ marker.style.lineHeight = '1';+ marker.style.letterSpacing = '2px';+ marker.style.color = 'var(--text-tertiary)';+ marker.setAttribute('data-share-gap', '');+ return marker;+}++/**+ * 同源资源 → data URL。页脚 logo 是打包 asset,html-to-image 本可自行内联,+ * 但预先转掉能把「产物里 logo 空白」这类不确定性彻底消掉。+ */+async function sameOriginToDataUrl(url: string): Promise<string> {+ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`share image asset fetch failed (${response.status})`);+ }+ const blob = await response.blob();+ return new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(blob);+ });+}++/** Cindy 角色图标的边长(px)。 */+const FOOTER_CHARACTER_PX = 40;+/** 品牌 wordmark 高度(px)。 */+const FOOTER_LOGO_HEIGHT_PX = 24;++export interface ShareImageFooterAssets {+ /** 品牌 wordmark(按主题深浅选好的那一版)。 */+ logoSrc: string;+ /** Cindy 角色主视觉;缺省时页脚只有 logo。 */+ characterSrc?: string;+ /** 网址文字(host,如 cindy.app)。 */+ siteHost: string;+}++/**+ * 品牌页脚:角色图标与 logo 横向锁定,网址在下一行,整体居中。+ * 角色图标仅承担品牌识别,通过小尺寸和轻度降饱和避免抢正文。+ */+export function buildShareImageFooter({+ logoSrc,+ characterSrc,+ siteHost,+}: ShareImageFooterAssets): HTMLElement {+ const footer = document.createElement('div');+ footer.className = 'flex flex-col items-center';+ footer.style.paddingTop = '48px';+ footer.style.gap = '6px';++ const lockup = document.createElement('div');+ lockup.className = 'flex items-center justify-center';+ lockup.style.gap = '8px';++ if (characterSrc) {+ const character = document.createElement('img');+ character.src = characterSrc;+ character.alt = '';+ character.style.height = `${FOOTER_CHARACTER_PX}px`;+ character.style.width = `${FOOTER_CHARACTER_PX}px`;+ character.style.borderRadius = '8px';+ character.style.objectFit = 'cover';+ character.style.filter = 'saturate(0.72) contrast(0.94)';+ character.style.opacity = '0.9';+ character.style.flexShrink = '0';+ character.setAttribute('loading', 'eager');+ lockup.appendChild(character);+ }++ const logo = document.createElement('img');+ logo.src = logoSrc;+ logo.alt = '';+ logo.style.height = `${FOOTER_LOGO_HEIGHT_PX}px`;+ logo.style.width = 'auto';+ logo.setAttribute('loading', 'eager');+ lockup.appendChild(logo);+ footer.appendChild(lockup);++ if (siteHost) {+ const site = document.createElement('span');+ site.textContent = siteHost;+ site.style.fontSize = '11px';+ site.style.color = 'var(--text-tertiary)';+ footer.appendChild(site);+ }+ return footer;+}++/** `https://cindy.app/` → `cindy.app`;解析失败回落原串。 */+export function websiteHost(websiteUrl: string | undefined): string {+ if (!websiteUrl) return '';+ try {+ return new URL(websiteUrl).host;+ } catch {+ return websiteUrl;+ }+}++/**+ * 生成分享图片。产物为 PNG Blob;出口(剪贴板 / 另存为)由调用方决定。+ */+export async function buildShareImageBlob({+ sessionId,+ orderedSelectedIds,+ contentWidth,+ logoSrc,+ characterSrc,+ siteHost,+}: BuildShareImageOptions): Promise<Blob> {+ const sourceNodes: HTMLElement[] = [];+ for (const clientId of orderedSelectedIds) {+ const selector = `[${SHARE_SESSION_ATTR}="${cssAttrValue(sessionId)}"][${SHARE_MESSAGE_ATTR}="${cssAttrValue(clientId)}"]`;+ const node = document.querySelector<HTMLElement>(selector);+ if (node) sourceNodes.push(node);+ }+ // 选中的消息里有克隆不到 DOM 的(被删除、或极端情况下已卸载):宁可整次失败,+ // 也不出一张静默缺内容的图 —— 用户不会知道少了哪一条。+ if (sourceNodes.length !== orderedSelectedIds.length) {+ log.warn('share image: selected message nodes are not mounted', {+ missingCount: orderedSelectedIds.length - sourceNodes.length,+ });+ throw new ShareImageSelectionNotMountedError();+ }+ if (sourceNodes.length === 0) throw new ShareImageNoContentError();++ // 实底色取自真实聊天流(天然跟随当前主题)。起点用消息的**父容器**而不是消息自身:+ // 搜索命中态的消息带高亮底色(--search-match-bg),从它起找会让整张图变成高亮色。+ const background = resolveExportBackground(sourceNodes[0].parentElement ?? sourceNodes[0]);++ // 离屏定位必须挂在**外层 host** 上,不能放到被光栅化的 stage 自己身上:+ // html-to-image 会把目标节点的 computed style 内联进产物 SVG,`position:fixed`+ // + `left:-99999px` 一起被复制过去,内容就被推出画布,产物只剩一片背景色+ // (2026-08-06 实测:图片全白就是这么来的)。host 负责藏,stage 保持静态定位。+ const host = document.createElement('div');+ host.setAttribute('data-share-export-host', '');+ host.style.position = 'fixed';+ host.style.left = '-99999px';+ host.style.top = '0';+ host.style.zIndex = '-1';+ host.style.pointerEvents = 'none';++ const stage = document.createElement('div');+ stage.setAttribute('data-share-export', '');+ // 显式静态定位 —— 见上:任何偏移类样式都会被内联进产物。+ stage.style.position = 'static';+ // content-box 是刻意的:全局 preflight 把 box-sizing 设成 border-box,那样+ // width 会连 padding 一起算,内容宽比聊天流窄 2×padding —— 换行位置就和用户+ // 在流里看到的不一样了。+ stage.style.boxSizing = 'content-box';+ stage.style.width = `${Math.max(320, Math.round(contentWidth))}px`;+ stage.style.backgroundColor = background;+ // 图片四周留一圈呼吸空间(产物是独立的一张图,不是页面局部截取)。+ stage.style.padding = '40px';+ // 条间距刻意比流内的 14px 宽:流内紧凑是为了信息密度,而独立的一张图要留白+ // 才读得开(§5「留白即品牌」)。+ stage.className = 'flex flex-col gap-6';+ host.appendChild(stage);++ // 跳选判据:选中项在「当前已渲染的可选序列」里是否相邻。以 DOM 序为准,+ // 与 queryShareableMessageIds / 全选同一个事实源。+ const allIds = queryShareableMessageIds(sessionId);+ 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);+ expandCollapsedMessages(stage);+ stripCloneAnchors(stage);+ redactTextNodes(stage);++ // 品牌素材是同源打包资源,html-to-image 本可自行内联;预先转掉是为了把+ // 「产物里 logo / 形象空白」这类不确定性彻底消掉。任一失败都只降级该张图,+ // 不连带整次导出。+ const [footerLogo, footerCharacter] = await Promise.all([+ sameOriginToDataUrl(logoSrc).catch((err) => {+ log.warn('share image: logo inline failed, falling back to raw src', {+ error: err instanceof Error ? err.message : String(err),+ });+ return logoSrc;+ }),+ characterSrc+ ? sameOriginToDataUrl(characterSrc).catch((err) => {+ log.warn('share image: character inline failed, dropping character', {+ error: err instanceof Error ? err.message : String(err),+ });+ return undefined;+ })+ : Promise.resolve(undefined),+ ]);+ stage.appendChild(+ buildShareImageFooter({+ logoSrc: footerLogo,+ ...(footerCharacter ? { characterSrc: footerCharacter } : {}),+ siteHost,+ }),+ );++ document.body.appendChild(host);+ // 顺序要紧:展开可滚动块依赖 computed style,必须等挂进 document 之后。+ expandScrollableBlocks(stage);+ await inlineCloneImages(stage);+ // data URL 换上后等一次 decode,避免 html-to-image 序列化到尚未解码的图。+ await Promise.all(+ Array.from(stage.querySelectorAll('img')).map((img) => img.decode().catch(() => undefined)),+ );+ assertShareImageReadableSize(stage);++ return await domToPngBlob(stage, { background });+ } finally {+ host.remove();+ }+}++/**+ * 属性选择器里的值要转义。clientId 是内部生成的 id,理论上不含引号/反斜杠,+ * 但选择器拼接一律走转义 —— 不给未来的 id 格式变更留注入面。+ */+function cssAttrValue(value: string): string {+ return value.replace(/[\0-\x1f\x7f"\\]/g, (character) => {+ if (character === '\0') return '\uFFFD';+ if (character === '"' || character === '\\') return `\\${character}`;+ return `\\${character.codePointAt(0)?.toString(16) ?? ''} `;+ });+}diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 0f3613dccd..33721c8ce6 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -278,7 +278,7 @@ Three tiers — **these three only**:- Don't invent arbitrary radii — only three values exist: 8px (inner controls), 12px (containers), 9999px (pill). Nothing in between, nothing else.- Don't add shadows to any element — the flat aesthetic is intentional- Don't use font weights above 500 — no bold, no black weight-- Don't add decorative illustrations — Cindy's working UI carries no mascots or artwork; brand imagery appears only on sanctioned brand surfaces (login, splash, new-session brand block — see §15.7 / §16)+- Don't add decorative illustrations — Cindy's working UI carries no mascots or artwork; brand imagery appears only on the explicitly enumerated sanctioned brand surfaces in §15.7 / §16- Don't use gradients anywhere — flat blocks and borders only- Don't overcomplicate the layout — stick to the region structure in §5; no complex nested grids- Don't use borders heavier than 1px — containment is always the lightest possible touch@@ -1005,7 +1005,14 @@ The brand block reads only `brand.icon/logo` — no compatibility with the legacThe splash wordmark is a separate asset pair (`assets/splash/wordmark.png`, white text, for DARK / `wordmark-light.png`, dark text, for LIGHT): both 459×156 (@2x) with a 229.5×78 render frame (its exact 2x full frame), and **neither carries a drop shadow** — `SplashScreen.test.tsx` asserts the absence. (Asset-size and shadow history: decision log.)-**Sanctioned brand surface — mobile download dialog (approved 2026-07-25).** The fourth surface allowed to carry brand artwork, alongside login / splash / new-session:+**Sanctioned brand surface — conversation-share export footer (approved 2026-08-06).**++- **Where**: the footer of PNG images generated by `renderer/lib/shareConversationImage.ts` only. The live conversation, selection mode, message stream, composer, and other working-UI surfaces remain neutral and must not display the character artwork.+- **Lockup**: one static 40×40px product-approved Cindy character crop (8px radius), followed by the active theme's 24px-high wordmark with an 8px gap; the regional host sits below in tertiary text (`cindy.cn` for `cn` / `dev`, `cindy.app` for `global`). The character stays deliberately quiet (`saturate(0.72) contrast(0.94)`, 0.9 opacity) so message content remains primary.+- **Constraints**: no animation, shadow, decorative background, additional brand color, enlarged hero treatment, or alternate character composition. This approval identifies the source of an exported Cindy conversation; it is not precedent for adding mascots to cards, dialogs, tool output, or other share-adjacent UI.+- **Theme boundary**: Light and Dark use their matching wordmark assets and semantic tertiary text. The same static character crop may be used in both modes because it is an exported brand asset, not a UI color surface.++**Sanctioned brand surface — mobile download dialog (approved 2026-07-25).**- **Where**: `components/sidebar/MobileDownloadDialog.tsx` only, and only the dialog header icon (64px `resources/icon.png`). This is a promotion surface for the mobile app, so showing the app's own icon is identification, not decoration.- **Constraints**: the color comes only from the official asset — no component-authored gradient or brand hex. The QR card itself carries **no brand edge, no border, no shadow and no pointer 3D tilt**: a 2px edge made of the scaled app icon was tried on 2026-07-25 and removed the same day (it read as a strange ring rotating behind the code — see §14.4). Do not re-add it in any form, static or animated.