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(bots): render component answers only in group message bodies

ylliuuu66b9fa5b6ba57f
diff --git a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
index 8e36ca1c6e..7166ccc447 100644
--- a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
@@ -8,6 +8,7 @@ import { refreshBotGroups } from '../../../src/renderer/features/bots/botGroupSt
import { ControlledBanner } from '../../../src/renderer/features/remote-device/ControlledBanner';
interface GroupData {
+ bodyAnswer?: boolean;
name: string;
members: Array<{ botId: string; name: string }>;
messages: number;
@@ -41,6 +42,21 @@ const message = (fields: Record<string, unknown>) => ({
});
/** One of each piece a teammate's bubble carries, in a conversation order. */
+function bodyMessages() {
+ const component = '```cindy-ui\n' + [
+ { seq: 1, version: 1, op: 'create', id: 'title', kind: 'heading', props: { text: '发布前检查' } },
+ { seq: 2, op: 'create', id: 'literal', kind: 'text', props: { text: '保留 <name>、*literal* 和 & 符号' } },
+ { seq: 3, op: 'create', id: 'list', kind: 'markdown', props: { text: '- 正文可以阅读\n- **重点**保持格式' } },
+ ].map(item => JSON.stringify(item)).join('\n') + '\n```';
+ return [
+ message({ id: 'body-user', sequence: 1, content: '请整理发布前检查', createdAt: T0 }),
+ message({ id: 'body-bot', sequence: 2, authorKind: 'bot', authorBotId: 'a', authorName: 'Aster',
+ content: '这是检查结果。\n\n' + component + '\n\n以上是本轮结论。', createdAt: T0 + MINUTE }),
+ message({ id: 'body-plain', sequence: 3, authorKind: 'bot', authorBotId: 'b', authorName: 'Nova',
+ content: '普通回复的 **加粗** 和段落保持原样。', createdAt: T0 + 2 * MINUTE }),
+ ];
+}
+
function bubbleMessages(wrappedReactions = false) {
const manyReactions = ['👍', '❤️', '😂', '🎉', '👀', '🙏', '✅', '🤔', '🔥', '👏', '🚀', '💯']
.map((emoji) => ({ emoji, count: 1, me: false }));
@@ -204,7 +220,7 @@ function groupFrom(data: GroupData) {
singleSpeaker: true } : {}),
...(data.bubbles || data.arrangement ? { serverBacked: true } : {}),
...(data.threadUnread ? { threads: threadSummaries() } : {}),
- messages: data.arrangement ? arrangementMessages(data.arrangement)
+ messages: data.bodyAnswer ? bodyMessages() : data.arrangement ? arrangementMessages(data.arrangement)
: bubbles ? bubbles.map(m => (data.threadUnread && UNREAD[m.id as string] ? { ...m, threadUnread: UNREAD[m.id as string] } : m))
: Array.from({ length: data.messages }, (_, i) => ({
id: `m${i}`,
diff --git a/apps/desktop/scripts/fixtures/group-control/ui-page.mjs b/apps/desktop/scripts/fixtures/group-control/ui-page.mjs
index f4b1d33706..2e004aae73 100644
--- a/apps/desktop/scripts/fixtures/group-control/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/group-control/ui-page.mjs
@@ -11,12 +11,21 @@ const LONG_DEVICE = 'Mac Studio · A very long device name for layout verificati
/** Migrated from check-group-control-layout.mjs (remote-control notice above the composer). */
export default {
name: 'group-chat',
+ // The single-page builder does not implement Vite's ?url imports. Voice is outside this fixture.
+ stubs: {
+ 'src/renderer/voice-input/workletUrl': 'export const getVoiceInputWorkletUrl = () => { throw new Error("Voice input is not covered by this fixture"); };',
+ },
entry: './group-control-fixture.tsx',
viewport: { width: 1280, height: 800 },
real: 'BotGroupChatView (timeline, composer, send button, header registration), ControlledBanner, ContentHeader shell, Markdown, theme, fonts and translations',
notCovered:
'Sending, round control, real device-link control and revocation, pending interactions, plans and attachments; the bubbles case shows a task snapshot, not a live task; the sidebar is an empty frame',
cases: {
+ 'body-answer': {
+ about: '#6550: component body is readable; literal punctuation and surrounding Markdown are retained',
+ viewport: { width: 720, height: 700 },
+ data: { ...base, sidebar: false, bodyAnswer: true },
+ },
default: { about: 'Empty group, short controller name, expanded sidebar', data: base },
'long-thread': {
about: '40 messages: bottom pin and history position survive notice changes',
@@ -69,6 +78,14 @@ export default {
},
async check(page, ui) {
const definition = this.cases[ui.case];
+ if (ui.case === 'body-answer') {
+ const timeline = page.getByTestId('bot-group-timeline');
+ assert.ok((await timeline.innerText()).includes('保留 <name>、*literal* 和 & 符号'));
+ assert.ok((await timeline.innerText()).includes('以上是本轮结论。'));
+ assert.equal(await timeline.getByText('重点', { exact: true }).count(), 1);
+ assert.ok(!(await timeline.innerText()).includes('"op":"create"'));
+ return;
+ }
const input = page.locator('textarea');
const chip = page.locator('[data-controlled-banner-chip]');
const collapsedDot = page.locator('[data-controlled-banner="collapsed"]');
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
index 46b086f713..e301071539 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
@@ -15,6 +15,8 @@
* 行用 `memo` 包住:父组件只在这条消息(或它的引用、安排快照、高亮状态)真的变了时才会
* 让它重绘;回调一律是父组件的稳定引用,按消息 id 调用。
*/
+import type { BotGroupAuthorKind } from '@cindy/maker-shared/botGroupChat';
+import { botGroupBodyParts } from '@cindy/maker-shared/botGroupPresentation';
import { memo, useEffect, useState, useLayoutEffect, useRef, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleAlert, CornerDownRight, RefreshCcw } from 'lucide-react';
@@ -126,8 +128,8 @@ const MENTION_CARD_CLOSE_MS = 150;
* Message text as Markdown, with `@名字` of known members in the link color. Resting the pointer on a
* mention shows that member's card; mentions are text ranges, so the hit test reads their boxes.
*/
-function BotGroupMessageText({ content, mentionLabels, members, mentions, serverBacked }: {
- content: string; mentionLabels: readonly string[]; members: readonly BotGroupMemberView[];
+function BotGroupMessageText({ content, mentionLabels, members, mentions, serverBacked, authorKind }: {
+ authorKind?: BotGroupAuthorKind; content: string; mentionLabels: readonly string[]; members: readonly BotGroupMemberView[];
/** Who the message mentioned; decides whose card a highlighted name opens. */
mentions: BotGroupMention;
serverBacked: boolean;
@@ -192,7 +194,9 @@ function BotGroupMessageText({ content, mentionLabels, members, mentions, server
return (
<div ref={ref} className="relative min-w-0 break-words" onPointerMove={onPointerMove}
onPointerLeave={() => { if (ref.current) ref.current.style.cursor = ''; scheduleClose(); }}>
- <MarkdownRenderer workingDir="" content={content} allowPrivilegedLinks={false} />
+ {botGroupBodyParts(content, authorKind).map((part, index) => part.kind === 'markdown'
+ ? <MarkdownRenderer key={index} workingDir="" content={part.content} allowPrivilegedLinks={false} />
+ : <p key={index} className="whitespace-pre-wrap break-words">{part.content}</p>)}
<BotGroupMentionCard member={card?.member ?? null} anchor={card?.anchor ?? null}
onPointerEnter={keepOpen} onPointerLeave={scheduleClose} />
</div>
@@ -534,7 +538,7 @@ function BotGroupTimelineItemImpl(props: BotGroupTimelineItemProps) {
{shareBody}
{!share && hasText ? (
<div className="min-w-0">
- <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} members={members} mentions={message.mentions ?? NO_MENTIONS} serverBacked={Boolean(props.reactionGroupId)} />
+ <BotGroupMessageText authorKind={message.authorKind} content={message.content} mentionLabels={mentionLabels} members={members} mentions={message.mentions ?? NO_MENTIONS} serverBacked={Boolean(props.reactionGroupId)} />
</div>
) : null}
{/* A task this teammate started from the group, under what it said about it; mine is live
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index b3730aa28a..408ace03b9 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -3710,3 +3710,17 @@ describe('pending main-chat copies across accounts', () => {
expect(mocks.reply).toHaveBeenCalledTimes(1);
});
});
+
+// #6550: actual timeline must project a bot's component body before Markdown rendering.
+it('renders component body as readable text without changing the message', async () => {
+ const content = 'Before\n\n```cindy-ui\n' + JSON.stringify({ seq: 1, version: 1, op: 'create', id: 'body', kind: 'text', props: { text: 'Readable answer' } }) + '\n```\n\nAfter';
+ const reply = msg({ id: 'rich-body', sequence: 1, authorKind: 'bot', authorBotId: 'a', content });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [reply] }) });
+ renderView();
+ await screen.findByText(/Readable answer/);
+ const body = screen.getByTestId('bot-group-timeline');
+ expect(body.textContent).toContain('Before');
+ expect(body.textContent).toContain('After');
+ expect(body.textContent).not.toContain('"op":"create"');
+ expect(reply.content).toBe(content);
+});
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 3f518acb5c..dda1c7f2a0 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -1327,3 +1327,16 @@ it('acknowledges other humans only once their messages reach the measured visibl
expect(h.chat.markRead).toHaveBeenLastCalledWith(['incoming-human']);
expect(h.markRead).not.toHaveBeenCalled();
});
+
+// #6550: screen + real mobile Markdown parser, with RN host primitives simulated in jsdom.
+it('renders component body as readable text without changing the message', async () => {
+ const content = 'Before\n\n```cindy-ui\n' + JSON.stringify({ seq: 1, version: 1, op: 'create', id: 'body', kind: 'text', props: { text: 'Readable answer' } }) + '\n```\n\nAfter';
+ const reply = message('rich-body', 1, { authorBotId: 'mimi', authorName: '咪咪', content });
+ await render(group({ messages: [reply] }));
+ const body = byId('botGroup.message.bot')!;
+ expect(body.textContent).toContain('Readable answer');
+ expect(body.textContent).toContain('Before');
+ expect(body.textContent).toContain('After');
+ expect(body.textContent).not.toContain('"op":"create"');
+ expect(reply.content).toBe(content);
+});
diff --git a/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx b/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
index a89be05718..6310e2adaf 100644
--- a/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
@@ -56,3 +56,15 @@ it('群聊不打开链接:强调里的链接只保留强调样式,不加下划
// 强调里的行内代码照常套代码样式。
expect(styleOf('a.ts')).toMatchObject({ fontFamily: 'Menlo' });
});
+
+// #6550: real group-body renderer must not reinterpret literal component text as markup.
+it('keeps component literal punctuation and Markdown formatting distinct', async () => {
+ const content = '```cindy-ui\n' + [
+ { seq: 1, version: 1, op: 'create', id: 'literal', kind: 'text', props: { text: '<name> *literal* & \n indented' } },
+ { seq: 2, op: 'create', id: 'md', kind: 'markdown', props: { text: '**authored bold**' } },
+ ].map(item => JSON.stringify(item)).join('\n') + '\n```';
+ await act(async () => root.render(createElement(BotGroupMarkdownText, { content, authorKind: 'bot' })));
+ expect(node.textContent).toContain('<name> *literal* & \n indented');
+ expect(styleOf('authored bold')).toMatchObject({ fontWeight: '600' });
+ expect(node.textContent).not.toContain('"op":"create"');
+});
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index 0c0552fe8f..56012e32ff 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -586,7 +586,7 @@ function BotGroupTimelineItem({
{message.task ? <BotGroupTaskCard task={message.task} owned={member !== undefined && member.isOwned !== false}
deviceId={member?.homeDeviceId || deviceId || ''} /> : null}
{message.attachments?.length ? <BotGroupMessageAttachments messageId={message.id} attachments={message.attachments} align="left" onResolveRemoteMedia={resolveMedia} resolveServerMedia={resolveServerMedia} /> : null}
- {message.content.trim() ? <BotGroupMarkdownText content={message.content} /> : null}
+ {message.content.trim() ? <BotGroupMarkdownText content={message.content} authorKind={message.authorKind} /> : null}
<BotGroupHandoffFiles files={message.files} />
</>}
</View>
diff --git a/apps/mobile/src/session/BotGroupMessageText.tsx b/apps/mobile/src/session/BotGroupMessageText.tsx
index 9ed9e52641..64ca036cbd 100644
--- a/apps/mobile/src/session/BotGroupMessageText.tsx
+++ b/apps/mobile/src/session/BotGroupMessageText.tsx
@@ -3,6 +3,8 @@
* 行内强调 / 代码),与伙伴私聊回看同样是只读文本,不加载任务页的完整消息渲染器;链接只
* 显示文字,不在群聊里打开。用户自己的消息保留原文,`@名字` 画成点名标记。
*/
+import { botGroupBodyParts } from '@cindy/maker-shared/botGroupPresentation';
+import type { BotGroupAuthorKind } from '@cindy/maker-shared/botGroupChat';
import { useMemo, type ReactNode } from 'react';
import { StyleSheet, View } from 'react-native';
import { splitBotGroupMentionSegments } from '@cindy/maker-shared/botGroupMentions';
@@ -72,9 +74,11 @@ function renderBlock(block: MobileMarkdownBlock, styles: Styles): ReactNode {
}
}
-export function BotGroupMarkdownText({ content }: { content: string }) {
+export function BotGroupMarkdownText({ content, authorKind }: { content: string; authorKind?: BotGroupAuthorKind }) {
const styles = useThemedStyles(makeStyles);
- const blocks = useMemo(() => parseMobileMarkdown(content), [content]);
+ const blocks = useMemo(() => botGroupBodyParts(content, authorKind).flatMap((part, index): MobileMarkdownBlock[] => part.kind === 'markdown'
+ ? parseMobileMarkdown(part.content).map(block => ({ ...block, key: `${index}:${block.key}` }))
+ : [{ type: 'paragraph', key: String(index), inlines: [{ type: 'text', text: part.content }] }]), [content, authorKind]);
return <View style={styles.body}>{blocks.map((block) => renderBlock(block, styles))}</View>;
}
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 8574eb1c06..79dc8178d8 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -223,6 +223,8 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下
## 5. 界面
+- 桌面和手机群聊正文将伙伴的组件回答显示为可读内容;无法转换的内容保留原文。
+
- 群聊行与伙伴私聊混排在侧栏「伙伴」段(置顶上方,与任务列表共用一个侧栏,见
[cindy-bots-runtime.md](cindy-bots-runtime.md#导航未读与系统角标));段头加号提供新建伙伴与新建群聊。群行显示成员组合头像、群名与最近一条消息:
两人斜向叠放;三人及以上围绕同一圆心等角度重叠,按群成员顺序取前五人,整体呈圆形聚拢。
diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
index 7bcf06ce70..5c6f0ad818 100644
--- a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
+ botGroupBodyParts,
botGroupComposerPlanState,
botGroupErrorVariant,
botGroupNoticeVariant,
@@ -156,3 +157,35 @@ describe('queue lanes', () => {
expect(groupLaneOfRouteKey(key)).toBe(`group:g1:access:${mode}:2`);
});
});
+
+// #6550: display-only projection. Existing presentation tests had no component bodies.
+describe('group body component display', () => {
+ const rich = (...nodes: Array<Record<string, unknown>>) => '```cindy-ui\n' + nodes.map((node, i) => JSON.stringify({ version: 1, seq: i + 1, op: 'create', id: `n${i}`, ...node })).join('\n') + '\n```';
+ it('keeps literal text literal, Markdown authored formatting, and surrounding prose in order', () => {
+ const content = 'Before\n\n' + rich({ kind: 'text', props: { text: '<name> *literal* & \n indented' } }, { kind: 'markdown', props: { text: '**bold**' } }) + '\nAfter';
+ expect(botGroupBodyParts(content, 'bot')).toEqual([
+ { kind: 'markdown', content: 'Before\n\n' },
+ { kind: 'text', content: '<name> *literal* & \n indented' },
+ { kind: 'markdown', content: '**bold**' },
+ { kind: 'markdown', content: 'After' },
+ ]);
+ });
+ it.each(['', 'Normal **text**', '```json\n{"op":"create"}\n```', '````md\n```cindy-ui\nexample\n```\n````'])('preserves ordinary or example body %s', content => {
+ expect(botGroupBodyParts(content, 'bot')).toEqual(content ? [{ kind: 'markdown', content }] : []);
+ });
+ it.each(['user', 'system'] as const)('does not convert %s authors', authorKind => {
+ const content = rich({ kind: 'text', props: { text: 'Example' } });
+ expect(botGroupBodyParts(content, authorKind)).toEqual([{ kind: 'markdown', content }]);
+ });
+ it.each([rich({ kind: 'text', props: { text: '' } }), rich({ kind: 'range' }), '```cindy-ui\ninvalid\n```'])('retains unreadable source %s', content => {
+ expect(botGroupBodyParts(content, 'bot')).toEqual([{ kind: 'markdown', content }]);
+ });
+ it('uses final tree content and exposes media descriptions without requesting local media', () => {
+ const content = rich({ kind: 'stack', props: { label: 'Summary' } }, { parent: 'n0', kind: 'text', props: { text: 'Old' } },
+ { op: 'patch', id: 'n1', props: { text: 'Updated' } }, { kind: 'image', props: { alt: 'Diagram', src: 'cindy-media://blobs/example.png' } });
+ expect(botGroupBodyParts(content, 'bot')).toEqual([
+ { kind: 'text', content: 'Summary' }, { kind: 'text', content: 'Updated' },
+ { kind: 'text', content: 'Diagram\ncindy-media://blobs/example.png' },
+ ]);
+ });
+});
diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.ts
index 78001e3e94..58efd3735c 100644
--- a/packages/maker-shared/src/botGroupPresentation.ts
+++ b/packages/maker-shared/src/botGroupPresentation.ts
@@ -3,6 +3,7 @@
* 排序、成员名单、轮次标记与分工(安排、下一步、交接文件)的判定,以及提示 / 报错
* 该用哪一句文案(各端按自己的 i18n 命名空间拼 key)。只依赖群聊契约,不碰 React 与 IPC。
*/
+import { RichAnswerStream, splitRichAnswer, richMarkdown, richString, richLabel, richResolvedValues, richChart, richOptions } from './richAnswer.js';
import {
isBotGroupPlanOpen,
type BotGroupDetail,
@@ -346,3 +347,48 @@ export function botGroupPathBasename(path: string): string {
const parts = path.split(/[\\/]+/).filter(Boolean);
return parts[parts.length - 1] ?? path;
}
+
+/** Display-only body fragments. Literal component text never becomes Markdown syntax. */
+export function botGroupBodyParts(content: string, authorKind?: BotGroupMessageView['authorKind']): Array<{ kind: 'text' | 'markdown'; content: string }> {
+ if (authorKind !== 'bot') return [{ kind: 'markdown', content }];
+ const parts = splitRichAnswer(content);
+ return parts.flatMap((part, index) => {
+ const source = content.slice(part.key, parts[index + 1]?.key ?? content.length);
+ if (part.kind === 'markdown') return [{ kind: 'markdown' as const, content: source }];
+ const doc = new RichAnswerStream().update(part.source, true);
+ // Preserve malformed or empty answers rather than silently dropping source content.
+ if (doc.issues) return [{ kind: 'markdown' as const, content: source }];
+ const values = richResolvedValues(doc);
+ const result: Array<{ kind: 'text' | 'markdown'; content: string }> = [];
+ const add = (text: string, kind: 'text' | 'markdown' = 'text') => {
+ if (text.trim()) result.push({ kind, content: text });
+ };
+ const visit = (id: string) => {
+ const node = doc.nodes.get(id);
+ if (!node) return;
+ const label = richString(node, 'label');
+ if (['image', 'video', 'audio', 'svg'].includes(node.kind)) {
+ // Group body has no task-local media authority. Keep its description readable.
+ add([label, richString(node, 'alt'), richString(node, 'caption'), richString(node, 'src')].filter(Boolean).join('\n'));
+ } else {
+ const markdown = richMarkdown(node);
+ if (markdown !== null) add(markdown, 'markdown');
+ else if (['text', 'heading'].includes(node.kind)) add(richLabel(node, values));
+ else if (node.kind === 'stat') add([label, richLabel(node, values)].filter(Boolean).join(': '));
+ else if (node.kind === 'chart') add([label, ...richChart(node, values).map(item => `${item.label}: ${item.value}`)].filter(Boolean).join('\n'));
+ else if (node.kind === 'icon') add([label, richString(node, 'text')].filter(Boolean).join('\n'));
+ else if (node.kind === 'divider') add('---', 'markdown');
+ else {
+ // Show authored defaults only; an untouched control is not a user answer.
+ const current = node.props.default;
+ const selected = node.kind === 'select' ? richOptions(node).find(option => option.value === current)?.label : undefined;
+ const display = selected ?? (typeof current === 'string' || typeof current === 'number' || typeof current === 'boolean' ? String(current) : '');
+ add([label, display && display + richString(node, 'suffix')].filter(Boolean).join(': '));
+ }
+ }
+ node.children.forEach(visit);
+ };
+ doc.roots.forEach(visit);
+ return result.length ? result : [{ kind: 'markdown' as const, content: source }];
+ });
+}