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: 统一消息 chip 的乐观态与收起态渲染 (#1680)

Dash789f417c70bf
diff --git a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
index 23d388150f..646f0ed9c2 100644
--- a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
+++ b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
@@ -230,6 +230,25 @@ describe('agentInputQueue', () => {
expect(updated.sessionReferencesRequireTrustedSnapshot).toBeUndefined();
});
+ it('drops stale agent-reference offsets from both queued message copies', () => {
+ const entry = queuedMessage(undefined);
+ const reference = {
+ kind: 'project' as const,
+ start: 0,
+ end: 12,
+ href: 'cindy://project/repo',
+ name: 'repo',
+ workingDir: '/repo',
+ };
+ entry.agentReferences = [reference];
+ entry.chatMessage.agentReferences = [reference];
+
+ const updated = updateQueuedMessageText(entry, 'rewritten');
+
+ expect(updated.agentReferences).toBeUndefined();
+ expect(updated.chatMessage.agentReferences).toBeUndefined();
+ });
+
it('clears stale slash offsets but keeps the explicit no-legacy marker after a text rewrite', () => {
const entry = queuedMessage(undefined);
entry.persistedContent = JSON.stringify({
diff --git a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
index 1423a8ef60..87cbe95ba2 100644
--- a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
@@ -34,8 +34,9 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =
"longMessageCollapsed && (automationOrigin ? 'line-clamp-3' : 'line-clamp-10')",
);
expect(userMessageSource).toMatch(
- /longMessageCollapsed\n\s+\? projectSentInlinePlainText\(\n\s+segment\.text,/,
+ /\{renderContent\(\n\s+segment\.text,/,
);
+ expect(userMessageSource).toContain('!longMessageCollapsed,');
});
it('keeps right-click Add to chat enabled while suppressing the floating button', () => {
diff --git a/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx b/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx
index 4df46324d6..cd249a29f4 100644
--- a/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sentAgentReferencePresentation.test.tsx
@@ -123,4 +123,40 @@ describe('sent structured reference chips', () => {
expect(chip?.querySelector('svg')).not.toBeNull();
expect(container.textContent).not.toContain('cindy://');
});
+
+ it('renders static sent references without focus or button semantics', () => {
+ const { container } = render(
+ <SentAgentReferenceChip
+ interactive={false}
+ reference={browserReference().reference}
+ />,
+ );
+ const chip = container.querySelector('[data-inline-reference-chip]');
+
+ expect(chip).not.toBeNull();
+ expect(chip?.getAttribute('role')).toBeNull();
+ expect(chip?.getAttribute('tabindex')).toBeNull();
+ expect(container.querySelector('button')).toBeNull();
+ });
+
+ it('keeps static message references in the quote-chip shape', () => {
+ const { container } = render(
+ <SentAgentReferenceChip
+ interactive={false}
+ reference={{
+ kind: 'message',
+ start: 0,
+ end: 16,
+ href: 'cindy://session/session-1?message=message-1',
+ sessionId: 'session-1',
+ messageClientId: 'message-1',
+ text: 'Quoted message',
+ }}
+ />,
+ );
+
+ expect(container.textContent).toContain('Quoted message');
+ expect(container.querySelector('[data-inline-reference-chip]')).not.toBeNull();
+ expect(container.querySelector('button')).toBeNull();
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx b/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx
new file mode 100644
index 0000000000..0b02607345
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx
@@ -0,0 +1,80 @@
+// @vitest-environment jsdom
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-i18next')>();
+ return {
+ ...actual,
+ useTranslation: () => ({ t: (key: string) => key }),
+ };
+});
+
+import { formatQuoteForSend } from '@/lib/chatQuotes';
+import { SentInlineAtomBody } from '@/components/chat/SentInlineAtomBody';
+
+const pendingQueueSource = readFileSync(
+ resolve(__dirname, '..', 'components', 'new-chat', 'PendingQueuePanel.tsx'),
+ 'utf8',
+).replace(/\r\n?/g, '\n');
+
+describe('SentInlineAtomBody', () => {
+ it('keeps the same atom shapes in static queue/collapse projections without focus targets', () => {
+ const quote = formatQuoteForSend({ text: 'quoted context' });
+ const content = `${quote}\n\n/help\n\nfull pasted payload\n\n@src/App.tsx\n\n@src/index.ts`;
+ const slashStart = content.indexOf('/help');
+ const pastedStart = content.indexOf('full pasted payload');
+ const agentStart = content.indexOf('@src/App.tsx');
+
+ render(
+ <SentInlineAtomBody
+ agentReferences={[
+ {
+ kind: 'project',
+ start: agentStart,
+ end: agentStart + '@src/App.tsx'.length,
+ href: 'cindy://project/src',
+ name: 'src',
+ workingDir: '/tmp/src',
+ },
+ ]}
+ content={content}
+ pastedTextRanges={[
+ {
+ start: pastedStart,
+ end: pastedStart + 'full pasted payload'.length,
+ display: 'Pasted text (1 line)',
+ },
+ ]}
+ quotesEncoded
+ slashCommandRanges={[{ start: slashStart, end: slashStart + '/help'.length }]}
+ />,
+ );
+
+ expect(screen.getByText('quoted context')).toBeTruthy();
+ expect(screen.getByText('/help')).toBeTruthy();
+ expect(screen.getByText('Pasted text (1 line)')).toBeTruthy();
+ expect(screen.getByText('src')).toBeTruthy();
+ expect(screen.getByText('index.ts')).toBeTruthy();
+ expect(screen.queryByRole('button')).toBeNull();
+ expect(document.querySelector('button')).toBeNull();
+ expect(document.querySelector('[tabindex]')).toBeNull();
+ });
+
+ it('leaves the pending queue single-line truncation contract to the row container', () => {
+ const bodyStart = pendingQueueSource.indexOf('<SentInlineAtomBody');
+ const bodyEnd = pendingQueueSource.indexOf('/>', bodyStart);
+
+ expect(bodyStart).toBeGreaterThanOrEqual(0);
+ expect(bodyEnd).toBeGreaterThan(bodyStart);
+ const bodyBlock = pendingQueueSource.slice(bodyStart, bodyEnd);
+ expect(bodyBlock).not.toContain('whitespace-pre-wrap');
+ expect(bodyBlock).not.toContain('truncate');
+ expect(pendingQueueSource).toContain(
+ "'relative top-px min-w-0 flex-1 truncate text-[13px] leading-[1.25]'",
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
index a3a71c0a3e..5139d32724 100644
--- a/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sentPastedTextPreview.test.ts
@@ -145,18 +145,19 @@ describe('UserMessage pasted-text chip wiring', () => {
// 那条路径上的粘贴段就又变回不可点。召唤卡 prompt 插槽已随「卡片即消息」
// 合并形态一并取消(chip 标注行改版):$指令 正文回归气泡,由普通正文
// 调用点统一渲染,不再有第三个调用点。
- expect(source.match(/handlePastedTextChipClick,/g)?.length).toBe(2);
+ // 计数包含 useCallback 定义本身 + 两个调用点。
+ expect(source.match(/handlePastedTextChipClick/g)?.length).toBe(3);
});
it('S1b 两个调用点都拿到同一份 sessionReferences(不再有 undefined 占位)', () => {
// 召唤卡 prompt 曾经漏传 sessionReferences(PR #966 review);该插槽现已
// 随合并形态取消,$指令 正文并入普通正文调用点。sessionReferences 按
// sessionId / messageClientId 匹配、不依赖文本偏移,两处理应拿同一份。
- // 调用点的末两个实参恒为 `sessionReferences, handlePastedTextChipClick`,
- // 一并锁住"都可点"与"都有引用元数据"。
- expect(
- source.match(/sessionReferences,\s*\n\s*handlePastedTextChipClick,/g)?.length,
- ).toBe(2);
+ // 展开态传 handler;收起态传 undefined,但两个调用点都保留同一份引用元数据。
+ expect(source).toMatch(
+ /sessionReferences,\s*\n\s*longMessageCollapsed \? undefined : handlePastedTextChipClick,/,
+ );
+ expect(source).toMatch(/sessionReferences,\s*\n\s*handlePastedTextChipClick,/);
});
it('S2 ToolPayloadLightbox 以只读 text 模式挂载', () => {
@@ -178,8 +179,11 @@ describe('UserMessage pasted-text chip wiring', () => {
);
// 测量镜像(独立 JSX 表达式)。
expect(source.match(/\{collapseMeasureBody\}/g)?.length).toBe(1);
- // 收起态正文(三元分支里,不是独立表达式)。
- expect(source).toMatch(/longMessageCollapsed\s*\n?\s*\?[\s\S]{0,400}collapseMeasureBody/);
+ // 收起态正文使用同一套静态 chip renderer,不再把投影纯文本直接塞进正文。
+ expect(source).toMatch(
+ /longMessageCollapsed\s*\n\s*\? renderContent\(\n\s*displayBubbleBody,/,
+ );
+ expect(source).toContain('bubbleAgentReferences,\n false,');
// 偏移只在 bubbleBody 与 ghostBody 同源时才折叠(引用交错的消息保持原文测量)。
expect(source).toContain('bubbleBody === ghostBody');
});
diff --git a/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx b/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx
index ea40c69f5e..8908540e13 100644
--- a/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx
@@ -1,12 +1,9 @@
-import {
- Globe2,
- Monitor,
- Plug,
-} from 'lucide-react';
+import { CornerDownRight, FolderOpen, Globe2, Monitor, Plug } from 'lucide-react';
import type { AgentInputReference } from '../../../shared/agentInputQueue';
import { InlineReferenceChip } from './InlineReferenceChip';
import { ProjectLinkChip } from './ProjectLinkChip';
+import { QuoteChip } from './QuoteChip';
import { SessionLinkChip } from './SessionLinkChip';
const MESSAGE_REFERENCE_LABEL_MAX = 240;
@@ -33,7 +30,46 @@ export function sentAgentReferenceDisplayLabel(reference: AgentInputReference):
}
/** Render one persisted Composer reference with the same visual shell as the input chip. */
-export function SentAgentReferenceChip({ reference }: { reference: AgentInputReference }) {
+export function SentAgentReferenceChip({
+ interactive = true,
+ reference,
+}: {
+ interactive?: boolean;
+ reference: AgentInputReference;
+}) {
+ if (!interactive) {
+ const label = sentAgentReferenceDisplayLabel(reference);
+ if (reference.kind === 'message') {
+ return (
+ <span className="relative top-[-1px] -my-[1px] inline-flex max-w-[min(240px,55vw)] align-middle">
+ <QuoteChip quote={{ text: label }} />
+ </span>
+ );
+ }
+ const icon =
+ reference.kind === 'session' ? (
+ <CornerDownRight aria-hidden />
+ ) : reference.kind === 'project' ? (
+ <FolderOpen aria-hidden />
+ ) : reference.kind === 'browser-tab' ? (
+ <Globe2 aria-hidden />
+ ) : reference.kind === 'desktop-window' ? (
+ <Monitor aria-hidden />
+ ) : (
+ <Plug aria-hidden />
+ );
+
+ return (
+ <InlineReferenceChip
+ ariaLabel={label}
+ className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
+ icon={icon}
+ label={label}
+ tooltip={label}
+ />
+ );
+ }
+
if (reference.kind === 'message') {
return (
<SessionLinkChip
@@ -55,11 +91,14 @@ export function SentAgentReferenceChip({ reference }: { reference: AgentInputRef
}
const label = sentAgentReferenceDisplayLabel(reference);
- const icon = reference.kind === 'browser-tab'
- ? <Globe2 aria-hidden />
- : reference.kind === 'desktop-window'
- ? <Monitor aria-hidden />
- : <Plug aria-hidden />;
+ const icon =
+ reference.kind === 'browser-tab' ? (
+ <Globe2 aria-hidden />
+ ) : reference.kind === 'desktop-window' ? (
+ <Monitor aria-hidden />
+ ) : (
+ <Plug aria-hidden />
+ );
return (
<InlineReferenceChip
diff --git a/apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx b/apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx
new file mode 100644
index 0000000000..81d39c83ad
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx
@@ -0,0 +1,100 @@
+/**
+ * Static projection of a sent message's structured inline atoms.
+ *
+ * Pending queue rows and clamped message bodies must keep the same chip
+ * geometry as the final message, but their chips cannot own navigation,
+ * lightbox, context-menu, or keyboard behaviour: the surrounding row or the
+ * expand control owns the interaction while clipped content may sit behind a
+ * line clamp.
+ */
+import { useTranslation } from 'react-i18next';
+
+import type { AgentInputReference } from '../../../shared/agentInputQueue';
+import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import { parseChatQuoteSegments, type ChatQuoteSegment } from '@/lib/chatQuotes';
+import { locateChatQuoteTextSegmentStarts, projectSentRanges, renderContent } from './UserMessage';
+import { QuoteChip } from './QuoteChip';
+
+export interface SentInlineAtomBodyProps {
+ content: string;
+ quotesEncoded?: boolean;
+ pastedTextRanges?: readonly PastedTextRange[];
+ slashCommandRanges?: readonly SlashCommandRange[];
+ agentReferences?: readonly AgentInputReference[];
+ workingDir?: string;
+ className?: string;
+}
+
+function visibleSegments(content: string, quotesEncoded: boolean): ChatQuoteSegment[] {
+ if (!content) return [];
+ if (!quotesEncoded) return [{ kind: 'text', text: content }];
+ const parsed = parseChatQuoteSegments(content);
+ return parsed.length > 0 ? parsed : [{ kind: 'text', text: content }];
+}
+
+export function SentInlineAtomBody({
+ agentReferences = [],
+ className,
+ content,
+ pastedTextRanges = [],
+ quotesEncoded = false,
+ slashCommandRanges,
+ workingDir = '',
+}: SentInlineAtomBodyProps) {
+ const { t } = useTranslation();
+ const segments = visibleSegments(content, quotesEncoded);
+ const segmentStarts = locateChatQuoteTextSegmentStarts(content, segments);
+
+ return (
+ <span className={className ?? 'inline-flex min-w-0 max-w-full items-center gap-1'}>
+ {segments.map((segment, index) => {
+ if (segment.kind === 'quote') {
+ return (
+ <span
+ className="mx-1 inline-flex max-w-[min(240px,55vw)] select-none align-middle"
+ key={`quote-${index}`}
+ >
+ <QuoteChip quote={segment.quote} />
+ </span>
+ );
+ }
+
+ const sourceStart = segmentStarts[index];
+ const localPastedRanges = projectSentRanges(
+ pastedTextRanges,
+ sourceStart,
+ segment.text.length,
+ );
+ const localSlashRanges =
+ slashCommandRanges === undefined
+ ? undefined
+ : projectSentRanges(slashCommandRanges, sourceStart, segment.text.length);
+ const localAgentReferences = projectSentRanges(
+ agentReferences,
+ sourceStart,
+ segment.text.length,
+ );
+
+ return (
+ <span className="min-w-0" key={`text-${index}`}>
+ {renderContent(
+ segment.text,
+ workingDir,
+ undefined,
+ undefined,
+ t,
+ undefined,
+ false,
+ localPastedRanges,
+ localSlashRanges,
+ undefined,
+ undefined,
+ localAgentReferences,
+ false,
+ )}
+ </span>
+ );
+ })}
+ </span>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 200cd3afa1..a1ae16a914 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -250,10 +250,13 @@ function UserFileChip({
function renderTextWithLinks(
text: string,
keyPrefix: string,
- onImageClick: (xdtFileUrl: string) => void,
+ onImageClick: ((xdtFileUrl: string) => void) | undefined,
sessionId?: string,
sessionReferences?: readonly PersistedSessionReferenceMetadata[],
+ interactive = true,
): React.ReactNode[] {
+ if (!interactive) return [text];
+
const result: React.ReactNode[] = [];
const matches = findLinkifyMatches(text);
let lastIndex = 0;
@@ -306,7 +309,7 @@ function renderTextWithLinks(
<button
key={`${keyPrefix}-img-${match.index}`}
type="button"
- onClick={() => onImageClick(toLocalFileUrl(p))}
+ onClick={() => onImageClick?.(toLocalFileUrl(p))}
// 同 UserMessageUrlLink:可点 = 正文色 + 常显下划线,不再靠 --msg-link 颜色。
className="underline underline-offset-2 cursor-pointer break-all"
>
@@ -382,14 +385,16 @@ function looksLikeCommand(word: string): boolean {
function renderContentWithoutPastedText(
content: string,
workingDir: string,
- onFileChipClick: (abs: string, name: string, chip: HTMLElement) => void | Promise<void>,
- onImageClick: (xdtFileUrl: string) => void,
+ onFileChipClick:
+ ((abs: string, name: string, chip: HTMLElement) => void | Promise<void>) | undefined,
+ onImageClick: ((xdtFileUrl: string) => void) | undefined,
t: TFunction,
sessionId?: string,
/** remote 会话:@-chip 点击跳过本机 smart resolve,按 workdir 风格直接 join。 */
remoteJoin = false,
renderLegacySlashCommands = true,
sessionReferences?: readonly PersistedSessionReferenceMetadata[],
+ interactive = true,
): React.ReactNode[] {
const nodes: React.ReactNode[] = [];
const lines = content.split('\n');
@@ -426,14 +431,14 @@ function renderContentWithoutPastedText(
// A real mention is always preceded by whitespace or sits at line start.
const prev = parts[pi - 1];
if (prev && prev.length > 0 && !/\s$/.test(prev)) {
- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences));
+ nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));
continue;
}
// Only render as chip if it looks like a real path
if (!looksLikePath(ref)) {
// Not a path — render as plain text
- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences));
+ nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));
continue;
}
@@ -469,42 +474,54 @@ function renderContentWithoutPastedText(
const fileName = ref.split(/[\\/]/).pop() || ref;
// v7: 右键菜单(复制 / 复制文件路径 / 打开文件所在目录) 由 UserFileChip 提供。
nodes.push(
- <UserFileChip
- key={key}
- refText={ref}
- fileName={fileName}
- workingDir={workingDir}
- onClick={async (e) => {
- // Capture currentTarget before the await: `currentTarget` is only
- // set while the DOM event is being dispatched, so it reads back as
- // null once the IPC resolves. (Not React event pooling — that was
- // removed in React 17; this is plain DOM Event semantics.) The
- // element is needed later to restore focus when the lightbox closes.
- const chip = e.currentTarget;
- if (remoteJoin) {
- // remote:本机 BFS 无意义,join 出远端绝对路径,存在性由
- // 点击后的远程取回链路兜底。
- await onFileChipClick(resolveLocalPath(ref, workingDir), fileName, chip);
- return;
- }
- // markdown-monorepo-resolve: smart resolve so a chip like
- // `@src/App.tsx` resolves to the right sub-package even
- // though session.workingDir points at the workspace root.
- const result = await resolveLocalPathSmart(ref, workingDir);
- if (result.status === 'multiple') {
- toast.error(
- t('chat.markdownRenderer.duplicateFiles', { count: result.candidates.length }),
- );
- return;
- }
- const abs = result.status === 'unique' ? result.absPath : result.fallbackAbsPath;
- await onFileChipClick(abs, fileName, chip);
- }}
- />,
+ interactive && onFileChipClick ? (
+ <UserFileChip
+ key={key}
+ refText={ref}
+ fileName={fileName}
+ workingDir={workingDir}
+ onClick={async (e) => {
+ // Capture currentTarget before the await: `currentTarget` is only
+ // set while the DOM event is being dispatched, so it reads back as
+ // null once the IPC resolves. (Not React event pooling — that was
+ // removed in React 17; this is plain DOM Event semantics.) The
+ // element is needed later to restore focus when the lightbox closes.
+ const chip = e.currentTarget;
+ if (remoteJoin) {
+ // remote:本机 BFS 无意义,join 出远端绝对路径,存在性由
+ // 点击后的远程取回链路兜底。
+ await onFileChipClick(resolveLocalPath(ref, workingDir), fileName, chip);
+ return;
+ }
+ // markdown-monorepo-resolve: smart resolve so a chip like
+ // `@src/App.tsx` resolves to the right sub-package even
+ // though session.workingDir points at the workspace root.
+ const result = await resolveLocalPathSmart(ref, workingDir);
+ if (result.status === 'multiple') {
+ toast.error(
+ t('chat.markdownRenderer.duplicateFiles', { count: result.candidates.length }),
+ );
+ return;
+ }
+ const abs = result.status === 'unique' ? result.absPath : result.fallbackAbsPath;
+ await onFileChipClick(abs, fileName, chip);
+ }}
+ />
+ ) : (
+ <InlineReferenceChip
+ key={key}
+ label={fileName}
+ icon={<FileIcon aria-hidden />}
+ tooltip={ref}
+ tooltipMono
+ ariaLabel={fileName}
+ className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
+ />
+ ),
);
}
} else {
- nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences));
+ nodes.push(...renderTextWithLinks(part, `${li}-${pi}`, onImageClick, sessionId, sessionReferences, interactive));
}
}
}
@@ -586,12 +603,12 @@ export function buildSentInlineTokens(
}
/**
- * 收起态渲染与镜像测量共用的纯文本投影:粘贴段折叠成它自己的胶囊文案。
+ * 收起判定与镜像测量共用的纯文本投影:粘贴段折叠成它自己的胶囊文案。
*
* 展开态里粘贴段是一个胶囊(点击看全文),收起态却按原文纯文本裁剪 —— 用户看到的
- * 是"收起还能看到日志前 10 行、展开只剩一个胶囊"的反向落差(issue #946)。两侧共用
- * 同一份投影后,收起与展开只差一个 line-clamp,内容形状一致;测量也不再被折叠掉的
- * 几百行原文顶穿阈值,「只粘一段」的消息直接以胶囊呈现,不再多套一层收起。
+ * 是"收起还能看到日志前 10 行、展开只剩一个胶囊"的反向落差(issue #946)。测量
+ * 使用同一份投影避免被折叠掉的几百行原文顶穿阈值;实际收起态则复用静态 chip
+ * renderer,保证它与展开态的内容形状一致。
*
* 只在 range 偏移确定精确时调用(见 UserMessage 的 collapseMeasureBody):
* buildSentInlineTokens 本身会丢弃越界 / 逆序的 range,偏移不准最坏退化成"不折叠",
@@ -662,11 +679,12 @@ export function projectSentRanges<T extends { start: number; end: number }>(
}
/** Replace persisted presentation ranges with read-only sent chips. */
-function renderContent(
+export function renderContent(
content: string,
workingDir: string,
- onFileChipClick: (abs: string, name: string, chip: HTMLElement) => void | Promise<void>,
- onImageClick: (xdtFileUrl: string) => void,
+ onFileChipClick:
+ ((abs: string, name: string, chip: HTMLElement) => void | Promise<void>) | undefined,
+ onImageClick: ((xdtFileUrl: string) => void) | undefined,
t: TFunction,
sessionId?: string,
remoteJoin = false,
@@ -679,6 +697,7 @@ function renderContent(
*/
onPastedTextChipClick?: (text: string, chip: HTMLElement) => void,
agentReferences: readonly AgentInputReference[] = [],
+ interactive = true,
): React.ReactNode[] {
const tokens = buildSentInlineTokens(
content,
@@ -712,7 +731,7 @@ function renderContent(
// 点击打开只读全文(与 composer 侧 pastedTextChip → ToolPayloadLightbox
// 对齐)。hover tooltip 是 320×256 的小浮层,几百行日志在里面读不了,
// 也无法选中复制,不能当作查看全文的唯一出口(issue #946)。
- {...(onPastedTextChipClick
+ {...(interactive && onPastedTextChipClick
? {
onClick: (event) =>
onPastedTextChipClick(token.text, event.currentTarget),
@@ -725,6 +744,7 @@ function renderContent(
return (
<SentAgentReferenceChip
key={`agent-reference-chip-${index}`}
+ interactive={interactive}
reference={token.reference}
/>
);
@@ -741,6 +761,7 @@ function renderContent(
remoteJoin,
useLegacySlashHeuristic,
sessionReferences,
+ interactive,
)}
</span>
);
@@ -938,8 +959,9 @@ export function UserMessage({
projectSentRanges(validAgentReferences, displayBubbleSourceStart, displayBubbleBody.length),
[displayBubbleBody.length, displayBubbleSourceStart, validAgentReferences],
);
- // 测量与收起态渲染共用的投影正文:粘贴段按胶囊文案计量,不再拿被折叠掉的
- // 几百行原文去撞收起阈值(issue #946)。偏移只在 bubbleBody 与 ghostBody 同源
+ // 收起判定与测量镜像共用的投影正文:粘贴段按胶囊文案计量,不再拿被折叠掉的
+ // 几百行原文去撞收起阈值(issue #946)。实际正文由同一套结构化 renderer 渲染,
+ // 偏移只在 bubbleBody 与 ghostBody 同源
// (无引用交错)时精确 —— quote 块被 join 掉的消息偏移会整体前移,保持原文
// 测量;硬指令剥 $token 不影响精确性(displayBubbleSourceStart 已重定位)。
const collapseMeasureBody = useMemo(
@@ -1416,30 +1438,12 @@ export function UserMessage({
// biome-ignore lint/suspicious/noArrayIndexKey: 已发送消息内容不可变,顺序稳定。
key={index}
>
- {longMessageCollapsed
- ? projectSentInlinePlainText(
- segment.text,
- projectSentRanges(
- pastedTextRanges ?? [],
- quoteTextSegmentStarts[index] === null ||
- ghostBodySourceStart === null
- ? null
- : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
- segment.text.length,
- ),
- projectSentRanges(
- validAgentReferences,
- quoteTextSegmentStarts[index] === null ||
- ghostBodySourceStart === null
- ? null
- : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
- segment.text.length,
- ),
- )
- : renderContent(
- segment.text,
- workingDir,
- async (abs, name, chip) => {
+ {renderContent(
+ segment.text,
+ workingDir,
+ longMessageCollapsed
+ ? undefined
+ : async (abs, name, chip) => {
if (
!(await shouldOpenTextLightboxForOrigin(
sessionFileCtx,
@@ -1450,39 +1454,42 @@ export function UserMessage({
activeFileChipRef.current = chip;
setTextLightboxFile({ path: abs, name });
},
- (xdtFileUrl) => setLightboxSrc(xdtFileUrl),
- t,
- sessionId,
- isRemoteFileOrigin(sessionFileCtx.origin),
- projectSentRanges(
- pastedTextRanges ?? [],
- quoteTextSegmentStarts[index] === null ||
- ghostBodySourceStart === null
- ? null
- : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
- segment.text.length,
- ),
- slashCommandRanges === undefined
- ? undefined
- : projectSentRanges(
- slashCommandRanges,
- quoteTextSegmentStarts[index] === null ||
- ghostBodySourceStart === null
- ? null
- : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
- segment.text.length,
- ),
- sessionReferences,
- handlePastedTextChipClick,
- projectSentRanges(
- validAgentReferences,
+ longMessageCollapsed
+ ? undefined
+ : (xdtFileUrl) => setLightboxSrc(xdtFileUrl),
+ t,
+ sessionId,
+ isRemoteFileOrigin(sessionFileCtx.origin),
+ projectSentRanges(
+ pastedTextRanges ?? [],
+ quoteTextSegmentStarts[index] === null ||
+ ghostBodySourceStart === null
+ ? null
+ : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
+ segment.text.length,
+ ),
+ slashCommandRanges === undefined
+ ? undefined
+ : projectSentRanges(
+ slashCommandRanges,
quoteTextSegmentStarts[index] === null ||
ghostBodySourceStart === null
? null
: ghostBodySourceStart + quoteTextSegmentStarts[index]!,
segment.text.length,
),
- )}
+ sessionReferences,
+ longMessageCollapsed ? undefined : handlePastedTextChipClick,
+ projectSentRanges(
+ validAgentReferences,
+ quoteTextSegmentStarts[index] === null ||
+ ghostBodySourceStart === null
+ ? null
+ : ghostBodySourceStart + quoteTextSegmentStarts[index]!,
+ segment.text.length,
+ ),
+ !longMessageCollapsed,
+ )}
</span>
),
)}
@@ -1495,12 +1502,27 @@ export function UserMessage({
)}
>
{longMessageCollapsed
- ? // 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.
- // 粘贴段用胶囊文案(而非原文)投影:与展开态同形状,
- // 且与上方测量镜像同一份文本(issue #946)。
- collapseMeasureBody
+ ? renderContent(
+ displayBubbleBody,
+ workingDir,
+ undefined,
+ undefined,
+ t,
+ sessionId,
+ isRemoteFileOrigin(sessionFileCtx.origin),
+ bubblePastedRanges,
+ slashCommandRanges === undefined
+ ? undefined
+ : projectSentRanges(
+ slashCommandRanges,
+ displayBubbleSourceStart,
+ displayBubbleBody.length,
+ ),
+ sessionReferences,
+ undefined,
+ bubbleAgentReferences,
+ false,
+ )
: renderContent(
displayBubbleBody,
workingDir,
diff --git a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
index 12a3f18b31..aa75a65e7e 100644
--- a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
@@ -37,6 +37,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SortableList } from '@/components/sidebar/SortableList';
+import { SentInlineAtomBody } from '@/components/chat/SentInlineAtomBody';
import { ListComposerTextarea } from './ListComposerTextarea';
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
@@ -321,6 +322,18 @@ export function PendingQueuePanel({
const showActions = isRowActive || isSteering || isRowEditing;
const canSteerRow = Boolean(onSteer) && rowPresentation.canSteer;
const canEditRow = Boolean(onEdit) && rowPresentation.canEdit;
+ const chatMessageContent = entry.chatMessage.content ?? entry.text;
+ const agentReferences =
+ entry.chatMessage.agentReferences?.length
+ ? entry.chatMessage.agentReferences
+ : (entry.agentReferences ?? []);
+ const hasStructuredAtoms =
+ !rowPresentation.isSyntheticTrigger &&
+ (entry.chatMessage.quotesEncoded === true ||
+ (entry.chatMessage.pastedTextRanges?.length ?? 0) > 0 ||
+ (entry.chatMessage.slashCommandRanges?.length ?? 0) > 0 ||
+ agentReferences.length > 0 ||
+ (entry.mentions?.length ?? 0) > 0);
const actionSlotWidth = canSteerRow
? (canEditRow ? 'w-[68px]' : 'w-[44px]')
: (canEditRow ? 'w-[44px]' : 'w-5');
@@ -330,6 +343,25 @@ export function PendingQueuePanel({
const base = t(turnRunning ? 'newChat.pendingQueue.steerRunningTip' : 'newChat.pendingQueue.steerPausedTip');
return steerShortcutLabel ? `${base} · ${steerShortcutLabel}` : base;
})();
+ // The surrounding <p> owns the queue row's single-line nowrap +
+ // ellipsis contract. Do not override white-space in the structured
+ // body or multiline text islands can expand the row.
+ const pendingRowContent = rowPresentation.isSyntheticTrigger
+ ? t(rowPresentation.syntheticKind === 'continue'
+ ? 'newChat.pendingQueue.syntheticContinueLabel'
+ : 'newChat.pendingQueue.syntheticTriggerLabel')
+ : hasStructuredAtoms ? (
+ <SentInlineAtomBody
+ agentReferences={agentReferences}
+ className="relative top-px inline-flex min-w-0 max-w-full items-center gap-1 text-[13px] leading-[1.25]"
+ content={chatMessageContent}
+ pastedTextRanges={entry.chatMessage.pastedTextRanges}
+ quotesEncoded={entry.chatMessage.quotesEncoded}
+ slashCommandRanges={entry.chatMessage.slashCommandRanges}
+ workingDir={entry.createOpts.workingDir}
+ />
+ )
+ : rowPresentation.displayText || t('newChat.pendingQueue.noTextContent');
const handleRowKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
if (!isPendingQueueSteerShortcut(e)) return;
if (!canSteerRow || !onSteer || isSteering || isRowEditing) return;
@@ -501,7 +533,7 @@ export function PendingQueuePanel({
? t(rowPresentation.syntheticKind === 'continue'
? 'newChat.pendingQueue.syntheticContinueLabel'
: 'newChat.pendingQueue.syntheticTriggerLabel')
- : (rowPresentation.displayText || t('newChat.pendingQueue.noTextContent'))}
+ : rowPresentation.displayText || t('newChat.pendingQueue.noTextContent')}
</span>
</div>
) : (
@@ -514,11 +546,7 @@ export function PendingQueuePanel({
: 'text-[var(--settings-section-desc)]',
)}
>
- {rowPresentation.isSyntheticTrigger
- ? t(rowPresentation.syntheticKind === 'continue'
- ? 'newChat.pendingQueue.syntheticContinueLabel'
- : 'newChat.pendingQueue.syntheticTriggerLabel')
- : (rowPresentation.displayText || t('newChat.pendingQueue.noTextContent'))}
+ {pendingRowContent}
</p>
)}
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 62635c8815..e7be2af657 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -451,6 +451,7 @@ export function updateQueuedMessageText(
};
if (!hasEncodedQuoteMarker) delete nextChatMessage.quotesEncoded;
delete nextChatMessage.pastedTextRanges;
+ delete nextChatMessage.agentReferences;
nextChatMessage.slashCommandRanges = [];
const updated: AgentInputQueuedMessage = {
...entry,
diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.ts
index 56af9b5793..b31c4171f2 100644
--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts
+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts
@@ -7,6 +7,7 @@
* 已回流的 clientId 立刻不再产出气泡(避免同一句话双显)。
*/
import { describe, expect, it } from 'vitest';
+import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';
import {
buildPendingSendItems,
pendingSendItemKey,
@@ -143,6 +144,45 @@ describe('buildPendingSendItems', () => {
expect(settling.actions).toBeNull();
expect(settling.queueIndex).toBeNull();
});
+
+ it('keeps queue atom metadata for the optimistic chip renderer', () => {
+ const quote = formatQuoteForSend({ text: 'quoted context' });
+ const text = `${quote}\n\n/help\n\nfull pasted payload`;
+ const slashStart = text.indexOf('/help');
+ const pastedStart = text.indexOf('full pasted payload');
+ const queuedItem = queued('atoms', text);
+ queuedItem.chatMessage.quotesEncoded = true;
+ queuedItem.chatMessage.slashCommandRanges = [{ start: slashStart, end: slashStart + 5 }];
+ queuedItem.chatMessage.pastedTextRanges = [{
+ start: pastedStart,
+ end: text.length,
+ display: 'Pasted text (1 line)',
+ }];
+
+ const [item] = build({ queue: [queuedItem] });
+ expect(item.sentInlineTokens.map((token) => token.kind)).toEqual([
+ 'quote',
+ 'slash',
+ 'text',
+ 'pasted',
+ ]);
+ });
+
+ it('keeps outbox atom metadata while attachments are still uploading', () => {
+ const text = '/help full pasted payload';
+ const outbox = outboxItem('outbox-atoms', {
+ text,
+ quotesEncoded: false,
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ pastedTextRanges: [{ start: 6, end: text.length, display: 'Pasted text (1 line)' }],
+ attachmentCount: 1,
+ uploadedCount: 0,
+ });
+
+ const [item] = build({ outbox: [outbox] });
+ expect(item.phase).toBe('uploading');
+ expect(item.sentInlineTokens.map((token) => token.kind)).toEqual(['slash', 'text', 'pasted']);
+ });
});
describe('pending_send 渲染接线', () => {
@@ -163,6 +203,13 @@ describe('pending_send 渲染接线', () => {
// 渲染分支存在,且 items 的联合类型里有这一支。
expect(source).toContain("case 'pending_send':");
expect(source).toContain('actions={actions.pendingSend}');
+ const bubbleSource = readFileSync(
+ resolvePath(process.cwd(), 'src/session/PendingSendBubble.tsx'),
+ 'utf8',
+ );
+ expect(bubbleSource).toContain('<SentInlineAtomBody');
+ expect(bubbleSource).toContain('interactiveAtoms={false}');
+ expect(bubbleSource).toContain('maxVisibleLines={selected ? undefined : 6}');
// 粘贴时已上传到媒体总仓的图(cindy-media://blobs/…)本地没有文件,气泡要靠远端取件
// 才有缩略图 —— 漏传 resolver 就只能画空占位格。
expect(source).toContain('resolveRemoteMedia={actions.onResolveRemoteMedia}');
diff --git a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
index d4b7131d15..882f26ece3 100644
--- a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
+++ b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
@@ -10,18 +10,32 @@ import {
describe('sent message atoms', () => {
it('keeps atom chips while rendering ordinary chunks with full Markdown semantics', () => {
+ const atomSource = readFileSync(resolve(process.cwd(), 'src/session/SentInlineAtomBody.tsx'), 'utf8');
+ const rendererSource = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
+
+ expect(atomSource).toContain('<InlineQuoteChip');
+ expect(atomSource).toContain('<InlineReferenceChip');
+ expect(atomSource).toContain('renderText(token.text, index)');
+ expect(atomSource).toContain('selectable={selectable}');
+ expect(rendererSource).toContain('<MarkdownBody');
+ expect(rendererSource).toContain('text={text}');
+ expect(atomSource).not.toContain('splitAnchoredSessionMessageLinks');
+ expect(atomSource).not.toContain('<SentMessageAnchorChip');
+ expect(atomSource).not.toContain('parseMobileMarkdownInlines(part.text)');
+ });
+
+ it('keeps atomized long messages structured while collapsed', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
- const bodyStart = source.indexOf('function SentInlineAtomBody');
- const bodyEnd = source.indexOf('function MarkdownBody', bodyStart);
- const bodySource = source.slice(bodyStart, bodyEnd);
+ const collapseStart = source.indexOf('const collapseMeasureEnabled =');
+ const collapseEnd = source.indexOf(';', collapseStart);
- expect(bodySource).toContain('<InlineQuoteChip');
- expect(bodySource).toContain('<InlineReferenceChip');
- expect(bodySource).toContain('<MarkdownBody');
- expect(bodySource).toContain('text={token.text}');
- expect(bodySource).not.toContain('splitAnchoredSessionMessageLinks');
- expect(bodySource).not.toContain('<SentMessageAnchorChip');
- expect(bodySource).not.toContain('parseMobileMarkdownInlines(part.text)');
+ expect(collapseStart).toBeGreaterThan(-1);
+ expect(collapseEnd).toBeGreaterThan(collapseStart);
+ expect(source.slice(collapseStart, collapseEnd)).not.toContain('!rendersSentInlineBody');
+ expect(source).toContain('maxVisibleLines={collapsedLineCount}');
+ expect(source).toContain('testID="message.collapsedSentInlineAtoms"');
+ expect(source).toContain('selectable={canSelectVisibleText}');
+ expect(source).toContain('interactiveAtoms={false}');
});
it('splits exact pasted-text and slash ranges without guessing', () => {
diff --git a/apps/mobile/src/session/InlineQuoteChip.tsx b/apps/mobile/src/session/InlineQuoteChip.tsx
index df89b39084..edf4cd32c9 100644
--- a/apps/mobile/src/session/InlineQuoteChip.tsx
+++ b/apps/mobile/src/session/InlineQuoteChip.tsx
@@ -9,7 +9,13 @@ export function compactQuoteLabel(text: string): string {
}
/** One quote per chip, shared geometry with message-anchor references. */
-export function InlineQuoteChip({ quote }: { quote: ChatQuote }) {
+export function InlineQuoteChip({
+ interactive = true,
+ quote,
+}: {
+ interactive?: boolean;
+ quote: ChatQuote;
+}) {
const { colors } = useTheme();
const source = quoteSourceDisplayLabel(quote);
const label = compactQuoteLabel(quote.text);
@@ -18,7 +24,9 @@ export function InlineQuoteChip({ quote }: { quote: ChatQuote }) {
accessibilityLabel={quote.text}
icon={<MessageSquareQuote color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />}
label={label}
- onPress={() => Alert.alert('引用', [`“${quote.text}”`, source].filter(Boolean).join('\n\n'))}
+ onPress={interactive
+ ? () => Alert.alert('引用', [`“${quote.text}”`, source].filter(Boolean).join('\n\n'))
+ : undefined}
testID="message.quoteChip"
/>
);
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b91fa7bd67..8d76e7aa88 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -16,7 +16,6 @@ import {
Ellipsis,
ExternalLink,
File as FileIcon,
- FileText,
Layers,
ListTodo,
LoaderCircle,
@@ -72,8 +71,7 @@ import { motionDuration, motionEasing } from '@/theme/tokens';
import { mobileAgentLabelFromUnknown } from '@/session/sessionAgentSwitch';
import { MessageActionSheet } from '@/session/MessageActionSheet';
import { buildMobileMessageMenu, type MobileMessageMenuActionId } from '@/session/messageActionMenu';
-import { InlineQuoteChip } from '@/session/InlineQuoteChip';
-import { InlineReferenceChip } from '@/session/InlineReferenceChip';
+import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';
import {
composerDocumentFromSerializedMessage,
type ComposerDocument,
@@ -106,7 +104,6 @@ import {
buildFilePayload,
buildMediaPayload,
buildMermaidPayload,
- buildTextPayload,
buildToolResultPayload,
formatDiffPayloadView,
payloadMediaKindLabel,
@@ -1741,6 +1738,9 @@ function MessageBubble({
// hook 来源消息在 RenderItemView 中会降级为左对齐 system kind,避免暴露
// 本地 user 消息的 fork / rewind / delete 操作;它仍可能携带至多 20k 文本,
// 因此必须继续复用长消息的有界测量与折叠保护。
+ // 引用 / 粘贴文本 / Slash 等结构化 atom 的 displayBubbleBody 已是紧凑投影,
+ // 因此可继续参与同一套长消息判定;真正收起时改用静态结构化 renderer + 整体
+ // 高度裁切,既不把完整 payload 摊开,也不会因含 chip 而永久失去长消息保护。
const collapseMeasureEnabled = (isUser || hookSource !== undefined)
&& (item.message.kind === 'user' || hookSource !== undefined)
&& !item.message.systemCardType
@@ -1940,26 +1940,46 @@ function MessageBubble({
/>
) : displayBubbleBody ? (
longMessageCollapsed ? (
- // 收起态降级为纯文本(对齐桌面:被裁切的富文本节点不该保留交互),
- // 展开后恢复 MarkdownBody 的完整渲染。文本选择不因收起而丢失:
- // 走与正文/secondaryBody 同款的 MarkdownSelectableText(iOS 用
- // UITextView,原生支持 numberOfLines 截断,长按有系统选择手柄)。
- <MarkdownSelectableText
- numberOfLines={collapsedLineCount}
- selectable={canSelectVisibleText}
- style={styles.messageText}
- testID="message.collapsedBody"
- >
- {displayBubbleBody}
- </MarkdownSelectableText>
+ rendersSentInlineBody ? (
+ <SentInlineAtomBody
+ interactiveAtoms={false}
+ maxVisibleLines={collapsedLineCount}
+ numberOfLines={collapsedLineCount}
+ selectable={canSelectVisibleText}
+ testID="message.collapsedSentInlineAtoms"
+ textStyle={styles.messageText}
+ tokens={sentInlineTokens}
+ />
+ ) : (
+ // 普通长消息收起态降级为纯文本(对齐桌面:被裁切的富文本节点不该
+ // 保留交互),展开后恢复 MarkdownBody。文本选择走与正文同款的
+ // MarkdownSelectableText(iOS UITextView 原生支持 numberOfLines)。
+ <MarkdownSelectableText
+ numberOfLines={collapsedLineCount}
+ selectable={canSelectVisibleText}
+ style={styles.messageText}
+ testID="message.collapsedBody"
+ >
+ {displayBubbleBody}
+ </MarkdownSelectableText>
+ )
) : rendersSentInlineBody ? (
<SentInlineAtomBody
- layout={contentLayout}
- markdownImageCacheKey={item.message.key}
onOpenPayload={actions.onOpenPayload}
- onOpenSessionLink={actions.onOpenSessionLink}
- selectable={canSelectVisibleText}
- sessionReferences={item.message.sessionReferences}
+ renderText={(text, index) => (
+ <View key={`text:${index}`} style={styles.sentInlineTextChunk}>
+ <MarkdownBody
+ layout={contentLayout}
+ markdownImageCacheKey={item.message.key}
+ onOpenPayload={actions.onOpenPayload}
+ onOpenSessionLink={actions.onOpenSessionLink}
+ selectable={canSelectVisibleText}
+ sessionReferences={item.message.sessionReferences}
+ streaming={false}
+ text={text}
+ />
+ </View>
+ )}
tokens={sentInlineTokens}
/>
) : (
@@ -3259,80 +3279,6 @@ function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; scre
// 消息正文统一走原生 markdown 渲染(流式与完成态同一条路径,完成时无"原生→WebView"的切换跳变)。
// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,
// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。
-/** Sent user atoms stay compact while their full wire text remains copyable/sendable. */
-function SentInlineAtomBody({
- layout,
- markdownImageCacheKey,
- onOpenPayload,
- onOpenSessionLink,
- selectable,
- sessionReferences,
- tokens,
-}: {
- layout: MessageContentLayout;
- markdownImageCacheKey?: string;
- onOpenPayload?: (payload: MessagePayload) => void;
- onOpenSessionLink?: (url: string) => void;
- selectable: boolean;
- sessionReferences?: readonly MobilePersistedSessionReferenceMetadata[];
- tokens: readonly SentInlineToken[];
-}) {
- const { colors } = useTheme();
- const styles = useThemedStyles(makeStyles);
- return (
- <View style={styles.sentInlineAtomBody} testID="message.sentInlineAtoms">
- {tokens.map((token, index) => {
- if (token.kind === 'quote') {
- return (
- <InlineQuoteChip
- key={`quote:${token.quote.sourcePath ?? 'chat'}:${index}:${token.quote.text}`}
- quote={token.quote}
- />
- );
- }
- if (token.kind === 'pasted') {
- return (
- <InlineReferenceChip
- accessibilityLabel={token.display}
- icon={<FileText color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />}
- key={`pasted:${index}`}
- label={token.display}
- onPress={onOpenPayload
- ? () => onOpenPayload(buildTextPayload('Pasted text', token.text))
- : undefined}
- testID="message.pastedTextChip"
- />
- );
- }
- if (token.kind === 'slash') {
- return (
- <InlineReferenceChip
- accessibilityLabel={token.text}
- key={`slash:${index}`}
- label={token.text}
- testID="message.slashCommandChip"
- />
- );
- }
- return token.text ? (
- <View key={`text:${index}`} style={styles.sentInlineTextChunk}>
- <MarkdownBody
- layout={layout}
- markdownImageCacheKey={markdownImageCacheKey}
- onOpenPayload={onOpenPayload}
- onOpenSessionLink={onOpenSessionLink}
- selectable={selectable}
- sessionReferences={sessionReferences}
- streaming={false}
- text={token.text}
- />
- </View>
- ) : null;
- })}
- </View>
- );
-}
-
function MarkdownBody({
allowIosUITextView = true,
markdownImageCacheKey,
@@ -5953,13 +5899,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
gap: 2,
width: '100%',
},
- sentInlineAtomBody: {
- alignItems: 'center',
- flexDirection: 'row',
- flexWrap: 'wrap',
- gap: spacing.xs,
- maxWidth: '100%',
- },
sentInlineTextChunk: {
flexBasis: '100%',
flexShrink: 1,
diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsx
index 392e490e89..9683ce29b2 100644
--- a/apps/mobile/src/session/PendingSendBubble.tsx
+++ b/apps/mobile/src/session/PendingSendBubble.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
import { Image } from 'expo-image';
import { Text } from '@/components/AppText';
+import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';
import {
AlertCircle,
ArrowUp,
@@ -193,6 +194,7 @@ export function PendingSendBubble({
const selected = interactive && actions.selectedClientId === item.clientId;
const bubbleLabel = item.text || t('message.queue.attachmentMessage');
const uploadsPending = item.phase === 'uploading';
+ const rendersSentInlineBody = item.sentInlineTokens.some((token) => token.kind !== 'text');
return (
<View style={styles.rowWrap} testID={`pendingSend.row.${item.clientId}`}>
@@ -231,7 +233,16 @@ export function PendingSendBubble({
]}
testID={`pendingSend.bubble.${item.clientId}`}
>
- {item.text ? (
+ {rendersSentInlineBody ? (
+ <SentInlineAtomBody
+ interactiveAtoms={false}
+ maxVisibleLines={selected ? undefined : 6}
+ numberOfLines={selected ? undefined : 6}
+ testID="pendingSend.sentInlineAtoms"
+ textStyle={styles.bubbleText}
+ tokens={item.sentInlineTokens}
+ />
+ ) : item.text ? (
<Text numberOfLines={selected ? undefined : 6} style={styles.bubbleText}>
{item.text}
</Text>
diff --git a/apps/mobile/src/session/SentInlineAtomBody.tsx b/apps/mobile/src/session/SentInlineAtomBody.tsx
new file mode 100644
index 0000000000..8926855544
--- /dev/null
+++ b/apps/mobile/src/session/SentInlineAtomBody.tsx
@@ -0,0 +1,147 @@
+import type { ReactNode } from "react";
+import {
+ StyleSheet,
+ View,
+ type StyleProp,
+ type TextStyle,
+ type ViewStyle,
+} from "react-native";
+import { FileText } from "lucide-react-native";
+import { Text } from "@/components/AppText";
+import { InlineQuoteChip } from "@/session/InlineQuoteChip";
+import { InlineReferenceChip } from "@/session/InlineReferenceChip";
+import {
+ buildTextPayload,
+ type MessagePayload,
+} from "@/session/messagePayload";
+import type { SentInlineToken } from "@/session/sentMessageAtoms";
+import {
+ iconSize,
+ iconStroke,
+ lineHeight,
+ spacing,
+ useTheme,
+ useThemedStyles,
+ type ThemeColors,
+} from "@/theme";
+
+/**
+ * Shared rendering shell for the structured atoms embedded in a sent message.
+ *
+ * The completed-message renderer supplies a Markdown text renderer, while the
+ * optimistic pending bubble supplies a lightweight plain-text renderer. Keeping
+ * the atom/chip decisions here means the first optimistic frame and the
+ * authoritative message use the same quote, pasted-text, and slash shapes.
+ */
+export function SentInlineAtomBody({
+ interactiveAtoms = true,
+ maxVisibleLines,
+ numberOfLines,
+ onOpenPayload,
+ renderText,
+ selectable,
+ textStyle,
+ testID = "message.sentInlineAtoms",
+ tokens,
+}: {
+ interactiveAtoms?: boolean;
+ maxVisibleLines?: number;
+ numberOfLines?: number;
+ onOpenPayload?: (payload: MessagePayload) => void;
+ renderText?: (text: string, index: number) => ReactNode;
+ selectable?: boolean;
+ textStyle?: StyleProp<TextStyle>;
+ testID?: string;
+ tokens: readonly SentInlineToken[];
+}) {
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const clampStyle: StyleProp<ViewStyle> = maxVisibleLines === undefined
+ ? undefined
+ : {
+ maxHeight:
+ maxVisibleLines * lineHeight.bodyLarge
+ + Math.max(0, maxVisibleLines - 1) * spacing.xs,
+ overflow: "hidden",
+ };
+ return (
+ <View style={[styles.body, clampStyle]} testID={testID}>
+ {tokens.map((token, index) => {
+ if (token.kind === "quote") {
+ return (
+ <InlineQuoteChip
+ interactive={interactiveAtoms}
+ key={`quote:${token.quote.sourcePath ?? "chat"}:${index}:${token.quote.text}`}
+ quote={token.quote}
+ />
+ );
+ }
+ if (token.kind === "pasted") {
+ return (
+ <InlineReferenceChip
+ accessibilityLabel={token.display}
+ icon={
+ <FileText
+ color={colors.textSecondary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ }
+ key={`pasted:${index}`}
+ label={token.display}
+ onPress={
+ interactiveAtoms && onOpenPayload
+ ? () =>
+ onOpenPayload(buildTextPayload("Pasted text", token.text))
+ : undefined
+ }
+ testID="message.pastedTextChip"
+ />
+ );
+ }
+ if (token.kind === "slash") {
+ return (
+ <InlineReferenceChip
+ accessibilityLabel={token.text}
+ key={`slash:${index}`}
+ label={token.text}
+ testID="message.slashCommandChip"
+ />
+ );
+ }
+ if (!token.text) return null;
+ if (renderText) return renderText(token.text, index);
+ return (
+ <View key={`text:${index}`} style={styles.textChunk}>
+ <Text
+ numberOfLines={numberOfLines}
+ selectable={selectable}
+ style={[styles.defaultText, textStyle]}
+ >
+ {token.text}
+ </Text>
+ </View>
+ );
+ })}
+ </View>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) =>
+ StyleSheet.create({
+ body: {
+ alignItems: "center",
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: spacing.xs,
+ maxWidth: "100%",
+ },
+ textChunk: {
+ flexBasis: "100%",
+ flexShrink: 1,
+ maxWidth: "100%",
+ },
+ defaultText: {
+ color: colors.textPrimary,
+ },
+ });
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index 9e16fd8219..a28a0b0f2c 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -16,9 +16,16 @@
* —— outbox 是最晚发出的。
*/
import { syntheticTriggerKind } from '@cindy/maker-shared/synthetic-trigger';
-import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
+import {
+ parseChatQuoteSegments,
+ stripChatQuoteMarkerLines,
+} from '@cindy/maker-shared/chat-quotes';
import { i18n } from '@/i18n';
import type { MobileOutboxDisplayItem, MobileOutboxThumb } from '@/session/sessionOutbox';
+import {
+ buildVisibleSentInlineTokens,
+ type SentInlineToken,
+} from '@/session/sentMessageAtoms';
import type { QueuedRemoteMessage } from '@/session/types';
export type MobilePendingSendPhase =
@@ -48,6 +55,8 @@ export interface MobilePendingSendItem {
key: string;
clientId: string;
text: string;
+ /** Structured quote / pasted-text / Slash atoms used by the optimistic renderer. */
+ sentInlineTokens: SentInlineToken[];
phase: MobilePendingSendPhase;
/** 队列序号(从 1 起,用于无障碍播报);不在队列里的条目为 null。 */
queueIndex: number | null;
@@ -84,6 +93,32 @@ export function pendingSendBubbleText(
return visibleText;
}
+function buildPendingSentInlineTokens(input: {
+ text: string;
+ quotesEncoded?: boolean;
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
+}): SentInlineToken[] {
+ const quoteSegments = input.quotesEncoded === true && input.text
+ ? parseChatQuoteSegments(input.text)
+ : [];
+ const visibleText = input.quotesEncoded === true
+ ? stripChatQuoteMarkerLines(input.text)
+ : input.text;
+ // 合成 UI 指令(「失败后继续」等)在正式消息流里会被隐藏。即使发送链路意外
+ // 给它带了 Slash range,乐观气泡也不能把裸指令重新泄露出来。
+ if (syntheticTriggerKind(visibleText)) return [];
+ const segments = quoteSegments.length > 0
+ ? quoteSegments
+ : input.text ? [{ kind: 'text' as const, text: input.text }] : [];
+ return buildVisibleSentInlineTokens(
+ input.text,
+ segments,
+ input.pastedTextRanges,
+ input.slashCommandRanges,
+ );
+}
+
/**
* 排队 / 落定气泡的图片缩略数据:消息 files 里的图片附件此刻仍是 `cindy-oss-attach://`
* 中转引用,本地渲染靠 sentAttachmentThumbStore 的兜底映射。非图片附件走计数行。
@@ -161,6 +196,12 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
key: pendingSendItemKey(item.clientId),
clientId: item.clientId,
text: pendingSendBubbleText(item),
+ sentInlineTokens: buildPendingSentInlineTokens({
+ text: item.text,
+ quotesEncoded: item.chatMessage.quotesEncoded,
+ pastedTextRanges: item.chatMessage.pastedTextRanges,
+ slashCommandRanges: item.chatMessage.slashCommandRanges,
+ }),
phase,
queueIndex,
thumbs: attachments.thumbs,
@@ -196,6 +237,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
key: pendingSendItemKey(item.clientId),
clientId: item.clientId,
text: item.quotesEncoded ? stripChatQuoteMarkerLines(item.text) : item.text,
+ sentInlineTokens: buildPendingSentInlineTokens(item),
phase: item.failed ? 'failed' : uploadsPending ? 'uploading' : 'sending',
queueIndex: null,
thumbs: item.thumbnails,
diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.ts
index b06c8454a1..3820c968a0 100644
--- a/apps/mobile/src/session/sessionOutbox.ts
+++ b/apps/mobile/src/session/sessionOutbox.ts
@@ -106,6 +106,8 @@ export interface MobileOutboxDisplayItem {
clientId: string;
text: string;
quotesEncoded: boolean;
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
attachmentCount: number;
uploadedCount: number;
/** 图片槽缩略格(按槽序);非图片附件走 fileCount 计数行。 */
@@ -371,6 +373,8 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayIt
clientId: item.clientId,
text: item.text,
quotesEncoded: item.quotesEncoded,
+ pastedTextRanges: item.pastedTextRanges,
+ slashCommandRanges: item.slashCommandRanges,
attachmentCount,
uploadedCount,
thumbnails,