Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): make everyday rich answers readable with native icons and chart labels
Chris326e80821515
diff --git a/apps/desktop/src/renderer/components/chat/RichAnswer.tsx b/apps/desktop/src/renderer/components/chat/RichAnswer.tsxindex e5f756458f..71326083b2 100644--- a/apps/desktop/src/renderer/components/chat/RichAnswer.tsx+++ b/apps/desktop/src/renderer/components/chat/RichAnswer.tsx@@ -1,3 +1,17 @@+import {+ Mail,+ CalendarDays,+ Folder,+ ChartColumn,+ Check,+ Info,+ Clock,+ MapPin,+ Coffee,+ Image,+ Users,+ Star,+} from 'lucide-react';import {Fragment,useMemo,@@ -14,6 +28,7 @@ import {RichInteractionMemory,richAction,richChart,+ richLinePlot,richResolvedValues,richCalculationUnavailable,richLabel,@@ -31,11 +46,28 @@ import { Input } from '@/components/ui/input';import { Slider } from '@/components/ui/slider';import './rich-answer.css';+const answerIcons = {+ mail: Mail,+ calendar: CalendarDays,+ folder: Folder,+ chart: ChartColumn,+ check: Check,+ info: Info,+ clock: Clock,+ location: MapPin,+ coffee: Coffee,+ image: Image,+ users: Users,+ star: Star,+};+const memory = new RichInteractionMemory({async read() {return localStorage.getItem('cindy.richAnswer.viewState.v1');},- writeSync(value) { localStorage.setItem('cindy.richAnswer.viewState.v1', value); },+ writeSync(value) {+ localStorage.setItem('cindy.richAnswer.viewState.v1', value);+ },async write(value) {localStorage.setItem('cindy.richAnswer.viewState.v1', value);},@@ -98,11 +130,16 @@ function RichAnswerDocument({const render = (id: string): ReactNode => {const node = doc.nodes.get(id);if (!node) return null;- if (richCalculationUnavailable(node, values)) return <p className="rich-answer-caption" role="status">{complete ? t('richAnswer.calculationUnavailable') : '…'}</p>;+ if (richCalculationUnavailable(node, values))+ return (+ <p className="rich-answer-caption" role="status">+ {complete ? t('richAnswer.calculationUnavailable') : '…'}+ </p>+ );const bind = richString(node, 'bind', id),label = richString(node, 'label');const children = node.children.map((child) => <Fragment key={child}>{render(child)}</Fragment>);- if ((['image', 'video', 'audio'].includes(node.kind)) && renderMedia)+ if (['image', 'video', 'audio'].includes(node.kind) && renderMedia)return (<div className="rich-answer-content">{renderMedia(node)}@@ -126,6 +163,23 @@ function RichAnswerDocument({return <h3 className="rich-answer-heading">{richLabel(node, values)}</h3>;case 'text':return <p className="rich-answer-text">{richLabel(node, values)}</p>;+ case 'icon': {+ const name = richString(node, 'name');+ const Icon = Object.prototype.hasOwnProperty.call(answerIcons, name)+ ? answerIcons[name as keyof typeof answerIcons]+ : Info;+ return (+ <div className="rich-answer-icon-row">+ <Icon size={20} strokeWidth={1.75} aria-hidden="true" />+ <div>+ <strong>{label || name}</strong>+ {richString(node, 'text') && (+ <p className="rich-answer-text">{richString(node, 'text')}</p>+ )}+ </div>+ </div>+ );+ }case 'divider':return <hr className="rich-answer-divider" />;case 'stack':@@ -293,35 +347,30 @@ function RichAnswerDocument({<figure className="rich-answer-chart"><figcaption>{label}</figcaption>{richString(node, 'variant') === 'line' ? (- <svg role="img" aria-label={label} viewBox="0 0 480 180">- <polyline- fill="none"- stroke="currentColor"- strokeWidth="2"- points={data- .map(- (item, i) =>- `${10 + (i / Math.max(1, data.length - 1)) * 460},${170 - ((item.value - min) / span) * 160}`,- )- .join(' ')}- />- </svg>+ <AnswerLineChart data={data} label={label} />) : null}- <dl>- {data.map((item, i) => (- <div key={i}>- <div className="rich-answer-control-label">- <dt>{item.label}</dt>- <dd>{item.value}</dd>- </div>- {richString(node, 'variant') !== 'line' && (- <div className="rich-answer-track">- <div style={{ marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`, width: `${(Math.abs(item.value) / span) * 100}%` }} />+ {richString(node, 'variant') !== 'line' && (+ <dl>+ {data.map((item, i) => (+ <div key={i}>+ <div className="rich-answer-control-label">+ <dt>{item.label}</dt>+ <dd>{item.value}</dd></div>- )}- </div>- ))}- </dl>+ {richString(node, 'variant') !== 'line' && (+ <div className="rich-answer-track">+ <div+ style={{+ marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`,+ width: `${(Math.abs(item.value) / span) * 100}%`,+ }}+ />+ </div>+ )}+ </div>+ ))}+ </dl>+ )}</figure>);}@@ -342,3 +391,78 @@ function RichAnswerDocument({</div>);}++function AnswerLineChart({+ data,+ label,+}: {+ data: { label: string; value: number }[];+ label: string;+}) {+ const ref = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(480);+ useEffect(() => {+ if (!ref.current) return;+ const observer = new ResizeObserver((entries) => setWidth(entries[0].contentRect.width));+ observer.observe(ref.current);+ return () => observer.disconnect();+ }, []);+ const plot = richLinePlot(data, width);+ return (+ <div ref={ref}>+ <svg+ role="img"+ aria-label={`${label}. ${data.map((item) => `${item.label}: ${item.value}`).join(', ')}`}+ viewBox={`0 0 ${plot.width} ${plot.height}`}+ style={{ height: plot.height }}+ >+ {plot.ticks.map((tick) => (+ <Fragment key={tick.value}>+ <line+ x1={plot.left}+ x2={plot.width - plot.right}+ y1={tick.y}+ y2={tick.y}+ className="rich-answer-chart-guide"+ />+ <text+ x={plot.left - 6}+ y={tick.y + 4}+ textAnchor="end"+ className="rich-answer-chart-axis"+ >+ {Number(tick.value.toPrecision(3))}+ </text>+ </Fragment>+ ))}+ <polyline+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ points={plot.points.map((p) => `${p.x},${p.y}`).join(' ')}+ />+ {plot.points.map((p, i) => (+ <Fragment key={i}>+ <circle cx={p.x} cy={p.y} r={3} fill="currentColor" />+ {plot.showValues && (+ <text x={p.x} y={p.y - 10} textAnchor="middle" className="rich-answer-chart-value">+ {p.value}+ </text>+ )}+ </Fragment>+ ))}+ </svg>+ <dl+ className={data.length <= 8 ? 'rich-answer-chart-labels' : undefined}+ style={data.length <= 8 ? { paddingLeft: plot.left, paddingRight: plot.right } : undefined}+ >+ {data.map((item, i) => (+ <div key={i}>+ <dt>{item.label}</dt>+ {!plot.showValues && <dd>{item.value}</dd>}+ </div>+ ))}+ </dl>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsxindex 777b69d2cc..4fb7e67999 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx@@ -5,32 +5,64 @@ vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { id: 'test-ovi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));import { RichAnswer } from '../RichAnswer';afterEach(cleanup);+vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ disconnect() {}+ },+);const line = (seq: number, op: Record<string, unknown>) => JSON.stringify({ seq, ...op }) + '\n';// Tier 1: mount the production renderer; input identity/state must survive// streamed patches, the final marker, and message-list virtualization.it('preserves edited controls through patches, finalization and remount', () => {- const source = line(1, { op: 'create', id: 'name', kind: 'input', props: { label: 'Name', default: 'Original' } }) + line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Before' } });+ const source =+ line(1, {+ op: 'create',+ id: 'name',+ kind: 'input',+ props: { label: 'Name', default: 'Original' },+ }) + line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Before' } });const props = { stateKey: 'stream-state', renderMarkdown: (text: string) => <span>{text}</span> };const view = render(<RichAnswer {...props} source={source} complete={false} />);const input = screen.getByLabelText('Name');fireEvent.change(input, { target: { value: 'Edited' } });- const updated = source + line(3, { op: 'patch', id: 'name', props: { default: 'New default' } }) + line(4, { op: 'append', id: 'note', text: ' and after' });+ const updated =+ source ++ line(3, { op: 'patch', id: 'name', props: { default: 'New default' } }) ++ line(4, { op: 'append', id: 'note', text: ' and after' });view.rerender(<RichAnswer {...props} source={updated} complete={true} />);expect(screen.getByLabelText('Name')).toBe(input);expect((input as HTMLInputElement).value).toBe('Edited');// Immediate reload must save the edit before the debounce fires.fireEvent(window, new Event('pagehide'));const saved = JSON.parse(localStorage.getItem('cindy.richAnswer.viewState.v1')!);- expect(saved.entries.find(([key]: [string]) => key === 'test-owner:stream-state')[1].name).toBe('Edited');+ expect(saved.entries.find(([key]: [string]) => key === 'test-owner:stream-state')[1].name).toBe(+ 'Edited',+ );expect(screen.getByText('Before and after')).toBeTruthy();view.unmount();render(<RichAnswer {...props} source={updated} complete />);expect((screen.getByLabelText('Name') as HTMLInputElement).value).toBe('Edited');});it('routes image media through the host renderer without evaluating generated markup', () => {- const source = line(1, { op: 'create', id: 'image', kind: 'image', props: { src: 'library:assets/a.png', alt: 'Preview' } }) + line(2, { op: 'create', id: 'text', kind: 'text', props: { text: '<script>throw 1</script>' } });+ const source =+ line(1, {+ op: 'create',+ id: 'image',+ kind: 'image',+ props: { src: 'library:assets/a.png', alt: 'Preview' },+ }) ++ line(2, {+ op: 'create',+ id: 'text',+ kind: 'text',+ props: { text: '<script>throw 1</script>' },+ });const renderMarkdown = vi.fn((text: string) => <span>{text}</span>);- const view = render(<RichAnswer stateKey="media" source={source} complete renderMarkdown={renderMarkdown} />);+ const view = render(+ <RichAnswer stateKey="media" source={source} complete renderMarkdown={renderMarkdown} />,+ );expect(renderMarkdown).toHaveBeenCalledWith('', 'image');expect(view.container.querySelector('script')).toBeNull();expect(screen.getByText('<script>throw 1</script>')).toBeTruthy();@@ -38,14 +70,111 @@ it('routes image media through the host renderer without evaluating generated ma// Tier 1: a referenced result may arrive after its consumer in a live answer.// Pending/error states must not erase readable content or misrepresent a total.it('renders pending calculated references, resolves them and isolates invalid final values', () => {- const first = line(1, { op: 'create', id: 'total', kind: 'stat', props: { label: 'Total', value: { ref: 'price' } } }) + line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Existing explanation' } });- const props = { stateKey: 'forward-reference', renderMarkdown: (text: string) => <span>{text}</span> };+ const first =+ line(1, {+ op: 'create',+ id: 'total',+ kind: 'stat',+ props: { label: 'Total', value: { ref: 'price' } },+ }) ++ line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Existing explanation' } });+ const props = {+ stateKey: 'forward-reference',+ renderMarkdown: (text: string) => <span>{text}</span>,+ };const view = render(<RichAnswer {...props} source={first} complete={false} />);expect(screen.getByRole('status').textContent).toBe('…');- view.rerender(<RichAnswer {...props} source={first + line(3, { op: 'create', id: 'price', kind: 'stat', props: { value: 25 } })} complete />);+ view.rerender(+ <RichAnswer+ {...props}+ source={first + line(3, { op: 'create', id: 'price', kind: 'stat', props: { value: 25 } })}+ complete+ />,+ );expect(screen.queryByText('…')).toBeNull();expect(screen.getAllByText('25')).toHaveLength(2);view.rerender(<RichAnswer {...props} source={first} complete />);expect(screen.getByRole('status').textContent).toBe('richAnswer.calculationUnavailable');expect(screen.getByText('Existing explanation')).toBeTruthy();});++// Tier 1: the everyday chart acceptance showed an unlabeled polyline. A streamed+// data patch must update its visible point values, category labels and accessible data.+it('labels chart points in place and updates them when the model revises a value', () => {+ const source = line(1, {+ op: 'create',+ id: 'trend',+ kind: 'chart',+ props: {+ label: '收入(万元)',+ variant: 'line',+ data: [+ { label: '1月', value: 12 },+ { label: '2月', value: 18 },+ ],+ },+ });+ const props = { stateKey: 'chart-labels', renderMarkdown: (text: string) => <span>{text}</span> };+ const view = render(<RichAnswer {...props} source={source} complete={false} />);+ expect(screen.getByRole('img').getAttribute('aria-label')).toContain('1月: 12, 2月: 18');+ expect([...view.container.querySelectorAll('svg text')].map((n) => n.textContent)).toContain(+ '12',+ );+ expect(screen.getByText('2月')).toBeTruthy();+ view.rerender(+ <RichAnswer+ {...props}+ source={+ source ++ line(2, {+ op: 'patch',+ id: 'trend',+ props: {+ data: [+ { label: '1月', value: 12 },+ { label: '2月', value: -6 },+ ],+ },+ })+ }+ complete+ />,+ );+ expect(screen.getByRole('img').getAttribute('aria-label')).toContain('2月: -6');+ expect(view.container.querySelectorAll('circle')).toHaveLength(2);+ expect(view.container.querySelector('polyline')?.getAttribute('points')).not.toMatch(+ /NaN|Infinity/,+ );+});++// Tier 1: native icons must retain their text (including an unknown icon name),+// without interpreting a model-supplied name as a resource or action.+it('renders native icon explanations and keeps unknown icon text readable', () => {+ const source =+ line(1, {+ op: 'create',+ id: 'mail',+ kind: 'icon',+ props: { name: 'mail', label: '邮件', text: '收发工作消息' },+ }) ++ line(2, {+ op: 'create',+ id: 'other',+ kind: 'icon',+ props: { name: 'https://invalid.example/icon.svg', label: '未知入口', text: '保留说明' },+ });+ const view = render(+ <RichAnswer+ stateKey="icons"+ source={source}+ complete+ renderMarkdown={(text) => <span>{text}</span>}+ />,+ );+ expect(screen.getByText('邮件')).toBeTruthy();+ expect(screen.getByText('收发工作消息')).toBeTruthy();+ expect(screen.getByText('保留说明')).toBeTruthy();+ expect(view.container.querySelectorAll('svg')).toHaveLength(2);+ expect(view.container.querySelector('img, button, a')).toBeNull();+ expect(screen.queryByRole('status')).toBeNull();+});diff --git a/apps/desktop/src/renderer/components/chat/rich-answer.css b/apps/desktop/src/renderer/components/chat/rich-answer.cssindex eb75fad906..02977559a6 100644--- a/apps/desktop/src/renderer/components/chat/rich-answer.css+++ b/apps/desktop/src/renderer/components/chat/rich-answer.css@@ -154,3 +154,46 @@gap: var(--space-4);min-width: 0;}++.rich-answer-icon-row {+ display: flex;+ align-items: flex-start;+ gap: var(--space-3);+}+.rich-answer-icon-row > svg {+ flex-shrink: 0;+ margin-top: var(--space-1);+}+.rich-answer-icon-row > div {+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+}+.rich-answer-icon-row strong {+ font-weight: 500;+}+.rich-answer-chart-guide {+ stroke: var(--border-default);+}+.rich-answer-chart-axis {+ fill: var(--text-secondary);+ font-size: var(--text-xs);+}+.rich-answer-chart-value {+ fill: var(--text-primary);+ font-size: var(--text-xs);+}+.rich-answer-chart dl.rich-answer-chart-labels {+ flex-direction: row;+ gap: 0;+ margin-top: 0;+}+.rich-answer-chart-labels > div {+ flex: 1;+ min-width: 0;+ text-align: center;+ overflow-wrap: anywhere;+ font-size: var(--text-xs);+ color: var(--text-secondary);+}diff --git a/apps/mobile/src/session/RichAnswer.tsx b/apps/mobile/src/session/RichAnswer.tsxindex a1431097f0..e151168750 100644--- a/apps/mobile/src/session/RichAnswer.tsx+++ b/apps/mobile/src/session/RichAnswer.tsx@@ -1,3 +1,17 @@+import {+ Mail,+ CalendarDays,+ Folder,+ ChartColumn,+ Check,+ Info,+ Clock,+ MapPin,+ Coffee,+ Image,+ Users,+ Star,+} from "lucide-react-native";import AsyncStorage from "@react-native-async-storage/async-storage";import {Fragment,@@ -18,7 +32,7 @@ import {StyleSheet,type GestureResponderEvent,} from "react-native";-import Svg, { Polyline } from "react-native-svg";+import Svg, { Polyline, Line, Circle, Text as SvgText } from "react-native-svg";import { useTranslation } from "react-i18next";import { useAuth } from "@/auth/AuthContext";import {@@ -35,6 +49,7 @@ import {RichInteractionMemory,richAction,richChart,+ richLinePlot,richResolvedValues,richCalculationUnavailable,richLabel,@@ -47,6 +62,21 @@ import {type RichValue,} from "@cindy/maker-shared/rich-answer";+const answerIcons = {+ mail: Mail,+ calendar: CalendarDays,+ folder: Folder,+ chart: ChartColumn,+ check: Check,+ info: Info,+ clock: Clock,+ location: MapPin,+ coffee: Coffee,+ image: Image,+ users: Users,+ star: Star,+};+const memory = new RichInteractionMemory({async read() {return AsyncStorage.getItem("cindy.richAnswer.viewState.v1");@@ -87,7 +117,9 @@ function RichDocumentView({);useEffect(() => {void memory.load();- const subscription = AppState.addEventListener('change', state => { if (state !== 'active') void memory.flush(); });+ const subscription = AppState.addEventListener("change", (state) => {+ if (state !== "active") void memory.flush();+ });return () => {subscription.remove();void memory.flush();@@ -114,13 +146,18 @@ function RichDocumentView({const render = (id: string): ReactNode => {const node = doc.nodes.get(id);if (!node) return null;- if (richCalculationUnavailable(node, values)) return <Text style={styles.caption}>{complete ? t("message.richAnswer.calculationUnavailable") : '…'}</Text>;+ if (richCalculationUnavailable(node, values))+ return (+ <Text style={styles.caption}>+ {complete ? t("message.richAnswer.calculationUnavailable") : "…"}+ </Text>+ );const bind = richString(node, "bind", id),label = richString(node, "label");const children = node.children.map((child) => (<Fragment key={child}>{render(child)}</Fragment>));- if ((["image", "video", "audio"].includes(node.kind)) && renderMedia)+ if (["image", "video", "audio"].includes(node.kind) && renderMedia)return (<View style={styles.content}>{renderMedia(node)}@@ -150,6 +187,28 @@ function RichDocumentView({{richLabel(node, values)}</Text>);+ case "icon": {+ const name = richString(node, "name");+ const Icon = Object.prototype.hasOwnProperty.call(answerIcons, name)+ ? answerIcons[name as keyof typeof answerIcons]+ : Info;+ return (+ <View style={styles.iconRow}>+ <Icon+ size={20}+ strokeWidth={1.75}+ color={colors.textPrimary}+ accessible={false}+ />+ <View style={styles.iconBody}>+ <Text style={styles.iconTitle}>{label || name}</Text>+ {richString(node, "text") ? (+ <Text style={styles.text}>{richString(node, "text")}</Text>+ ) : null}+ </View>+ </View>+ );+ }case "divider":return <View style={styles.divider} />;case "stack":@@ -325,43 +384,30 @@ function RichDocumentView({<View style={styles.stack}><Text style={styles.text}>{label}</Text>{richString(node, "variant") === "line" ? (- <Svg- accessibilityLabel={label}- width="100%"- height={160}- viewBox="0 0 480 180"- >- <Polyline- fill="none"- stroke={colors.textPrimary}- strokeWidth={2}- points={data- .map(- (item, i) =>- `${10 + (i / Math.max(1, data.length - 1)) * 460},${170 - ((item.value - min) / span) * 160}`,- )- .join(" ")}- />- </Svg>+ <AnswerLineChart data={data} label={label} />) : null}- {data.map((item, index) => (- <View key={index}>- <View style={styles.labelRow}>- <Text style={styles.caption}>{item.label}</Text>- <Text style={styles.caption}>{item.value}</Text>- </View>- {richString(node, "variant") !== "line" ? (- <View style={styles.track}>- <View- style={[- styles.bar,- { marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`, width: `${(Math.abs(item.value) / span) * 100}%` },- ]}- />+ {richString(node, "variant") !== "line" &&+ data.map((item, index) => (+ <View key={index}>+ <View style={styles.labelRow}>+ <Text style={styles.caption}>{item.label}</Text>+ <Text style={styles.caption}>{item.value}</Text></View>- ) : null}- </View>- ))}+ {richString(node, "variant") !== "line" ? (+ <View style={styles.track}>+ <View+ style={[+ styles.bar,+ {+ marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`,+ width: `${(Math.abs(item.value) / span) * 100}%`,+ },+ ]}+ />+ </View>+ ) : null}+ </View>+ ))}</View>);}@@ -384,6 +430,100 @@ function RichDocumentView({</View>);}+function AnswerLineChart({+ data,+ label,+}: {+ data: { label: string; value: number }[];+ label: string;+}) {+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const [width, setWidth] = useState(320);+ const plot = richLinePlot(data, width);+ return (+ <View onLayout={(e) => setWidth(e.nativeEvent.layout.width)}>+ <Svg+ width="100%"+ height={plot.height}+ viewBox={`0 0 ${plot.width} ${plot.height}`}+ accessible+ accessibilityLabel={`${label}. ${data.map((item) => `${item.label}: ${item.value}`).join(", ")}`}+ >+ {plot.ticks.map((tick) => (+ <Fragment key={tick.value}>+ <Line+ x1={plot.left}+ x2={plot.width - plot.right}+ y1={tick.y}+ y2={tick.y}+ stroke={colors.border}+ />+ <SvgText+ x={plot.left - 6}+ y={tick.y + 4}+ textAnchor="end"+ fontSize={textStyles.footnote.fontSize}+ fill={colors.textSecondary}+ >+ {Number(tick.value.toPrecision(3))}+ </SvgText>+ </Fragment>+ ))}+ <Polyline+ fill="none"+ stroke={colors.textPrimary}+ strokeWidth={2}+ points={plot.points.map((p) => `${p.x},${p.y}`).join(" ")}+ />+ {plot.points.map((p, i) => (+ <Fragment key={i}>+ <Circle cx={p.x} cy={p.y} r={3} fill={colors.textPrimary} />+ {plot.showValues ? (+ <SvgText+ x={p.x}+ y={p.y - 10}+ textAnchor="middle"+ fontSize={textStyles.footnote.fontSize}+ fill={colors.textPrimary}+ >+ {p.value}+ </SvgText>+ ) : null}+ </Fragment>+ ))}+ </Svg>+ <View+ style={[+ data.length <= 8 ? styles.chartLabels : styles.stack,+ data.length <= 8 && {+ paddingLeft: plot.left,+ paddingRight: plot.right,+ },+ ]}+ >+ {data.map((item, i) => (+ <View+ key={i}+ style={data.length <= 8 ? styles.chartLabel : styles.labelRow}+ >+ <Text+ style={[+ styles.caption,+ data.length <= 8 && styles.chartLabelText,+ ]}+ >+ {item.label}+ </Text>+ {!plot.showValues ? (+ <Text style={styles.caption}>{item.value}</Text>+ ) : null}+ </View>+ ))}+ </View>+ </View>+ );+}function AnswerRange({node,value,@@ -452,6 +592,20 @@ function AnswerRange({}const makeStyles = (colors: ThemeColors) =>StyleSheet.create({+ iconRow: {+ flexDirection: "row",+ alignItems: "flex-start",+ gap: spacing.md,+ },+ iconBody: { flex: 1, gap: spacing.xs, minWidth: 0 },+ iconTitle: {+ ...textStyles.bodyLarge,+ color: colors.textPrimary,+ fontWeight: fontWeight.medium,+ },+ chartLabels: { flexDirection: "row" },+ chartLabel: { flex: 1, minWidth: 0 },+ chartLabelText: { textAlign: "center" },stack: { gap: spacing.lg, minWidth: 0 },content: { minWidth: 0, flexShrink: 1 },row: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },diff --git a/docs/images/rich-answers/desktop-charts.png b/docs/images/rich-answers/desktop-charts.pngnew file mode 100644index 0000000000..16aa5b7887Binary files /dev/null and b/docs/images/rich-answers/desktop-charts.png differdiff --git a/docs/images/rich-answers/desktop-icons.png b/docs/images/rich-answers/desktop-icons.pngnew file mode 100644index 0000000000..211faa5c93Binary files /dev/null and b/docs/images/rich-answers/desktop-icons.png differdiff --git a/docs/images/rich-answers/desktop-illustrated.png b/docs/images/rich-answers/desktop-illustrated.pngnew file mode 100644index 0000000000..81d92688c2Binary files /dev/null and b/docs/images/rich-answers/desktop-illustrated.png differdiff --git a/docs/images/rich-answers/mobile-charts-light.png b/docs/images/rich-answers/mobile-charts-light.pngnew file mode 100644index 0000000000..73023e2c56Binary files /dev/null and b/docs/images/rich-answers/mobile-charts-light.png differdiff --git a/docs/images/rich-answers/mobile-icons-dark.png b/docs/images/rich-answers/mobile-icons-dark.pngnew file mode 100644index 0000000000..2293509dedBinary files /dev/null and b/docs/images/rich-answers/mobile-icons-dark.png differdiff --git a/docs/images/rich-answers/mobile-illustrated-light.png b/docs/images/rich-answers/mobile-illustrated-light.pngnew file mode 100644index 0000000000..9ec3903b24Binary files /dev/null and b/docs/images/rich-answers/mobile-illustrated-light.png differdiff --git a/docs/rich-answers.md b/docs/rich-answers.mdindex 4e1cfa0d78..b48b27792d 100644--- a/docs/rich-answers.md+++ b/docs/rich-answers.md@@ -38,6 +38,14 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到旧完整 HTML 预览路径已移除,其旧验收不覆盖本实现。送审不代表跨设备补充验收已完成;合并/发布前仍须补齐上面列明的相关场景。+## 日常正文补充验收(2026-10-18)++按用户纠正,新增 15 次真实 maker 调用:照片图文、图标说明、数据简报各 3 种 Harness,加上原生线条图标与图表修正后的 6 次复测。请求只描述用户要看的内容,没有指定组件协议或手写模型答案。14 份组件正文解析无错误;Pi 的首次图标说明采用普通 Markdown + emoji,属于有效简洁输出。明确要求线条图标后,三种 Harness 均选中 mail/calendar/folder/chart 四个原生图标。三份图文均加载 coffee/park/art 三张真实照片;六组图表(折线 + 条形)全部 60 个数值与输入一致。++实测发现并修复:折线图原先只有线,必须对照下方列表才能读数;现有共享坐标计算,桌面与手机都直接展示刻度、点值和类别。补充原生线条图标,未知名称保留文字并使用通用图标,不加载任意资源。两项生产渲染入口回归通过,包含流式数据修改后的标签和可读结果(组件 5/5,2.16s);共享 85 项、两端类型检查、测试卫生检查通过。这里只扩展已授权公共能力说明中的图标与图表属性,没有新增模型后处理。++桌面浅/深色各查看 15 份实际结果,没有解析提示或横向溢出。iPhone 浅/深色回放图文、原生图标与修正图表的三 Harness 结果。六次复测均记录到模型尚未结束时已显示的正文组件。手机照片通过本机测试 HTTP 映射读取,明确不当作跨设备媒体取件已通过。调试版沿用的导航弃用与 Reanimated 警告已留在运行记录,截图时收起调试提示,没有修改生产日志规则。+## 界面证据真实模型费用比较,12 个月并开启服务;宿主原生组件显示 300 / 240、省 60。图片只含本任务合成测试内容。@@ -47,3 +55,13 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到| iOS 浅色(原生回放) | iOS 深色(原生回放) || --- | --- ||  |  |++### 常见输出(真实模型生成)++++++| iOS 图文 | iOS 原生图标(深色) | iOS 数据图 |+| --- | --- | --- |+|  |  |  |diff --git a/packages/maker-shared/src/richAnswer.ts b/packages/maker-shared/src/richAnswer.tsindex 11fa999b17..ab40f36f6b 100644--- a/packages/maker-shared/src/richAnswer.ts+++ b/packages/maker-shared/src/richAnswer.ts@@ -4,6 +4,7 @@ export const RICH_ANSWER_KINDS = ["text","markdown","heading",+ "icon","stack","row","grid",@@ -388,18 +389,34 @@ export function richDefaults(}/** Resolve inputs and calculated node references from one document snapshot.* Forward references are supported; cycles and missing values stay unavailable. */-export function richResolvedValues(document: RichDocument, edited: RichValues = {}): RichValues {- const values: Record<string, RichValue | undefined> = { ...richDefaults(document), ...edited };+export function richResolvedValues(+ document: RichDocument,+ edited: RichValues = {},+): RichValues {+ const values: Record<string, RichValue | undefined> = {+ ...richDefaults(document),+ ...edited,+ };const visiting = new Set<string>();const resolve = (id: string): RichValue | undefined => {if (own(values, id)) return values[id];if (visiting.has(id) || visiting.size >= MAX_DEPTH) return undefined;const node = document.nodes.get(id);- if (!node || !["stat", "text", "heading"].includes(node.kind)) return undefined;+ if (!node || !["stat", "text", "heading"].includes(node.kind))+ return undefined;visiting.add(id);- const result = richEvaluate(node.props.value ?? node.props.text, values, 0, resolve);+ const result = richEvaluate(+ node.props.value ?? node.props.text,+ values,+ 0,+ resolve,+ );visiting.delete(id);- Object.defineProperty(values, id, { value: result, enumerable: true, configurable: true });+ Object.defineProperty(values, id, {+ value: result,+ enumerable: true,+ configurable: true,+ });return result;};for (const node of document.nodes.values()) resolve(node.id);@@ -423,59 +440,110 @@ export function richEvaluate(if (expr.op === "if") {if (expr.args.length !== 3) return undefined;const condition = evaluate(expr.args[0]);- return condition === undefined ? undefined : evaluate(expr.args[condition ? 1 : 2]);+ return condition === undefined+ ? undefined+ : evaluate(expr.args[condition ? 1 : 2]);}const args = expr.args.map(evaluate);- if (args.some(x => x === undefined)) return undefined;+ if (args.some((x) => x === undefined)) return undefined;if (expr.op === "concat") {// Computed references may share and repeatedly double strings. Bound the// result before allocating it, just like an individual node props payload.- if (args.reduce<number>((size, arg) => size + String(arg).length, 0) > 65_536) return undefined;+ if (+ args.reduce<number>((size, arg) => size + String(arg).length, 0) > 65_536+ )+ return undefined;return args.join("");}- if (["eq", "lt", "gt", "sub", "div"].includes(String(expr.op)) && args.length !== 2) return undefined;+ if (+ ["eq", "lt", "gt", "sub", "div"].includes(String(expr.op)) &&+ args.length !== 2+ )+ return undefined;if (expr.op === "eq") return args[0] === args[1];- if (args.length === 0 || args.some(x => typeof x === "string" && !x.trim())) return undefined;+ if (args.length === 0 || args.some((x) => typeof x === "string" && !x.trim()))+ return undefined;const nums = args.map(Number);if (!nums.every(Number.isFinite)) return undefined;let result: number;switch (expr.op) {- case "add": result = nums.reduce((a, b) => a + b, 0); break;- case "mul": result = nums.reduce((a, b) => a * b, 1); break;- case "sub": result = nums[0] - nums[1]; break;- case "div": result = nums[0] / nums[1]; break;- case "min": result = Math.min(...nums); break;- case "max": result = Math.max(...nums); break;- case "lt": return nums[0] < nums[1];- case "gt": return nums[0] > nums[1];- default: return undefined;+ case "add":+ result = nums.reduce((a, b) => a + b, 0);+ break;+ case "mul":+ result = nums.reduce((a, b) => a * b, 1);+ break;+ case "sub":+ result = nums[0] - nums[1];+ break;+ case "div":+ result = nums[0] / nums[1];+ break;+ case "min":+ result = Math.min(...nums);+ break;+ case "max":+ result = Math.max(...nums);+ break;+ case "lt":+ return nums[0] < nums[1];+ case "gt":+ return nums[0] > nums[1];+ default:+ return undefined;}return Number.isFinite(result) ? result : undefined;}-export function richValue(node: RichNode, values: RichValues): RichValue | undefined {+export function richValue(+ node: RichNode,+ values: RichValues,+): RichValue | undefined {return richEvaluate(node.props.value ?? node.props.text ?? "", values);}export function richLabel(node: RichNode, values: RichValues): string {const result = richValue(node, values);- return result === undefined ? "—" : richString(node, "prefix") + String(result) + richString(node, "suffix");+ return result === undefined+ ? "—"+ : richString(node, "prefix") + String(result) + richString(node, "suffix");}/** Component-local pending/error display; unaffected prose and controls remain usable. */-export function richCalculationUnavailable(node: RichNode, values: RichValues): boolean {- if (["stat", "text", "heading"].includes(node.kind)) return richValue(node, values) === undefined;- return node.kind === "chart" && Array.isArray(node.props.data) && node.props.data.some(item => {- if (!record(item)) return true;- const result = richEvaluate(item.value, values);- return result === undefined || (typeof result === "string" && !result.trim()) || !Number.isFinite(Number(result));- });+export function richCalculationUnavailable(+ node: RichNode,+ values: RichValues,+): boolean {+ if (["stat", "text", "heading"].includes(node.kind))+ return richValue(node, values) === undefined;+ return (+ node.kind === "chart" &&+ Array.isArray(node.props.data) &&+ node.props.data.some((item) => {+ if (!record(item)) return true;+ const result = richEvaluate(item.value, values);+ return (+ result === undefined ||+ (typeof result === "string" && !result.trim()) ||+ !Number.isFinite(Number(result))+ );+ })+ );}-export function richAction(node: RichNode, values: RichValues): Record<string, RichValue> {+export function richAction(+ node: RichNode,+ values: RichValues,+): Record<string, RichValue> {const action = node.props.set;if (!record(action)) return {};const changes: Record<string, RichValue> = {};- for (const [key, expr] of Object.entries(action).filter(([key]) => ID.test(key)).slice(0, 100)) {+ for (const [key, expr] of Object.entries(action)+ .filter(([key]) => ID.test(key))+ .slice(0, 100)) {const result = richEvaluate(expr, values);if (result === undefined) return {}; // an invalid form cannot partially apply- Object.defineProperty(changes, key, { value: result, enumerable: true, configurable: true });+ Object.defineProperty(changes, key, {+ value: result,+ enumerable: true,+ configurable: true,+ });}return changes;}@@ -593,7 +661,11 @@ export class RichInteractionMemory {}flushSync(): void {clearTimeout(this.timer);- try { this.storage?.writeSync?.(this.serialize()); } catch { /* Storage unavailable: keep in-memory values. */ }+ try {+ this.storage?.writeSync?.(this.serialize());+ } catch {+ /* Storage unavailable: keep in-memory values. */+ }}async flush(): Promise<void> {clearTimeout(this.timer);@@ -625,6 +697,39 @@ export function richChart(.filter((item) => Number.isFinite(item.value)): [];}++/** Shared plot coordinates keep native and desktop charts aligned with the same data. */+export function richLinePlot(+ data: { label: string; value: number }[],+ width: number,+) {+ const w = Math.max(180, width),+ left = 36,+ right = 12,+ top = 26,+ bottom = 146;+ const min = Math.min(0, ...data.map((item) => item.value));+ const max = Math.max(0, ...data.map((item) => item.value));+ const scale = Math.max(Math.abs(min), Math.abs(max), 1);+ const span = max / scale - min / scale || 1;+ const y = (v: number) =>+ bottom - ((v / scale - min / scale) / span) * (bottom - top);+ return {+ width: w,+ height: 164,+ left,+ right,+ ticks: [min, min / 2 + max / 2, max]+ .filter((v, i, all) => all.indexOf(v) === i)+ .map((value) => ({ value, y: y(value) })),+ points: data.map((item, i) => ({+ ...item,+ x: left + ((i + 0.5) / Math.max(1, data.length)) * (w - left - right),+ y: y(item.value),+ })),+ showValues: data.length <= Math.floor((w - left - right) / 35),+ };+}export function richRange(node: RichNode,current: unknown,@@ -664,6 +769,10 @@ export function richAnswerText(source: string): string {.filter(Boolean).join("\n\n");if (node.kind === "heading") return `### ${richLabel(node, values)}`;+ if (node.kind === "icon")+ return [richString(node, "label"), richString(node, "text")]+ .filter(Boolean)+ .join("\n");if (node.kind === "text") return richLabel(node, values);if (node.kind === "divider") return "---";if (node.kind === "stat")diff --git a/packages/maker-shared/src/richAnswerGuide.ts b/packages/maker-shared/src/richAnswerGuide.tsindex d244630458..3cfa61e7ed 100644--- a/packages/maker-shared/src/richAnswerGuide.ts+++ b/packages/maker-shared/src/richAnswerGuide.ts@@ -12,12 +12,13 @@ Each block starts seq=1 and increments by one. Its first operation has version:1Components and props (no arbitrary HTML, CSS, scripts or tool access):- text/heading: text; markdown: text supports lists/tables/links.+- icon: name (mail, calendar, folder, chart, check, info, clock, location, coffee, image, users, star), label, text?. A small native line icon with a title and optional description. Use for icon-led explanations; no buttons or actions.- stack/group: vertical children. row/grid: columns 1–3; grid layout:"aside" for image + text. Containers combine freely and adapt to the available width.- divider.- image/video/audio: src (existing managed reference, URL or task file), alt, caption. Reuse actual media; never invent asset URLs or embed base64 data.- code: text, language. math: text (LaTeX). diagram: text (Mermaid).- stat: label, value, prefix?, suffix?.-- chart: label, variant:"bar"|"line", data:[{label,value}].+- chart: label (include unit), variant:"bar"|"line", data:[{label,value}]. Data labels are short categories/dates; values are drawn separately, so do not repeat them in labels. Line charts include axis guides and point values; bar charts label every bar.- range: label, bind?, min,max,step,default,suffix?. input: label,bind?,default,placeholder. check: label,bind?,default boolean. select: label,bind?,default,options:[{label,value}].- details: label,default boolean,children. tabs: children are containers with label; default is selected child id.- button/form: label,set:{stateKey:expression}. Button or form submit only changes local UI values. It does not execute tools, navigate, or send messages.@@ -32,7 +33,6 @@ Example (each object is one line within the cindy-ui block):Keep blocks under 128 KB, with no more than 2048 nodes and depth 32. Finish each line before starting the next. Media loads via the existing host path. Interrupted output keeps committed nodes; incomplete lines wait for completion. Unknown or malformed operations show a local readable fallback, never execute code. New Cindy clients render components; older clients may show the fenced source. Use Markdown when the receiving channel does not support components.`;-/** Host addition only: native CLI instructions and execution remain unchanged. */export const ANSWER_DELIVERY_PROMPT = `## Cindy answer deliveryDeliver your answer directly in the conversation, respecting the user's current request and saved presentation preferences already in your context. These delivery capabilities apply equally to ordinary tasks and companions. They do not change how you execute tasks, use tools, or finish a turn.