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): 已发送消息的粘贴段可查看全文 (#966)

DavidShenXD82a049d88a40
diff --git a/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
new file mode 100644
index 0000000000..bf33d47f66
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
@@ -0,0 +1,195 @@
+/**
+ * sentPastedTextPreview.test.ts
+ * ---------------------------------------------------------------------------
+ * Regression tests for issue #946:「粘贴大量日志后内容被静默截断,未收到任何提示」。
+ *
+ * 实测结论:发送链路并没有截断(agent 能报出 440 行粘贴文本的末行内容),真正的缺陷
+ * 在已发送气泡的渲染上 ——
+ * 1. 粘贴段胶囊没有 onClick,全文只挂在 320×256 的 hover tooltip 上,几百行日志
+ * 读不了也复制不了,用户无法核对自己发出去的内容;
+ * 2. 收起态按原文纯文本裁到 10 行、展开态换成一个胶囊,「展开」反而看得更少。
+ *
+ * 契约:
+ * P1 projectSentPastedPlainText 把粘贴段折叠成胶囊文案,周围手打文字原样保留。
+ * P2 range 缺失 / 越界时退化为原文,绝不截断(宁可不折叠)。
+ * P3 「只粘一段」的消息投影后不再撞收起阈值 —— 不套第二层收起。
+ * S1 粘贴段胶囊接 onClick → handlePastedTextChipClick(hover tooltip 不再是唯一出口)。
+ * S2 ToolPayloadLightbox 以 kind:'text' 挂载且不传 textEdit(已发送消息只读)。
+ * S3 测量镜像与收起态渲染共用 collapseMeasureBody(同一份投影,判定与呈现一致)。
+ * S4 previewTitle 在四种界面语言里都有,标题不复用随消息落库的 display。
+ *
+ * 组件级契约走静态源码扫描,与 textLightbox.test.ts / imageLightboxCloseAnywhere.test.ts
+ * 同一约定:把测试留在 node 环境,不为这几条接线检查拖进 jsdom + react-dom。
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { projectSentPastedPlainText } from '@/components/chat/UserMessage';
+import {
+ LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
+ mayExceedVisualLineThreshold,
+} from '@/components/chat/userMessageCollapse';
+import type { PastedTextRange } from '@/lib/imageRef';
+
+const sourcePath = resolve(__dirname, '..', 'components', 'chat', 'UserMessage.tsx');
+const source = readFileSync(sourcePath, 'utf8');
+
+const LOCALES = ['zh-CN', 'en', 'ja', 'ko'] as const;
+
+/** 440 行日志的最小可测替身:行数足够撞穿收起阈值。 */
+function makeLog(lines: number): string {
+ return Array.from({ length: lines }, (_, i) => `2026-07-29 log line ${i + 1}`).join('\n');
+}
+
+describe('projectSentPastedPlainText', () => {
+ it('P1 把粘贴段折叠成胶囊文案,前后手打文字原样保留', () => {
+ const log = makeLog(440);
+ const content = `帮我看这段日志\n${log}\n有什么问题`;
+ const start = content.indexOf(log);
+ const ranges: PastedTextRange[] = [
+ { start, end: start + log.length, display: '粘贴的文本(440 行)' },
+ ];
+
+ expect(projectSentPastedPlainText(content, ranges)).toBe(
+ '帮我看这段日志\n粘贴的文本(440 行)\n有什么问题',
+ );
+ });
+
+ it('P1 多段粘贴各自折叠成自己的胶囊文案', () => {
+ const first = makeLog(30);
+ const second = makeLog(40);
+ const content = `A\n${first}\nB\n${second}\nC`;
+ const firstStart = content.indexOf(first);
+ const secondStart = content.indexOf(second, firstStart + first.length);
+ const ranges: PastedTextRange[] = [
+ { start: firstStart, end: firstStart + first.length, display: '粘贴的文本(30 行)' },
+ { start: secondStart, end: secondStart + second.length, display: '粘贴的文本(40 行)' },
+ ];
+
+ expect(projectSentPastedPlainText(content, ranges)).toBe(
+ 'A\n粘贴的文本(30 行)\nB\n粘贴的文本(40 行)\nC',
+ );
+ });
+
+ it('P2 没有 range 时原样返回', () => {
+ const content = makeLog(440);
+ expect(projectSentPastedPlainText(content)).toBe(content);
+ expect(projectSentPastedPlainText(content, [])).toBe(content);
+ });
+
+ it('P2 range 越界 / 逆序时退化为原文,不截断', () => {
+ const content = '帮我看这段日志';
+ // 越界(end 超出正文长度)——偏移不可信时宁可不折叠,也不能吞掉尾部内容。
+ expect(
+ projectSentPastedPlainText(content, [
+ { start: 2, end: content.length + 50, display: '粘贴的文本(440 行)' },
+ ]),
+ ).toBe(content);
+ // 逆序 / 空区间同样被丢弃。
+ expect(
+ projectSentPastedPlainText(content, [{ start: 5, end: 3, display: '粘贴的文本(2 行)' }]),
+ ).toBe(content);
+ });
+
+ it('P3 只粘一段的消息投影后不再撞收起阈值(不套第二层收起)', () => {
+ const log = makeLog(440);
+ const content = `看下这段日志\n${log}`;
+ const start = content.indexOf(log);
+ const ranges: PastedTextRange[] = [
+ { start, end: start + log.length, display: '粘贴的文本(440 行)' },
+ ];
+
+ // 修复前:拿原文测量,440 行必然收起 → 收起看 10 行原文、展开只剩胶囊。
+ expect(mayExceedVisualLineThreshold(content, LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD)).toBe(
+ true,
+ );
+ // 修复后:按胶囊文案测量,整条消息只有两行,直接以胶囊呈现。
+ expect(
+ mayExceedVisualLineThreshold(
+ projectSentPastedPlainText(content, ranges),
+ LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
+ ),
+ ).toBe(false);
+ });
+
+ it('P3 手打正文本身够长时仍然收起(投影只抵扣被折叠的粘贴段)', () => {
+ const typed = Array.from({ length: 40 }, (_, i) => `第 ${i + 1} 行手打说明`).join('\n');
+ const log = makeLog(200);
+ const content = `${typed}\n${log}`;
+ const start = content.indexOf(log);
+ const ranges: PastedTextRange[] = [
+ { start, end: start + log.length, display: '粘贴的文本(200 行)' },
+ ];
+
+ expect(
+ mayExceedVisualLineThreshold(
+ projectSentPastedPlainText(content, ranges),
+ LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('UserMessage pasted-text chip wiring', () => {
+ it('S1 粘贴段胶囊接上 onClick,hover tooltip 不再是查看全文的唯一出口', () => {
+ const chipBlock = source.slice(
+ source.indexOf("if (token.kind === 'pasted')"),
+ source.indexOf("if (token.kind === 'pasted')") + 1200,
+ );
+ expect(chipBlock).toContain('onPastedTextChipClick');
+ expect(chipBlock).toContain('onClick:');
+ expect(chipBlock).toContain('event.currentTarget');
+ // 三个 renderContent 调用点(引用交错分段 / 普通正文 / 召唤卡 prompt)都要传,
+ // 少传一处那条路径上的粘贴段就又变回不可点。
+ expect(source.match(/handlePastedTextChipClick,/g)?.length).toBe(3);
+ });
+
+ it('S1b 三个调用点都拿到同一份 sessionReferences(不再有 undefined 占位)', () => {
+ // 召唤卡 prompt 曾经漏传 sessionReferences(实参列表止于 slashCommandRanges),
+ // prompt 里的会话深链 chip 因此少了 referenceMetadata 的 tooltip 明细行,与气泡
+ // 正文渲染不一致(PR #966 review)。sessionReferences 按 sessionId /
+ // messageClientId 匹配、不依赖文本偏移,三处理应拿同一份。
+ // 三个调用点的末两个实参恒为 `sessionReferences, handlePastedTextChipClick`,
+ // 一并锁住"都可点"与"都有引用元数据"。
+ expect(
+ source.match(/sessionReferences,\s*\n\s*handlePastedTextChipClick,/g)?.length,
+ ).toBe(3);
+ });
+
+ it('S2 ToolPayloadLightbox 以只读 text 模式挂载', () => {
+ const lightboxStart = source.indexOf('{pastedTextPreview !== null && (');
+ expect(lightboxStart).toBeGreaterThan(-1);
+ const lightboxBlock = source.slice(lightboxStart, lightboxStart + 600);
+ expect(lightboxBlock).toContain('<ToolPayloadLightbox');
+ expect(lightboxBlock).toContain("kind: 'text'");
+ expect(lightboxBlock).toContain("t('newChat.pastedText.previewTitle')");
+ expect(lightboxBlock).toContain('triggerRef={activeFileChipRef}');
+ // 已发送消息不可编辑:textEdit 一旦传入,lightbox 会渲染保存按钮。
+ expect(lightboxBlock).not.toContain('textEdit');
+ });
+
+ it('S3 测量镜像与收起态渲染共用同一份投影正文', () => {
+ expect(source).toContain('mayExceedVisualLineThreshold(collapseMeasureBody, collapseThreshold)');
+ expect(source).toContain(
+ 'useUserMessageAutoCollapse(collapseMeasureBody, collapseMeasureEnabled, collapseThreshold)',
+ );
+ // 测量镜像(独立 JSX 表达式)。
+ expect(source.match(/\{collapseMeasureBody\}/g)?.length).toBe(1);
+ // 收起态正文(三元分支里,不是独立表达式)。
+ expect(source).toMatch(/longMessageCollapsed\s*\n?\s*\?[\s\S]{0,400}collapseMeasureBody/);
+ // 偏移只在 bubbleBody 与 ghostBody 同源时才折叠(引用交错的消息保持原文测量)。
+ expect(source).toContain('bubbleBody === ghostBody');
+ });
+
+ it('S4 previewTitle 在四种界面语言里都有', () => {
+ for (const locale of LOCALES) {
+ const localePath = resolve(__dirname, '..', 'i18n', 'locales', locale, 'common.json');
+ const parsed = JSON.parse(readFileSync(localePath, 'utf8')) as {
+ newChat: { pastedText: { previewTitle?: string } };
+ };
+ expect(parsed.newChat.pastedText.previewTitle, locale).toBeTruthy();
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index aafcb37644..4326d73715 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -67,6 +67,7 @@ import {
import { quoteSegmentsToComposerDocument } from '@/lib/composerQuoteDocument';
import { ChatImageView } from './ChatImageView';
import { TextLightbox } from './TextLightbox';
+import { ToolPayloadLightbox } from './ToolPayloadLightbox';
import { MessageActionBar } from './MessageActionBar';
import { ErrorMessageCard } from './ErrorMessageCard';
import { useForkAtMessage, textToTiptapDoc } from './useForkAtMessage';
@@ -564,6 +565,28 @@ export function buildSentInlineTokens(
return tokens;
}
+/**
+ * 收起态渲染与镜像测量共用的纯文本投影:粘贴段折叠成它自己的胶囊文案。
+ *
+ * 展开态里粘贴段是一个胶囊(点击看全文),收起态却按原文纯文本裁剪 —— 用户看到的
+ * 是"收起还能看到日志前 10 行、展开只剩一个胶囊"的反向落差(issue #946)。两侧共用
+ * 同一份投影后,收起与展开只差一个 line-clamp,内容形状一致;测量也不再被折叠掉的
+ * 几百行原文顶穿阈值,「只粘一段」的消息直接以胶囊呈现,不再多套一层收起。
+ *
+ * 只在 range 偏移确定精确时调用(见 UserMessage 的 collapseMeasureBody):
+ * buildSentInlineTokens 本身会丢弃越界 / 逆序的 range,偏移不准最坏退化成"不折叠",
+ * 不会截断或错位正文。
+ */
+export function projectSentPastedPlainText(
+ content: string,
+ pastedTextRanges: readonly PastedTextRange[] = [],
+): string {
+ if (pastedTextRanges.length === 0) return content;
+ return buildSentInlineTokens(content, pastedTextRanges)
+ .map((token) => (token.kind === 'pasted' ? token.display : token.text))
+ .join('');
+}
+
/** Locate each parsed text island in the original quote wire text. */
export function locateChatQuoteTextSegmentStarts(
content: string,
@@ -612,6 +635,11 @@ function renderContent(
pastedTextRanges: readonly PastedTextRange[] = [],
slashCommandRanges?: readonly SlashCommandRange[],
sessionReferences?: readonly PersistedSessionReferenceMetadata[],
+ /**
+ * 粘贴段胶囊的点击入口(issue #946)。不传时胶囊退回不可交互,只剩 hover
+ * tooltip —— 那正是"发出去就再也看不到全文"的旧行为,新调用点都应该传。
+ */
+ onPastedTextChipClick?: (text: string, chip: HTMLElement) => void,
): React.ReactNode[] {
const tokens = buildSentInlineTokens(content, pastedTextRanges, slashCommandRanges ?? []);
const useLegacySlashHeuristic = slashCommandRanges === undefined;
@@ -637,6 +665,15 @@ function renderContent(
tooltipContentClassName="max-h-64 w-80 max-w-[70vw] overflow-y-auto whitespace-pre-wrap [overflow-wrap:anywhere]"
ariaLabel={token.display}
className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
+ // 点击打开只读全文(与 composer 侧 pastedTextChip → ToolPayloadLightbox
+ // 对齐)。hover tooltip 是 320×256 的小浮层,几百行日志在里面读不了,
+ // 也无法选中复制,不能当作查看全文的唯一出口(issue #946)。
+ {...(onPastedTextChipClick
+ ? {
+ onClick: (event) =>
+ onPastedTextChipClick(token.text, event.currentTarget),
+ }
+ : {})}
/>
);
}
@@ -724,9 +761,18 @@ export function UserMessage({
} | null>(null);
const [orcaExpanded, setOrcaExpanded] = useState(false);
const [longMessageExpanded, setLongMessageExpanded] = useState(false);
+ // issue #946: 已发送消息里点粘贴段胶囊 → 只读全文 lightbox(无文件路径可给
+ // TextLightbox,与 composer 侧一样走 ToolPayloadLightbox 的 text 模式)。
+ const [pastedTextPreview, setPastedTextPreview] = useState<string | null>(null);
// text-lightbox F6: ref to the chip currently driving the lightbox so
// close can return focus to it (only one lightbox at a time per message).
const activeFileChipRef = useRef<HTMLElement | null>(null);
+ // 与 file chip 共用 activeFileChipRef 的"最近一次触发者胜出"语义:同一条消息
+ // 同时只会开一个 lightbox,关闭后焦点回到真正点过的那个胶囊。
+ const handlePastedTextChipClick = useCallback((text: string, chip: HTMLElement) => {
+ activeFileChipRef.current = chip;
+ setPastedTextPreview(text);
+ }, []);
// text-lightbox F1 replaces the old `@path` inline prepend. Files are now
// rendered as a dedicated Chip-Row above the text bubble (per cc-agent-view
@@ -833,14 +879,29 @@ export function UserMessage({
const collapseThreshold = automationOrigin
? AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD
: LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD;
+ // 粘贴段在 bubbleBody 局部坐标下的 range(与下方富渲染同一份投影)。
+ const bubblePastedRanges = useMemo(
+ () => projectSentRanges(pastedTextRanges ?? [], ghostBodySourceStart, bubbleBody.length),
+ [bubbleBody.length, ghostBodySourceStart, pastedTextRanges],
+ );
+ // 测量与收起态渲染共用的投影正文:粘贴段按胶囊文案计量,不再拿被折叠掉的
+ // 几百行原文去撞收起阈值(issue #946)。偏移只在 bubbleBody 与 ghostBody 同源时
+ // 精确 —— 引用交错的消息(quote 块被 join 掉,偏移会整体前移)保持原文测量。
+ const collapseMeasureBody = useMemo(
+ () =>
+ bubbleBody === ghostBody
+ ? projectSentPastedPlainText(bubbleBody, bubblePastedRanges)
+ : bubbleBody,
+ [bubbleBody, bubblePastedRanges, ghostBody],
+ );
// 合并形态($指令 / 软提示兑现 / 语义召唤)不渲文字气泡,镜像测量无处挂载,直接关掉。
const collapseMeasureEnabled =
!orcaCommunication &&
!hookSource &&
!ghostMergedForm &&
- mayExceedVisualLineThreshold(bubbleBody, collapseThreshold);
+ mayExceedVisualLineThreshold(collapseMeasureBody, collapseThreshold);
const { mirrorRef: collapseMirrorRef, shouldCollapse: shouldCollapseLongMessage } =
- useUserMessageAutoCollapse(bubbleBody, collapseMeasureEnabled, collapseThreshold);
+ useUserMessageAutoCollapse(collapseMeasureBody, collapseMeasureEnabled, collapseThreshold);
const longMessageCollapsed = shouldCollapseLongMessage && !longMessageExpanded;
// message-actions hover state — raw hover boolean, no debounce here.
@@ -1256,7 +1317,7 @@ export function UserMessage({
'whitespace-pre-wrap [overflow-wrap:anywhere]',
)}
>
- {bubbleBody}
+ {collapseMeasureBody}
</div>
)}
{inlineQuoteCount > 0 ? (
@@ -1319,6 +1380,7 @@ export function UserMessage({
segment.text.length,
),
sessionReferences,
+ handlePastedTextChipClick,
)}
</span>
),
@@ -1335,7 +1397,9 @@ export function UserMessage({
? // Collapsed chips render as plain text on purpose: otherwise
// clipped links/file chips can remain focusable behind the
// visual clamp. Expanding restores the rich chip rendering.
- bubbleBody
+ // 粘贴段用胶囊文案(而非原文)投影:与展开态同形状,
+ // 且与上方测量镜像同一份文本(issue #946)。
+ collapseMeasureBody
: renderContent(
bubbleBody,
workingDir,
@@ -1352,11 +1416,7 @@ export function UserMessage({
t,
sessionId,
isRemoteFileOrigin(sessionFileCtx.origin),
- projectSentRanges(
- pastedTextRanges ?? [],
- ghostBodySourceStart,
- bubbleBody.length,
- ),
+ bubblePastedRanges,
slashCommandRanges === undefined
? undefined
: projectSentRanges(
@@ -1365,6 +1425,7 @@ export function UserMessage({
bubbleBody.length,
),
sessionReferences,
+ handlePastedTextChipClick,
)}
</div>
)}
@@ -1431,6 +1492,14 @@ export function UserMessage({
ghostCardPromptSourceStart,
ghostCardPromptBody.length,
),
+ // 召唤卡 prompt 与气泡正文用同一份 sessionReferences:它按
+ // sessionId / messageClientId 匹配,不依赖文本偏移,不需要像
+ // pastedTextRanges / slashCommandRanges 那样投影到 prompt 局部
+ // 坐标。此前这里漏传(实参列表止于 slashCommandRanges),导致
+ // prompt 里的会话深链 chip 少了 referenceMetadata 的 tooltip
+ // 明细行,与正文渲染不一致(PR #966 review)。
+ sessionReferences,
+ handlePastedTextChipClick,
)
: undefined
}
@@ -1483,6 +1552,20 @@ export function UserMessage({
onClose={() => setTextLightboxFile(null)}
/>
)}
+ {/* issue #946: 粘贴段全文(只读)。不传 textEdit —— 已发送的消息不可改。
+ 标题用当前语言的 previewTitle,不复用随消息落库的 display(那是发送时刻
+ 的语言,切换界面语言后会变成旧语种);行数仍在胶囊标签上可见。 */}
+ {pastedTextPreview !== null && (
+ <ToolPayloadLightbox
+ payload={{
+ kind: 'text',
+ title: t('newChat.pastedText.previewTitle'),
+ text: pastedTextPreview,
+ }}
+ triggerRef={activeFileChipRef}
+ onClose={() => setPastedTextPreview(null)}
+ />
+ )}
{/* rewind-session: Preview Dialog. Only mounted while open so dryRun
re-runs cleanly each time (key on clientId for safety). */}
{rewindOpen && sessionId && messageClientId && (