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(mobile): 保留伙伴群聊 Markdown 表格的行列布局

zcinta05149c147b5dfaa6
diff --git a/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx b/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
index a89be05718..5766448dec 100644
--- a/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupMarkdownText.test.tsx
@@ -8,18 +8,23 @@ vi.mock('react-native', async () => {
const React = await import('react');
const flat = (style: unknown): Record<string, unknown> =>
Object.assign({}, ...[style].flat(Infinity).filter(Boolean));
- const host = (tag: string) => ({ children, style }: any) =>
- React.createElement(tag, { 'data-style': JSON.stringify(flat(style)) }, children);
+ const host = (tag: string) => ({ children, style, horizontal, onLayout, testID }: any) => {
+ React.useEffect(() => { onLayout?.({ nativeEvent: { layout: { width: 280 } } }); }, [onLayout]);
+ return React.createElement(tag, { 'data-style': JSON.stringify(flat(style)),
+ 'data-horizontal': horizontal, 'data-testid': testID }, children);
+ };
return {
View: host('div'),
+ ScrollView: host('section'),
Text: host('span'),
+ useWindowDimensions: () => ({ width: 360, height: 800, fontScale: 1, scale: 3 }),
StyleSheet: { create: (s: any) => s, flatten: (s: any) => s, hairlineWidth: 1 },
Platform: { OS: 'ios', select: (s: any) => s.ios ?? s.default },
};
});
vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
vi.mock('@/theme', () => ({
- fontWeight: { semibold: '600', bold: '700' },
+ fontWeight: { regular: '400', medium: '500', semibold: '600', bold: '700' },
monoFont: 'Menlo',
useThemedStyles: (make: (colors: any) => any) => make(new Proxy({}, { get: () => '#000' })),
}));
@@ -34,6 +39,36 @@ beforeEach(() => {
document.body.append(node);
root = createRoot(node);
});
+
+// #6713: real group body previously flattened tables into one Text. DOM hosts do not
+// measure RN layout; verify the rendered row/cell geometry here, then test native scrolling in Simulator.
+it('keeps table columns aligned across short, long and empty cells, with horizontal overflow', async () => {
+ await act(async () => root.render(createElement(BotGroupMarkdownText, {
+ content: '| 项目 | 说明 | 状态 |\n| --- | --- | --- |\n| A | **很长的说明内容需要在所属单元格内换行,不能串到下一列** | 完成 |\n| B | | 进行中 |',
+ })));
+ const scroll = node.querySelector('section[data-horizontal="true"]');
+ expect(scroll).not.toBeNull();
+ const rows = [...scroll!.firstElementChild!.children];
+ expect(rows).toHaveLength(3);
+ const widths = rows.map(row => [...row.children].map(cell => JSON.parse(cell.getAttribute('data-style')!).width));
+ expect(widths[0]).toHaveLength(3);
+ expect(widths[1]).toEqual(widths[0]);
+ expect(widths[2]).toEqual(widths[0]);
+ expect(widths[0].reduce((a, b) => a + b, 0)).toBeGreaterThan(280);
+ expect([...rows[2].children].map(cell => cell.textContent)).toEqual(['B', '', '进行中']);
+ expect(styleOf('很长的说明内容需要在所属单元格内换行,不能串到下一列').fontWeight).toBe('600');
+ expect(node.textContent).not.toContain(' | ');
+});
+
+it('expands a short table to the measured message width without changing code blocks', async () => {
+ await act(async () => root.render(createElement(BotGroupMarkdownText, {
+ content: '| A | B |\n| --- | --- |\n| 1 | 2 |\n\n~~~text\na | b\n~~~',
+ })));
+ const row = node.querySelector('section')!.firstElementChild!.firstElementChild!;
+ const widths = [...row.children].map(cell => JSON.parse(cell.getAttribute('data-style')!).width);
+ expect(widths.reduce((a, b) => a + b, 0)).toBe(280);
+ expect(styleOf('a | b').fontFamily).toBe('Menlo');
+});
afterEach(() => {
act(() => root.unmount());
node.remove();
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index f8e729aee5..c1a9549e27 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -1,6 +1,7 @@
import { SHARED_REMOTE_CONTROL_FIXTURE } from '@cindy/maker-shared/fixtures';
import { projectHistoryView } from '@cindy/maker-shared/message-window';
import { TASK_TAG_COLORS, type TaskTagRequest, type TaskTagResult } from '@cindy/maker-shared';
+import { BOT_GROUP_CHAT_PRIMITIVE, BOT_GROUP_REMOTE_COLLECTION_ID, BOT_GROUP_REMOTE_RESOURCE_KIND } from '@cindy/maker-shared/botGroupChat';
import { ApiError, type ApiFetchOptions } from '@/api/client';
import type { DeviceView, LinkAcceptPayload } from '@cindy/device-link';
import type { MobileUser } from '@/auth/AuthContext';
@@ -212,6 +213,33 @@ async function visualMockInvoke<T = unknown>(
channel: string,
args: unknown[] = [],
): Promise<T> {
+ // #6713 native regression: open /companions/groups/table-qa?deviceId=cindy-visual-mock-mac.
+ // Only reachable through the existing __DEV__ visual-mock provider; no real account or server.
+ if (process.env.EXPO_PUBLIC_CINDY_GROUP_TABLE_DEMO === '1'
+ && channel === 'maker:remote-resources:get'
+ && (args[0] as { ref?: { collectionId?: string; id?: string } })?.ref?.collectionId === BOT_GROUP_REMOTE_COLLECTION_ID
+ && (args[0] as { ref?: { id?: string } })?.ref?.id === 'table-qa') {
+ const content = [
+ '窄屏表格:短表铺满正文,宽表横向滑动。',
+ '', '| A | B |', '| --- | --- |', '| 1 | 2 |',
+ '', '| 项目 | 说明 | 状态 | 最后一列 |', '| --- | --- | --- | --- |',
+ '| A | **长说明在单元格内换行,行高应随内容增加,下一行仍按相同列宽对齐。** | 完成 | 末列可见 |',
+ '| B | | 进行中 | 末列第二行 |',
+ '', '~~~text', 'code | unchanged', '~~~',
+ '', '表格后正文:上下滚动仍可阅读。',
+ ].join('\n');
+ return {
+ ref: { collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: 'table-qa' }, revision: '1',
+ display: { title: 'Table QA · Synthetic data' }, actions: [], links: [],
+ blocks: [{ id: 'chat', primitive: BOT_GROUP_CHAT_PRIMITIVE, fallbackMarkdown: content, data: {
+ id: 'table-qa', name: 'Table QA · Synthetic data',
+ members: [{ botId: 'table-bot', name: 'QA Partner', status: 'active' }],
+ messages: [{ id: 'table-message', sequence: 1, kind: 'message', authorKind: 'bot',
+ authorBotId: 'table-bot', authorName: 'QA Partner', content, createdAt: NOW }],
+ plans: [], createdAt: NOW, updatedAt: NOW,
+ } }],
+ } as T;
+ }
const realData = await loadVisualRealDataSnapshot();
const pluginResult = realData ? undefined : pluginVisualFixture(channel, args);
if (pluginResult !== undefined) return pluginResult as T;
diff --git a/apps/mobile/src/session/BotGroupMessageText.tsx b/apps/mobile/src/session/BotGroupMessageText.tsx
index 9ed9e52641..99b0ed7b37 100644
--- a/apps/mobile/src/session/BotGroupMessageText.tsx
+++ b/apps/mobile/src/session/BotGroupMessageText.tsx
@@ -1,15 +1,17 @@
/**
* 群聊消息正文。伙伴的回复是 Markdown:这里只做轻量排版(段落、标题、引用、列表、代码块、
- * 行内强调 / 代码),与伙伴私聊回看同样是只读文本,不加载任务页的完整消息渲染器;链接只
+ * 表格、行内强调 / 代码),与伙伴私聊回看同样是只读文本,不加载任务页的完整消息渲染器;链接只
* 显示文字,不在群聊里打开。用户自己的消息保留原文,`@名字` 画成点名标记。
*/
-import { useMemo, type ReactNode } from 'react';
-import { StyleSheet, View } from 'react-native';
+import { useCallback, useMemo, useState, type ReactNode } from 'react';
+import { ScrollView, StyleSheet, View, useWindowDimensions, type LayoutChangeEvent } from 'react-native';
import { splitBotGroupMentionSegments } from '@cindy/maker-shared/botGroupMentions';
import { Text } from '@/components/AppText';
import { fontWeight, monoFont, useThemedStyles, type ThemeColors } from '@/theme';
import { lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
import { parseMobileMarkdown, type MobileMarkdownBlock, type MobileMarkdownInline } from './messageMarkdown';
+import { buildMessageContentLayout } from './messageContentLayout';
+import { buildMobileMarkdownTableColumnWidths } from './messageTableLayout';
type Styles = ReturnType<typeof makeStyles>;
@@ -37,11 +39,36 @@ function renderInlines(inlines: readonly MobileMarkdownInline[], styles: Styles)
});
}
-function tableText(block: Extract<MobileMarkdownBlock, { type: 'table' }>): string {
- const cell = (inlines: readonly MobileMarkdownInline[]) => inlines.map((inline) => inline.type === 'image' ? inline.alt : inline.text).join('');
- return [block.header, ...block.rows.map((row) => row.cells)]
- .map((cells) => cells.map(cell).join(' | '))
- .join('\n');
+function BotGroupMarkdownTable({ block, styles }: {
+ block: Extract<MobileMarkdownBlock, { type: 'table' }>;
+ styles: Styles;
+}) {
+ const { width: screenWidth } = useWindowDimensions();
+ const [availableWidth, setAvailableWidth] = useState(0);
+ const onLayout = useCallback((event: LayoutChangeEvent) => {
+ setAvailableWidth(event.nativeEvent.layout.width);
+ }, []);
+ const widths = buildMobileMarkdownTableColumnWidths({
+ header: block.header, rows: block.rows, availableWidth,
+ minWidth: buildMessageContentLayout({ screenWidth }).markdownTableCellMinWidth,
+ });
+ const renderRow = (cells: readonly MobileMarkdownInline[][], key: string, header = false) => (
+ <View key={key} style={[styles.tableRow, header && styles.tableHeaderRow]}>
+ {widths.map((width, index) => (
+ <View key={index} style={[styles.tableCell, { width }]}>
+ <Text selectable style={[styles.tableText, header && styles.tableHeaderText]}>
+ {renderInlines(cells[index] ?? [], styles)}
+ </Text>
+ </View>
+ ))}
+ </View>
+ );
+ return <ScrollView horizontal style={styles.tableScroll} onLayout={onLayout}>
+ <View style={styles.table}>
+ {renderRow(block.header, `${block.key}:header`, true)}
+ {block.rows.map(row => renderRow(row.cells, row.key))}
+ </View>
+ </ScrollView>;
}
function renderBlock(block: MobileMarkdownBlock, styles: Styles): ReactNode {
@@ -64,9 +91,7 @@ function renderBlock(block: MobileMarkdownBlock, styles: Styles): ReactNode {
<Text selectable style={styles.codeText}>{block.text}</Text>
</View>;
case 'table':
- return <View key={block.key} style={styles.codeBlock}>
- <Text selectable style={styles.codeText}>{tableText(block)}</Text>
- </View>;
+ return <BotGroupMarkdownTable key={block.key} block={block} styles={styles} />;
default:
return <Text key={block.key} selectable style={styles.text}>{renderInlines(block.inlines, styles)}</Text>;
}
@@ -106,5 +131,15 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
codeBlock: { backgroundColor: colors.chatCodeSurface, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,
borderRadius: radius.control, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },
codeText: { color: colors.textPrimary, fontFamily: monoFont, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },
+ tableScroll: { maxWidth: '100%' },
+ table: { borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,
+ borderRadius: radius.container, overflow: 'hidden' },
+ tableRow: { flexDirection: 'row' },
+ tableHeaderRow: { backgroundColor: colors.surfaceElevated },
+ tableCell: { flexShrink: 0, borderRightColor: colors.border, borderRightWidth: StyleSheet.hairlineWidth,
+ borderBottomColor: colors.border, borderBottomWidth: StyleSheet.hairlineWidth,
+ paddingHorizontal: spacing.sm, paddingVertical: spacing.xs },
+ tableText: { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },
+ tableHeaderText: { color: colors.textSecondary, fontWeight: fontWeight.medium },
mention: { fontWeight: fontWeight.medium, backgroundColor: colors.surfaceChip },
});
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index b8a7788476..7db39620fa 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -356,6 +356,8 @@
- 群聊页与电脑一致:多作者时间线、安排卡、交接消息与文件名、「下一步 · 继续」「没做完 · 重试」、
「N 步都做完了」、正在发言/安排/做的伙伴、待确认操作内嵌;输入框支持 @、附件(见 3.1)与「+」安排分工。
- 电脑不支持群附件时(旧版本,`supportsAttachments` 缺省),手机不显示附件入口。
+- 伙伴正文中的 Markdown 表格保留表头与单元格,逐列统一宽度;短表铺满正文可用宽度,宽表在表格内横向滚动,长内容在所属单元格内换行。
+ 列宽复用普通任务的 `messageTableLayout.ts`,实现与回归见 `BotGroupMessageText.tsx`、`BotGroupMarkdownText.test.tsx`。
- 分工产出的文件在电脑上:手机只显示文件名,不在手机上打开。消息附件里的图片经已有远程媒体读取显示缩略图,
文件只显示名字。
- 视觉遵循 Mobile 设计规范:按钮用手机端现有的紧凑按钮(视觉轻、触控够),Light / Dark 同时实现。