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。

feat(chat): keep rich answer colors with Cindy across devices and modes

Chris822e528ade3e
diff --git a/apps/desktop/src/renderer/components/chat/RichAnswer.tsx b/apps/desktop/src/renderer/components/chat/RichAnswer.tsx
index 37629ab964..1a89f37bf9 100644
--- a/apps/desktop/src/renderer/components/chat/RichAnswer.tsx
+++ b/apps/desktop/src/renderer/components/chat/RichAnswer.tsx
@@ -45,6 +45,7 @@ import {
richRange,
richString,
type RichNode,
+ type RichPalette,
type RichValue,
} from '@cindy/maker-shared/rich-answer';
import { useAuth } from '@/contexts/AuthContext';
@@ -53,10 +54,15 @@ import { Input } from '@/components/ui/input';
import { Slider } from '@/components/ui/slider';
import './rich-answer.css';
-const subscribeTheme = (listener: () => void) => {
- const observer = new MutationObserver(listener);
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
- return () => observer.disconnect();
+/** Answer colors are Cindy theme tokens, so they follow the mode without re-rendering. */
+const palette: RichPalette = {
+ primary: 'var(--text-primary)',
+ secondary: 'var(--text-secondary)',
+ tertiary: 'var(--text-tertiary)',
+ success: 'var(--status-success)',
+ warning: 'var(--warning-fg)',
+ danger: 'var(--error-fg)',
+ border: 'var(--border-default)',
};
const answerIcons = {
mail: Mail,
@@ -124,10 +130,6 @@ function RichAnswerDocument({
renderMarkdown: (source: string, id: string) => ReactNode;
}) {
const { t } = useTranslation();
- const dark = useSyncExternalStore(subscribeTheme, () =>
- document.documentElement.classList.contains('dark'),
- );
-
const parser = useRef(new RichAnswerStream());
const doc = useMemo(() => parser.current.update(source, complete), [source, complete]);
const edited = useSyncExternalStore(memory.subscribe, () => memory.get(stateKey));
@@ -147,12 +149,15 @@ function RichAnswerDocument({
const node = doc.nodes.get(id);
if (!node) return null;
const result = renderContent(id),
- visual = richVisualStyle(node, dark);
+ visual = richVisualStyle(node, palette);
if (!isValidElement(result) || !Object.keys(visual).length) return result;
const element = result as ReactElement<{ style?: CSSProperties }>;
const media = ['image', 'video', 'audio'].includes(node.kind);
const box = { ...visual };
if (media) for (const key of ['height', 'minHeight', 'maxHeight']) delete box[key];
+ // The same answer is read on phones: fixed widths never exceed the available width.
+ if (typeof box.width === 'number' && box.maxWidth === undefined) box.maxWidth = '100%';
+ if (typeof box.minWidth === 'number') box.minWidth = `min(${box.minWidth}px, 100%)`;
const variables: Record<string, string | number> = {};
for (const [key, value] of Object.entries(visual))
variables[`--rich-${key}`] =
@@ -206,16 +211,18 @@ function RichAnswerDocument({
);
switch (node.kind) {
case 'svg': {
- const vector = richVector(node, dark);
+ const vector = richVector(node, palette);
return (
<svg
role="img"
aria-label={label || richString(node, 'alt')}
viewBox={vector.viewBox}
- style={{ width: '100%', height: 'auto', display: 'block' }}
+ // Unpainted shapes take the host text color instead of SVG's default black.
+ style={{ width: '100%', height: 'auto', display: 'block', fill: 'currentColor' }}
>
- {vector.shapes.map((shape, index) =>
- createElement(shape.type, { ...shape.props, key: index }, shape.text),
+ {vector.shapes.map(({ type, props: { fill, stroke, ...props }, text }, index) =>
+ // Theme tokens only resolve as CSS, not as SVG presentation attributes.
+ createElement(type, { ...props, style: { fill, stroke }, key: index }, text),
)}
</svg>
);
@@ -417,7 +424,12 @@ function RichAnswerDocument({
<figure className="rich-answer-chart">
<figcaption>{label}</figcaption>
{richString(node, 'variant') === 'line' ? (
- <AnswerLineChart data={data} label={label} node={node} dark={dark} />
+ <AnswerLineChart
+ data={data}
+ label={label}
+ node={node}
+ color={richColor(node.props.color, palette)}
+ />
) : null}
{richString(node, 'variant') !== 'line' && (
<dl>
@@ -432,8 +444,8 @@ function RichAnswerDocument({
<div
style={{
backgroundColor:
- richColor((node.props.colors as unknown[])?.[i], dark) ??
- richColor(node.props.color, dark),
+ richColor((node.props.colors as unknown[])?.[i], palette) ??
+ richColor(node.props.color, palette),
marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`,
width: `${(Math.abs(item.value) / span) * 100}%`,
}}
@@ -469,12 +481,12 @@ function AnswerLineChart({
data,
label,
node,
- dark,
+ color = 'currentColor',
}: {
data: { label: string; value: number }[];
label: string;
node: RichNode;
- dark: boolean;
+ color?: string;
}) {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(480);
@@ -515,8 +527,7 @@ function AnswerLineChart({
</Fragment>
))}
<polyline
- fill="none"
- stroke={richColor(node.props.color, dark) ?? 'currentColor'}
+ style={{ fill: 'none', stroke: color }}
strokeWidth={richNumber(node, 'strokeWidth', 2)}
points={plot.points.map((p) => `${p.x},${p.y}`).join(' ')}
/>
@@ -538,7 +549,7 @@ function AnswerLineChart({
cx={p.x}
cy={p.y}
r={richNumber(node, 'pointRadius', 3)}
- fill={richColor(node.props.color, dark) ?? 'currentColor'}
+ style={{ fill: color }}
/>
)}
{plot.showValues && (
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
index 5c15dd92fa..b3f51512d2 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
@@ -188,7 +188,7 @@ it('renders model styling and vector geometry and applies a local visual patch',
op: 'create',
id: 'title',
kind: 'heading',
- props: { text: '自由排版', style: { color: '#2457a7', fontSize: 32 } },
+ props: { text: '自由排版', style: { color: 'secondary', fontSize: 32 } },
}) +
line(2, {
op: 'create',
@@ -198,7 +198,7 @@ it('renders model styling and vector geometry and applies a local visual patch',
label: '自绘图',
viewBox: [0, 0, 400, 200],
shapes: [
- { type: 'path', d: 'M 0 100 L 400 20', stroke: '#2457a7', strokeWidth: 4 },
+ { type: 'path', d: 'M 0 100 L 400 20', stroke: 'success', strokeWidth: 4 },
{ type: 'text', x: 10, y: 20, text: '模型标注' },
{ type: 'script', text: 'alert(1)' },
],
@@ -210,16 +210,16 @@ it('renders model styling and vector geometry and applies a local visual patch',
};
const view = render(<RichAnswer {...props} source={source} complete={false} />);
expect(screen.getByText('自由排版').style.fontSize).toBe('32px');
- expect(screen.getByLabelText('自绘图').querySelector('path')?.getAttribute('stroke')).toBe(
- '#2457a7',
+ expect(screen.getByLabelText('自绘图').querySelector('path')?.style.stroke).toBe(
+ 'var(--status-success)',
);
expect(screen.getByLabelText('自绘图').querySelector('script')).toBeNull();
const updated =
source +
- line(3, { op: 'patch', id: 'title', props: { style: { color: '#98346a', fontSize: 24 } } });
+ line(3, { op: 'patch', id: 'title', props: { style: { color: 'danger', fontSize: 24 } } });
view.rerender(<RichAnswer {...props} source={updated} complete />);
expect(screen.getByText('自由排版').style.fontSize).toBe('24px');
- expect(screen.getByText('自由排版').style.color).toBe('rgb(152, 52, 106)');
+ expect(screen.getByText('自由排版').style.color).toBe('var(--error-fg)');
});
// Tier 1: real model output used a unitless line-height and stock data whose
@@ -294,3 +294,18 @@ it('loads a site player on demand, retains its source link and disposes it on re
view.unmount();
expect(document.querySelector('webview')).toBeNull();
});
+
+// Unit: an answer designed on a desktop is also read on a phone, and colors belong to Cindy:
+// wide fixed boxes stay in bounds and model backgrounds or literal colors are not painted.
+it('bounds fixed widths and leaves backgrounds and literal colors to the host', () => {
+ const source =
+ line(1, { op: 'create', id: 'card', kind: 'stack', props: { style: { backgroundColor: '#14161b', width: 720, minWidth: 480 } } }) +
+ line(2, { op: 'create', id: 'faint', kind: 'text', parent: 'card', props: { text: 'Faint', style: { color: { light: '#222', dark: '#222' } } } });
+ render(<RichAnswer stateKey="bounds" source={source} complete renderMarkdown={(text) => <span>{text}</span>} />);
+ const card = screen.getByText('Faint').parentElement!;
+ expect(card.style.backgroundColor).toBe('');
+ expect(card.style.maxWidth).toBe('100%');
+ expect(card.style.minWidth).toBe('min(480px, 100%)');
+ expect(screen.getByText('Faint').style.color).toBe('');
+});
+
diff --git a/apps/mobile/src/session/RichAnswer.tsx b/apps/mobile/src/session/RichAnswer.tsx
index 7a8b76f78c..9bc78408ca 100644
--- a/apps/mobile/src/session/RichAnswer.tsx
+++ b/apps/mobile/src/session/RichAnswer.tsx
@@ -79,9 +79,21 @@ import {
richRange,
richString,
type RichNode,
+ type RichPalette,
type RichValue,
} from "@cindy/maker-shared/rich-answer";
+/** Answer colors are Cindy theme colors; the model only names a role. */
+const richPalette = (colors: ThemeColors): RichPalette => ({
+ primary: colors.textPrimary,
+ secondary: colors.textSecondary,
+ tertiary: colors.textTertiary,
+ success: colors.statusDone,
+ warning: colors.warningFg,
+ danger: colors.statusError,
+ border: colors.border,
+});
+
const answerIcons = {
mail: Mail,
calendar: CalendarDays,
@@ -125,7 +137,9 @@ function RichDocumentView({
renderMedia,
}: Props) {
const { t } = useTranslation();
- const { colors, mode } = useTheme();
+ const { colors } = useTheme();
+ const palette = richPalette(colors);
+ const [rootWidth, setRootWidth] = useState(0);
const baseStyles = useThemedStyles(makeStyles);
const styles = baseStyles;
const parser = useRef(new RichAnswerStream());
@@ -156,7 +170,7 @@ function RichDocumentView({
const render = (id: string, inherited: TextStyle = {}): ReactNode => {
const node = doc.nodes.get(id);
if (!node) return null;
- const visual = richVisualStyle(node, mode === "dark");
+ const visual = richVisualStyle(node, palette);
const textStyle: TextStyle = { ...inherited };
const viewStyle: ViewStyle = {};
for (const [key, value] of Object.entries(visual)) {
@@ -181,6 +195,13 @@ function RichDocumentView({
delete viewStyle.minHeight;
delete viewStyle.maxHeight;
}
+ // Answers written on a desktop are read here too: fixed widths stay within the screen.
+ if (typeof viewStyle.width === "number" && viewStyle.maxWidth === undefined)
+ viewStyle.maxWidth = "100%";
+ if (typeof viewStyle.minWidth === "number")
+ viewStyle.minWidth = rootWidth
+ ? Math.min(viewStyle.minWidth, rootWidth)
+ : undefined;
const result = renderContent(id, textStyle);
if (!isValidElement(result)) return result;
const element = result as ReactElement<{
@@ -259,7 +280,7 @@ function RichDocumentView({
);
switch (node.kind) {
case "svg":
- return <AnswerVector node={node} dark={mode === "dark"} />;
+ return <AnswerVector node={node} palette={palette} />;
case "text":
case "heading":
return (
@@ -302,7 +323,7 @@ function RichDocumentView({
return (
<AnswerLayout
node={node}
- dark={mode === "dark"}
+ palette={palette}
renderChild={(child) => render(child, textStyle)}
/>
);
@@ -461,9 +482,9 @@ function RichDocumentView({
backgroundColor:
richColor(
(node.props.colors as unknown[])?.[index],
- mode === "dark",
+ palette,
) ??
- richColor(node.props.color, mode === "dark") ??
+ richColor(node.props.color, palette) ??
colors.textSecondary,
marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`,
width: `${(Math.abs(item.value) / span) * 100}%`,
@@ -482,7 +503,11 @@ function RichDocumentView({
}
};
return (
- <View testID="message.richAnswer" style={styles.stack}>
+ <View
+ testID="message.richAnswer"
+ style={styles.stack}
+ onLayout={(e) => setRootWidth(e.nativeEvent.layout.width)}
+ >
{doc.roots.map((id) => (
<Fragment key={id}>{render(id)}</Fragment>
))}
@@ -494,15 +519,15 @@ function RichDocumentView({
}
function AnswerVector({
node,
- dark,
+ palette,
style,
}: {
node: RichNode;
- dark: boolean;
+ palette: RichPalette;
style?: StyleProp<ViewStyle>;
}) {
const [width, setWidth] = useState(0);
- const vector = richVector(node, dark);
+ const vector = richVector(node, palette);
const dims = vector.viewBox.split(" ").map(Number);
const box = StyleSheet.flatten(style) ?? {};
const height = Math.min(
@@ -528,6 +553,8 @@ function AnswerVector({
width="100%"
height={height}
viewBox={vector.viewBox}
+ // Unpainted shapes take the host text color instead of SVG's default black.
+ fill={palette.primary}
accessibilityLabel={richString(node, "label", richString(node, "alt"))}
>
{vector.shapes.map((shape, index) =>
@@ -543,17 +570,17 @@ function AnswerVector({
}
function AnswerLayout({
node,
- dark,
+ palette,
renderChild,
style,
}: {
node: RichNode;
- dark: boolean;
+ palette: RichPalette;
renderChild: (id: string) => ReactNode;
style?: StyleProp<ViewStyle>;
}) {
const [width, setWidth] = useState(0);
- const visual = richVisualStyle(node, dark);
+ const visual = richVisualStyle(node, palette);
const aside = richString(node, "layout") === "aside";
const mobile = width <= 600 && !aside;
const weights = Array.isArray(node.props.weights)
@@ -618,7 +645,9 @@ function AnswerLineChart({
label: string;
node: RichNode;
}) {
- const { colors, mode } = useTheme();
+ const { colors } = useTheme();
+ const color =
+ richColor(node.props.color, richPalette(colors)) ?? colors.textPrimary;
const styles = useThemedStyles(makeStyles);
const [width, setWidth] = useState(320);
const plot = richLinePlot(data, width, node.props);
@@ -655,9 +684,7 @@ function AnswerLineChart({
))}
<Polyline
fill="none"
- stroke={
- richColor(node.props.color, mode === "dark") ?? colors.textPrimary
- }
+ stroke={color}
strokeWidth={richNumber(node, "strokeWidth", iconStroke.regular)}
points={plot.points.map((p) => `${p.x},${p.y}`).join(" ")}
/>
@@ -680,10 +707,7 @@ function AnswerLineChart({
cx={p.x}
cy={p.y}
r={richNumber(node, "pointRadius", 3)}
- fill={
- richColor(node.props.color, mode === "dark") ??
- colors.textPrimary
- }
+ fill={color}
/>
)}
{plot.showValues ? (
diff --git a/docs/rich-answers.md b/docs/rich-answers.md
index c93c430a12..9a94920e55 100644
--- a/docs/rich-answers.md
+++ b/docs/rich-answers.md
@@ -10,6 +10,14 @@
Desktop 使用原生 React 组件;Mobile 使用原生 View/Text 与既有媒体组件,不新增原生依赖或 runtime fingerprint。浅深主题取各端语义 token,窄屏按可用宽度换行。
+### 跨端与双模式
+
+同一份答案会在桌面消息列(约 560–900 px)与手机(约 320–430 px)上阅读,常在一台设备生成、另一台查看,并在生成后随时切换浅深色。公共交付说明直接告诉模型这一点:按 320 px 可读设计,不假设当前设备或模式。
+
+2026-10-18 用户裁决:背景色与文字颜色由 Cindy 限定,避免答案花哨或出现与界面割裂的黑白反差。模型负责布局、层次、字号与间距;颜色只能写角色名:`primary` / `secondary` / `tertiary`(文字层级)和 `success` / `warning` / `danger`(仅表达结果、提醒、问题)。两端把角色映射到各自主题 token(Desktop 用 CSS 变量,Mobile 用当前调色板),切换模式自动跟随。`backgroundColor`、`borderColor`、字面颜色与旧的 `{light, dark}` 颜色对一律忽略;边框固定为 1 px 主题边框色。图表与 SVG 的颜色同样只接受角色(SVG 另可用 `none`)。已保存的旧答案按同一规则显示,不再出现自定义背景。
+
+数值宽度限定不超过可用宽度,最小宽度不超过容器,固定尺寸在窄屏缩小而不横向溢出。
+
## 恢复与容量
原始操作流作为原消息正文持久保存,重新打开时从原文还原文档。完整累计文本快照天然包含断线前的操作;序号重复不重复执行,缺口保留已提交内容并报告未能显示部分。历史传输超过原有预算时先合并为完整树快照,仍超限则使用可读正文降级并保留原有远程截断标记,不传半截操作 JSON。
@@ -38,7 +46,7 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到
共享解析/消息测试 85 项;Desktop 组件、伙伴投影、历史摘要和远程传输 145 项;Mobile 伙伴投影 23 项;三 Harness 真实指令组装定向测试 4 项。两端类型检查、共享包构建检查通过,未跑无关全量。实测修复了移动端流式到历史行的身份切换、桌面立即重载丢控件值,以及计算节点引用静默归零。
-当前组件使用宿主主题,不支持任意 HTML/CSS 或文字颜色;按钮只改本地状态。原型中的外部动作、自定义隔离可视化尚未接入,不宣称全部原型设想已交付。
+组件只接受白名单样式与 Cindy 颜色角色(见「跨端与双模式」),不执行任意 HTML/CSS;按钮只改本地状态。原型中的外部动作、自定义隔离可视化尚未接入,不宣称全部原型设想已交付。
旧完整 HTML 预览路径已移除,其旧验收不覆盖本实现。送审不代表跨设备补充验收已完成;合并/发布前仍须补齐上面列明的相关场景。
@@ -111,3 +119,21 @@ iPhone 18 Pro 模拟器从生产组件装载同一官方播放器和原链接;
与跨设备端到端尚未验收,不能据此声明所有外联媒体和环境已通过。
官方接入要求:[YouTube embedded player](https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-youtube-player)。
+
+## 颜色收归 Cindy 与跨端双模式验收(2026-10-18)
+
+按用户裁决移除模型背景色与自定义颜色,颜色只取 Cindy 角色(见「跨端与双模式」);同时删去本轮先行试做、
+已无必要的对比度兜底与局部换主题逻辑,只保留宽度限定。旧答案中的背景与颜色对按新规则忽略。
+
+隔离 Desktop 重启载入新说明后,三 Harness(Codex / Claude Code / Pi)各生成 3 个自然请求(周计划、
+三款唱机对比、要求“深色主视觉”的议程)共 9 份:全部使用组件,没有 `backgroundColor` / `borderColor`,
+颜色值全部是角色名,没有超过 300 px 的固定宽度。Claude Code 在议程答案开头向用户说明了颜色由 Cindy
+统一绘制。宽屏与 393 px 窄屏在浅/深色下均无横向溢出;答案内仅剩的底色来自宿主 Markdown 行内代码与表头。
+
+模式切换:9 份已打开答案不刷新、不重新生成,浅 → 深 → 浅,文字、边框与图形颜色即时变化并完全还原。
+另发起一次真实 Codex 生成,在流式输出中途三次切换,切换立即生效,后续内容按当前模式出现,完成态正确。
+iPhone 18 Pro 模拟器以原生回放同 9 份答案,浅/深色各看开头、中段、结尾;对同一打开答案连续四次切换系统
+外观,应用模式与正文颜色在 1 秒内跟随。手机仍是测试数据回放,不代替登录后的跨设备全链路;Android 未测。
+
+定向验证:共享解析/视觉 11 项、Desktop 正文组件 9 项通过;共享包、Desktop、Mobile 类型检查通过。
+测试任务 12 个已关闭、标记删除并回读;截图与数据在作者的“跨端双模式验收”目录。
diff --git a/packages/maker-shared/src/__tests__/richAnswer.test.ts b/packages/maker-shared/src/__tests__/richAnswer.test.ts
index 5fe1f5d71e..a9fc049f5a 100644
--- a/packages/maker-shared/src/__tests__/richAnswer.test.ts
+++ b/packages/maker-shared/src/__tests__/richAnswer.test.ts
@@ -1,6 +1,6 @@
import { youtubeVideo } from '../richAnswer';
import { describe, expect, it } from 'vitest';
-import { RichAnswerStream, RichInteractionMemory, hasRichAnswer, splitRichAnswer, richDefaults, richEvaluate, richLabel, richResolvedValues, richChart, richCalculationUnavailable, richVisualStyle, richVector, richLinePlot } from '../richAnswer';
+import { RichAnswerStream, RichInteractionMemory, hasRichAnswer, splitRichAnswer, richDefaults, richEvaluate, richLabel, richResolvedValues, richChart, richCalculationUnavailable, richVisualStyle, richVector, richLinePlot, type RichPalette } from '../richAnswer';
// Tier 1: actual stream reducer. Regression targets are partial transport, edits,
// replay and preservation of user input; no DOM/source-string contracts.
const line = (seq: number, op: Record<string, unknown>) => JSON.stringify({ seq, ...op }) + '\n';
@@ -108,16 +108,17 @@ it('keeps missing, cyclic and invalid calculations unavailable instead of report
expect(richEvaluate({ op: 'concat', args: Array(32).fill({ ref: 'text' }) }, { text: 'a'.repeat(4096) })).toBeUndefined();
});
+const palette: RichPalette = { primary: "P", secondary: "S", tertiary: "T", success: "OK", warning: "W", danger: "D", border: "B" };
// Tier 1: model visual attributes must reach both renderers without admitting
// executable SVG/URL payloads; the reported stock data must not flatten at zero.
-it("preserves model colors and vector geometry, excludes executable attributes, and fits line domains", () => {
+it("maps color roles, keeps vector geometry, excludes executable attributes, and fits line domains", () => {
const source = line(1, {
op: "create",
id: "visual",
kind: "svg",
props: {
style: {
- color: { light: "#1257ab", dark: "#89baff" },
+ color: "secondary",
fontSize: 28,
gap: 24,
backgroundColor: "url(https://example.test/track)",
@@ -127,7 +128,8 @@ it("preserves model colors and vector geometry, excludes executable attributes,
{
type: "path",
d: "M 0 20 L 40 30",
- stroke: { light: "#1257ab", dark: "#89baff" },
+ stroke: "success",
+ fill: "none",
strokeWidth: 4,
onClick: "alert(1)",
},
@@ -140,17 +142,18 @@ it("preserves model colors and vector geometry, excludes executable attributes,
const doc = new RichAnswerStream().update(source, true),
node = doc.nodes.get("visual")!;
expect(doc.issues).toBe(0);
- expect(richVisualStyle(node, true)).toEqual({
- color: "#89baff",
+ expect(richVisualStyle(node, palette)).toEqual({
+ color: "S",
fontSize: 28,
gap: 24,
});
- const vector = richVector(node, true);
+ const vector = richVector(node, palette);
expect(vector.viewBox).toBe("0 0 400 240");
expect(vector.shapes).toHaveLength(2);
expect(vector.shapes[0].props).toEqual({
d: "M 0 20 L 40 30",
- stroke: "#89baff",
+ stroke: "OK",
+ fill: "none",
strokeWidth: 4,
});
const data = [
@@ -212,3 +215,13 @@ it('routes YouTube pages to canonical players without turning arbitrary URLs int
for (const src of ['https://youtube.com.evil.test/watch?v=glW1pXWebnY', 'https://[email protected]/watch?v=glW1pXWebnY', 'file:///watch?v=glW1pXWebnY', 'https://example.org/movie.mp4', 'https://youtube.com/watch?v=bad']) expect(youtubeVideo(src)).toBeNull();
expect(youtubeVideo('https://www.youtube-nocookie.com/embed/glW1pXWebnY?autoplay=1')?.embed).toBe('https://www.youtube.com/embed/glW1pXWebnY?playsinline=1&autoplay=0');
});
+// 2026-10-18 owner decision: colors and backgrounds belong to Cindy. Answers written
+// before it (and literal colors from models) must not paint backgrounds or custom colors.
+it("ignores model backgrounds and color values and keeps borders on the host border", () => {
+ const card = new RichAnswerStream().update(
+ line(1, { op: "create", id: "card", kind: "stack", props: { style: { backgroundColor: { light: "#14161b", dark: "#101216" }, color: { light: "#f5f6f8", dark: "#f5f6f8" }, borderColor: "#2a2e36", borderWidth: 3, padding: 20 } } }),
+ true,
+ ).nodes.get("card")!;
+ expect(richVisualStyle(card, palette)).toEqual({ padding: 20, borderWidth: 1, borderStyle: "solid", borderColor: "B" });
+ expect(richVisualStyle(card)).toEqual({ padding: 20, borderWidth: 1 });
+});
diff --git a/packages/maker-shared/src/richAnswer.ts b/packages/maker-shared/src/richAnswer.ts
index 0d37e5db30..2f27391b67 100644
--- a/packages/maker-shared/src/richAnswer.ts
+++ b/packages/maker-shared/src/richAnswer.ts
@@ -1,4 +1,4 @@
-export { richColor, richVisualStyle, richVector } from "./richAnswerVisual";
+export { RICH_COLOR_ROLES, richColor, richVisualStyle, richVector, type RichColorRole, type RichPalette } from "./richAnswerVisual";
export { youtubeVideo } from "./youtubeVideo";
/** Model-neutral, declarative answer components. No code evaluation or I/O. */
export const RICH_ANSWER_LANGUAGE = "cindy-ui";
diff --git a/packages/maker-shared/src/richAnswerGuide.ts b/packages/maker-shared/src/richAnswerGuide.ts
index 8c3f69191a..889fb80755 100644
--- a/packages/maker-shared/src/richAnswerGuide.ts
+++ b/packages/maker-shared/src/richAnswerGuide.ts
@@ -1,7 +1,11 @@
/** Single delivery protocol used by host instructions and optional capability lookup. */
export const RICH_ANSWER_GUIDE = `Cindy can render a streaming component document directly in an assistant progress message or final answer. You choose content and layout; ordinary Markdown remains available. No HTML file or extra model call is needed.
-Your canvas is an inline, progressively rendered part of the conversation, within the message width on desktop or mobile. Cindy supplies the surrounding application surface. The same answer can be viewed in light or dark mode, and the user can switch modes after generation. Unspecified colors use the host defaults. When choosing your own backgrounds, text, chart or SVG colors, consider their contrast together in both modes; use {light:"...",dark:"..."} color pairs when they need to adapt. Literal colors remain unchanged across themes. Backgrounds and other visual choices are yours; this describes the rendering environment, not a prescribed visual style.
+Your canvas is an inline, progressively rendered part of the conversation, on Cindy's own surface. Layout, hierarchy, typography and spacing are yours; colors and backgrounds belong to Cindy so every answer stays calm and consistent with the application.
+
+Every answer must work across devices and modes. The same stored answer is shown in a desktop message column (about 560–900 px wide) and on phones (about 320–430 px wide), and is often generated on one device and read later on another. It is shown in light and dark mode, and the user can switch modes at any time after generation. Do not design for the device or mode you assume the user has now.
+- Layout: keep the answer readable at 320 px without horizontal scrolling. Prefer unset or percentage widths; use fixed pixel sizes only for small elements. Below 600 px, rows and grids become one column unless mobileColumns sets more; decide what should stay side by side on a phone. Cindy keeps nodes within the available width, so oversized fixed widths shrink rather than overflow.
+- Color: answers have no backgrounds or custom color values; Cindy draws every color from its theme, so both modes follow automatically. Where color carries meaning, name a role: "primary", "secondary" or "tertiary" for text emphasis, and "success", "warning" or "danger" only for results, cautions and problems. Other color values are ignored. When asked for a colorful or themed look, build it from layout, typography, icons and spacing instead of colors.
To use components, place newline-delimited JSON operations inside a cindy-ui fenced block. Each complete line is rendered immediately; do not wait for a whole document. A code example must be nested inside a longer outer Markdown fence so it stays an example.
@@ -20,13 +24,13 @@ Components and props (no arbitrary HTML, CSS, scripts or tool access):
- image/video/audio: src (existing managed reference, URL or task file), alt, caption. Reuse actual media; never invent asset URLs or embed base64 data. Video src accepts a playable media file URL or a YouTube watch/share/shorts URL (the host uses the site player). Other website pages are links, not video files; link to those pages instead of treating them as media bytes.
- code: text, language. math: text (LaTeX). diagram: text (Mermaid).
- stat: label, value, prefix?, suffix?.
-- chart: label, variant:"bar"|"line", data:[{label,value}], color?, colors? (bar colors), height?, yMin?, yMax?, includeZero?, ticks?, decimals?, showValues?, showLabels?, showPoints?, pointRadius?, strokeWidth?, showGrid?, left?, right?, top?, bottom?. Line domains fit the data unless specified. Chart options are optional; use svg for other chart types or custom composition.
-- svg: label/alt, viewBox:[x,y,width,height], shapes:[{type,...attributes}]. Shape types: path, rect, circle, ellipse, line, polyline, polygon, text. Attributes: x,y,x1,y1,x2,y2,width,height,rx,ry,cx,cy,r,d,points,fill,stroke,strokeWidth,strokeDasharray,strokeLinecap,strokeLinejoin,opacity,fillOpacity,strokeOpacity,fontSize,fontWeight,letterSpacing,textAnchor,transform. text shapes use text. Coordinates and paths are model-designed; the viewBox scales to the available width. No script, events, HTML, external references or URL paints.
+- chart: label, variant:"bar"|"line", data:[{label,value}], color? (role), colors? (bar roles), height?, yMin?, yMax?, includeZero?, ticks?, decimals?, showValues?, showLabels?, showPoints?, pointRadius?, strokeWidth?, showGrid?, left?, right?, top?, bottom?. Line domains fit the data unless specified. Chart options are optional; use svg for other chart types or custom composition.
+- svg: label/alt, viewBox:[x,y,width,height], shapes:[{type,...attributes}]. Shape types: path, rect, circle, ellipse, line, polyline, polygon, text. Attributes: x,y,x1,y1,x2,y2,width,height,rx,ry,cx,cy,r,d,points,fill and stroke (a color role or "none"),strokeWidth,strokeDasharray,strokeLinecap,strokeLinejoin,opacity,fillOpacity,strokeOpacity,fontSize,fontWeight,letterSpacing,textAnchor,transform. text shapes use text. Coordinates and paths are model-designed; the viewBox scales to the available width. No script, events, HTML, external references or URL paints.
- 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.
-Every node accepts props.style (style beside props is also accepted) with optional color, backgroundColor, borderColor, opacity, width/maxWidth/minWidth/height/minHeight/maxHeight, padding/paddingTop/paddingRight/paddingBottom/paddingLeft, marginTop/marginBottom, gap, borderRadius/borderWidth/borderStyle, fontSize/fontWeight/fontFamily/fontStyle/lineHeight/letterSpacing/textAlign/textDecorationLine, flexGrow/flexShrink, alignItems/justifyContent/flexDirection/flexWrap. Lengths are numbers in display pixels; dimensions also accept percentages. lineHeight up to 4 is a font-size multiplier; larger values are pixels. Colors are literal CSS colors or {light:"...",dark:"..."}. Model-specified styles override host defaults; content styling is not restricted to Cindy's application chrome. Custom visualizations and icons can use svg primitives instead of the preset chart/icon. SVG is structured data, not a markup string.
+Every node accepts props.style (style beside props is also accepted) with optional color (a role), opacity, width/maxWidth/minWidth/height/minHeight/maxHeight, padding/paddingTop/paddingRight/paddingBottom/paddingLeft, marginTop/marginBottom, gap, borderRadius/borderWidth/borderStyle (borders are 1 px in Cindy's border color), fontSize/fontWeight/fontFamily/fontStyle/lineHeight/letterSpacing/textAlign/textDecorationLine, flexGrow/flexShrink, alignItems/justifyContent/flexDirection/flexWrap. Lengths are numbers in display pixels; dimensions also accept percentages. lineHeight up to 4 is a font-size multiplier; larger values are pixels. Model-specified styles override host defaults within these limits. Custom visualizations and icons can use svg primitives instead of the preset chart/icon. SVG is structured data, not a markup string.
bind defaults to node id. User values persist locally per account/device/message and take precedence over later model defaults. They are not automatically sent to the model or synchronized across viewing devices. Do not ask for credentials in these controls.
value and chart data may use a scalar, {ref:"stateKeyOrComputedNodeId"}, or {op,args:[...]}. Supported op: add,sub,mul,div,min,max,lt,gt,eq,if,concat. References can target input bindings or computed stat/text node ids, including nodes declared later. Never create circular references. Missing or invalid references are unavailable, not zero. No JavaScript evaluation.
@@ -40,7 +44,7 @@ Keep blocks under 128 KB, with no more than 2048 nodes and depth 32. Finish each
/** Host addition only: native CLI instructions and execution remain unchanged. */
export const ANSWER_DELIVERY_PROMPT = `## Cindy answer delivery
-Create beautiful, elegant, readable answers. You decide the visual design, layout, typography, colors and charts, following the user's request and presentation preferences. Cindy's component defaults are fallbacks, not design requirements. These capabilities apply to tasks and companions without changing your tool use or native workflow.
+Create beautiful, elegant, readable answers. You decide the layout, typography and charts within Cindy's colors, following the user's request and presentation preferences. Cindy's component defaults are fallbacks, not design requirements. These capabilities apply to tasks and companions without changing your tool use or native workflow.
The component protocol is rendered on Cindy conversation surfaces. External channels retain their required formats. Controls hold local viewing state; they do not execute work or send input to the model.
diff --git a/packages/maker-shared/src/richAnswerVisual.ts b/packages/maker-shared/src/richAnswerVisual.ts
index 9907ad3a6f..5ddf62572f 100644
--- a/packages/maker-shared/src/richAnswerVisual.ts
+++ b/packages/maker-shared/src/richAnswerVisual.ts
@@ -42,28 +42,46 @@ const enums: Record<string, readonly string[]> = {
textDecorationLine: ["none", "underline", "line-through"],
borderStyle: ["solid", "dashed", "dotted"],
};
-export function richColor(value: unknown, dark = false): string | undefined {
- if (value && typeof value === "object") {
- const pair = value as Record<string, unknown>;
- value = dark ? (pair.dark ?? pair.light) : (pair.light ?? pair.dark);
- }
- if (typeof value !== "string") return undefined;
- // Both native SVG and CSS support these literal colors. URLs/var()/expressions never cross this boundary.
- return /^(?:#[\da-f]{3,8}|rgba?\([\d.,%\s]+\)|hsla?\([\d.,%\s]+\)|[a-z]+)$/i.test(
- value,
- )
- ? value
+/**
+ * Colors are Cindy's, not the model's: answers may only name a role, and each client maps
+ * roles to its theme tokens so both modes and every device stay consistent and calm.
+ */
+export const RICH_COLOR_ROLES = [
+ "primary",
+ "secondary",
+ "tertiary",
+ "success",
+ "warning",
+ "danger",
+] as const;
+export type RichColorRole = (typeof RICH_COLOR_ROLES)[number];
+/** Host values for each role plus the host border; values are theme tokens or theme colors. */
+export type RichPalette = Record<RichColorRole | "border", string>;
+export function richColor(
+ value: unknown,
+ palette: RichPalette,
+): string | undefined {
+ return typeof value === "string" &&
+ (RICH_COLOR_ROLES as readonly string[]).includes(value)
+ ? palette[value as RichColorRole]
: undefined;
}
-export function richVisualStyle(node: RichNode, dark = false): RichVisualStyle {
+/** Without a palette (layout-only callers) colors and borders are omitted. */
+export function richVisualStyle(
+ node: RichNode,
+ palette?: RichPalette,
+): RichVisualStyle {
const raw = node.props.style;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const style = raw as Record<string, unknown>;
const out: RichVisualStyle = {};
for (const [key, value] of Object.entries(style)) {
- if (["color", "backgroundColor", "borderColor"].includes(key)) {
- const color = richColor(value, dark);
+ // Backgrounds and border colors stay with the host; text uses a named role only.
+ if (key === "color") {
+ const color = palette && richColor(value, palette);
if (color) out[key] = color;
+ } else if (key === "borderWidth" && typeof value === "number") {
+ if (value > 0) out[key] = 1;
} else if (
lengths.has(key) &&
typeof value === "number" &&
@@ -102,6 +120,11 @@ export function richVisualStyle(node: RichNode, dark = false): RichVisualStyle {
out[key] = Math.max(0, Math.min(1, value));
else if (enums[key]?.includes(String(value))) out[key] = String(value);
}
+ if (palette && (out.borderWidth || out.borderStyle)) {
+ out.borderWidth ??= 1;
+ out.borderStyle ??= "solid";
+ out.borderColor = palette.border;
+ }
return out;
}
export type RichVectorShape = {
@@ -150,7 +173,7 @@ const numbers = new Set([
]);
export function richVector(
node: RichNode,
- dark = false,
+ palette: RichPalette,
): { viewBox: string; shapes: RichVectorShape[] } {
const vb = Array.isArray(node.props.viewBox)
? node.props.viewBox
@@ -174,7 +197,7 @@ export function richVector(
if (numbers.has(k) && typeof v === "number" && Number.isFinite(v))
props[k] = v;
else if (["fill", "stroke"].includes(k)) {
- const c = richColor(v, dark);
+ const c = v === "none" ? "none" : richColor(v, palette);
if (c) props[k] = c;
} else if (
k === "d" &&