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): render rich content in shared conversation images

zqchris04e0ad24203b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c989cfabbe..487028ad33 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { snapshotRichAnswerValues } from '@/session/RichAnswer';
import { deviceDisplayName } from '@/device-link/deviceName';
import { SessionQuickSendProvider } from '@/session/SessionQuickSendContext';
import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';
@@ -6305,6 +6306,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
);
const conversationShareWidth = buildConversationShareContentWidth(detailViewport);
const conversationShareColors = useMemo<ConversationShareWebViewColors>(() => ({
+ success: colors.statusDone, warning: colors.warningFg, danger: colors.statusError,
background: colors.surface,
border: colors.border,
ownUserBubble: userBubbleColors,
@@ -6325,7 +6327,10 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
textTertiary: colors.textTertiary,
dark: mode === 'dark',
}), [colors, mode, userBubbleColors]);
+ const snapshotShareRichValues = useCallback((message: ConversationShareMessage) => snapshotRichAnswerValues(message.body,
+ `${auth.user?.id ?? 'signed-out'}:${deviceId}:${sessionId}:${message.richStateKey ?? message.clientId}`), [auth.user?.id, deviceId, sessionId]);
const shareImages = useConversationShareImages(selectedShareMessages, resolveRemoteMedia, {
+ snapshotRichValues: snapshotShareRichValues,
workdir: currentSession?.workingDir ?? undefined,
remoteHostId: currentSession?.remoteHostId ?? undefined,
sessionId,
@@ -6389,6 +6394,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
&& shareSelectionRevisionRef.current === operationSelectionRevision;
let localUri: string | null = null;
let shareCompleted = false;
+ let restoreShareSelection: (() => boolean) | undefined;
setConversationShareBusy(true);
try {
// 成功分享的 PNG 要保留给系统扩展读取;回收更早的产物,限制 cache
@@ -6402,14 +6408,16 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
if (!localUri) throw new Error(t('session.screen.shareNoLocalImage'));
const sharing = await import('expo-sharing');
if (!isShareOperationActive()) return;
+ // 系统面板的 Promise 在关闭后才返回,交接时就收起选择栏。
+ // expo-sharing 不区分取消与完成;只有打开失败才恢复原勾选。
+ restoreShareSelection = shareSelectionStore.exitForShare();
await sharing.shareAsync(localUri, { mimeType: 'image/png' });
// shareAsync 成功后系统扩展仍可能读取该 URL;即使当前操作随即失活,
// 也必须交给下一次有界清理,不能在 finally 中提前删除。
shareCompleted = true;
- if (!isShareOperationActive()) return;
- shareSelectionStore.exit();
} catch (error) {
- if (!isShareOperationActive()) return;
+ if (shareOperationSeqRef.current !== operationSeq) return;
+ if (restoreShareSelection ? !restoreShareSelection() : !isShareOperationActive()) return;
console.warn('[conversation-share] failed to generate or open share image', error);
Alert.alert(t('session.screen.shareFailedTitle'), t('session.screen.shareImageFailed'));
} finally {
diff --git a/apps/mobile/src/__tests__/conversationShareImages.test.ts b/apps/mobile/src/__tests__/conversationShareImages.test.ts
index a90850b0f5..ea6233e9ad 100644
--- a/apps/mobile/src/__tests__/conversationShareImages.test.ts
+++ b/apps/mobile/src/__tests__/conversationShareImages.test.ts
@@ -335,3 +335,190 @@ describe("conversation share images", () => {
expect(result).toEqual([]);
});
});
+
+// Regression: assistant components were exported as JSON and their images were never loaded.
+// Production entry: prepareConversationShareImages → HTML/native SVG builders (unit tier).
+// Existing cases only exercised Markdown image syntax, not component media or local view state.
+it("exports composed images, values, charts and vectors on both capture paths without operation text", async () => {
+ const ops = [
+ {
+ kind: "image",
+ id: "photo",
+ props: {
+ src: "cindy-media://blobs/sample.png",
+ alt: "页面对比",
+ caption: "同一份内容",
+ },
+ },
+ { kind: "grid", id: "stats", props: { columns: 4, mobileColumns: 2 } },
+ ...[48, 12, 36, 7].map((value, index) => ({
+ kind: "stat",
+ id: `s${index}`,
+ parent: "stats",
+ props: { label: ["全部", "进行中", "已完成", "待处理"][index], value },
+ })),
+ {
+ kind: "range",
+ id: "months",
+ props: { label: "月数", default: 1, min: 1, max: 12 },
+ },
+ {
+ kind: "stat",
+ id: "total",
+ props: {
+ label: "费用",
+ value: { op: "mul", args: [{ ref: "months" }, 20] },
+ },
+ },
+ {
+ kind: "chart",
+ id: "trend",
+ props: {
+ label: "趋势",
+ variant: "line",
+ data: [
+ { label: "一月", value: 12 },
+ { label: "二月", value: 36 },
+ ],
+ },
+ },
+ {
+ kind: "svg",
+ id: "vector",
+ props: {
+ viewBox: [0, 0, 300, 80],
+ shapes: [
+ { type: "circle", cx: 40, cy: 40, r: 20, fill: "primary" },
+ { type: "text", x: 75, y: 45, text: "示意图" },
+ ],
+ },
+ },
+ { kind: "details", id: "hidden", props: { label: "附录", default: false } },
+ {
+ kind: "image",
+ id: "hiddenPhoto",
+ parent: "hidden",
+ props: { src: "cindy-media://blobs/hidden.png", alt: "隐藏图片" },
+ },
+ ].map((node, index) =>
+ JSON.stringify({ version: 1, seq: index + 1, op: "create", ...node }),
+ );
+ const body = "```cindy-ui\n" + ops.join("\n") + "\n```";
+ const load = vi.fn(async () => image);
+ const messages = await prepareConversationShareImages(
+ [
+ {
+ clientId: "rich",
+ kind: "assistant",
+ body,
+ richValues: { 0: { months: 6 } },
+ },
+ ],
+ load,
+ );
+ expect(load.mock.calls).toEqual([["cindy-media://blobs/sample.png"]]);
+ for (const theme of [lightColors, darkColors]) {
+ const colors = {
+ background: theme.surface,
+ border: theme.border,
+ codeSurface: theme.chatCodeSurface,
+ inlineCode: theme.chatInlineCodeText,
+ surfaceChip: theme.surfaceChip,
+ surfaceElevated: theme.surfaceElevated,
+ textPrimary: theme.textPrimary,
+ textSecondary: theme.textSecondary,
+ textTertiary: theme.textTertiary,
+ syntax: {},
+ };
+ const html = buildConversationShareHtml({
+ allShareableIds: ["rich"],
+ colors,
+ contentWidth: 390,
+ selectedMessages: messages,
+ });
+ const layout = buildConversationShareSvgLayout({
+ allShareableIds: ["rich"],
+ colors,
+ width: 390,
+ messages,
+ });
+ const text = layout.bubbles
+ .flatMap((bubble) => bubble.textBlocks.flatMap((block) => block.lines))
+ .join("");
+ expect(text).toContain("120");
+ expect(html).toContain("120");
+ expect(html).toContain(image.uri);
+ expect(layout.images).toHaveLength(1);
+ expect(layout.bubbles.flatMap((b) => b.vectors ?? [])).toHaveLength(2);
+ expect(html).toContain("<circle");
+ expect(html).not.toContain("cindy-media://");
+ expect(html).not.toContain("&quot;op&quot;");
+ expect(text).not.toContain('"op"');
+ expect(text).not.toContain("隐藏图片");
+ const labels = layout.bubbles
+ .flatMap((b) => b.textBlocks)
+ .filter((b) =>
+ ["全部", "进行中", "已完成", "待处理"].includes(b.lines.join("")),
+ );
+ expect(labels).toHaveLength(4);
+ expect(labels[0]!.y).toBe(labels[1]!.y);
+ expect(labels[2]!.y).toBeGreaterThan(labels[0]!.y);
+ }
+ const user = await prepareConversationShareImages(
+ [{ clientId: "example", kind: "user", body }],
+ load,
+ );
+ expect(user[0]!.images!.size).toBe(0); // User-authored examples remain code.
+});
+
+// A selected option label is visible output, even though its stored value is harmless.
+// Regression guard for the new component projection crossing the existing redaction boundary.
+it("redacts resolved component content before either capture path renders it", () => {
+ const body =
+ "```cindy-ui\n" +
+ JSON.stringify({
+ version: 1,
+ seq: 1,
+ op: "create",
+ id: "choice",
+ kind: "select",
+ props: {
+ label: "配置",
+ default: "one",
+ options: [{ value: "one", label: "password: private-selected-secret" }],
+ },
+ }) +
+ "\n```";
+ const messages = [{ clientId: "rich", kind: "assistant" as const, body }];
+ const colors = {
+ background: lightColors.surface,
+ border: lightColors.border,
+ codeSurface: lightColors.chatCodeSurface,
+ inlineCode: lightColors.chatInlineCodeText,
+ surfaceChip: lightColors.surfaceChip,
+ surfaceElevated: lightColors.surfaceElevated,
+ textPrimary: lightColors.textPrimary,
+ textSecondary: lightColors.textSecondary,
+ textTertiary: lightColors.textTertiary,
+ syntax: {},
+ };
+ const html = buildConversationShareHtml({
+ allShareableIds: ["rich"],
+ colors,
+ contentWidth: 390,
+ selectedMessages: messages,
+ });
+ const layout = buildConversationShareSvgLayout({
+ allShareableIds: ["rich"],
+ colors,
+ width: 390,
+ messages,
+ });
+ const text = layout.bubbles
+ .flatMap((bubble) => bubble.textBlocks.flatMap((block) => block.lines))
+ .join("");
+ expect(html).not.toContain("private-selected-secret");
+ expect(text).not.toContain("private-selected-secret");
+ expect(html).toContain("配置");
+ expect(text).toContain("配置");
+});
diff --git a/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts b/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts
index f20621b361..1186af7c0f 100644
--- a/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts
+++ b/apps/mobile/src/__tests__/mobileNativeBoundaryContracts.test.ts
@@ -31,10 +31,10 @@ it('bounds native export and preserves the hidden document and system share boun
const route = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
const share = route.indexOf("await sharing.shareAsync(localUri, { mimeType: 'image/png' });");
const completed = route.indexOf('shareCompleted = true;', share);
- const inactive = route.indexOf('if (!isShareOperationActive()) return;', share);
expect(share).toBeGreaterThanOrEqual(0);
expect(completed).toBeGreaterThan(share);
- expect(inactive).toBeGreaterThan(completed);
+ // Selection now closes before opening the sheet. File lifetime still follows
+ // the native promise, independent of that UI state.
expect(route).toContain('if (!shareCompleted && localUri)');
});
diff --git a/apps/mobile/src/__tests__/shareSelectionStore.test.ts b/apps/mobile/src/__tests__/shareSelectionStore.test.ts
index 5a6ed27f61..7977d7a7fb 100644
--- a/apps/mobile/src/__tests__/shareSelectionStore.test.ts
+++ b/apps/mobile/src/__tests__/shareSelectionStore.test.ts
@@ -1,21 +1,59 @@
import { describe, expect, it } from "vitest";
-import { isShareableMessage } from "@/session/shareSelectionStore";
+import {
+ isShareableMessage,
+ shareSelectionStore,
+} from "@/session/shareSelectionStore";
describe("mobile share selection eligibility", () => {
it("excludes legacy hook-source messages from share selection and export", () => {
expect(isShareableMessage({ kind: "user" })).toBe(true);
expect(
- isShareableMessage({ kind: "user", hookSource: { userTextContent: false } }),
+ isShareableMessage({
+ kind: "user",
+ hookSource: { userTextContent: false },
+ }),
).toBe(false);
expect(
- isShareableMessage({ kind: "assistant", hookSource: { userTextContent: false } }),
+ isShareableMessage({
+ kind: "assistant",
+ hookSource: { userTextContent: false },
+ }),
).toBe(false);
});
it("keeps local IM rows (stored as clean user text) shareable like ordinary user messages", () => {
expect(
- isShareableMessage({ kind: "user", hookSource: { userTextContent: true } }),
+ isShareableMessage({
+ kind: "user",
+ hookSource: { userTextContent: true },
+ }),
).toBe(true);
});
});
+
+// tier: unit. System sharing may stay pending after handoff. Selection must
+// disappear immediately; an opening error restores it without reviving an old
+// task or overwriting a newer selection. Eligibility tests do not cover this.
+it("closes selection at handoff and restores it only before newer user actions", () => {
+ try {
+ shareSelectionStore.enter("task-a", "first");
+ shareSelectionStore.toggle("second");
+ const restore = shareSelectionStore.exitForShare();
+ expect(shareSelectionStore.isActive("task-a")).toBe(false);
+ expect(shareSelectionStore.getSelectedIds()).toEqual([]);
+ expect(restore()).toBe(true);
+ expect(shareSelectionStore.isActive("task-a")).toBe(true);
+ expect(shareSelectionStore.getSelectedIds()).toEqual(["first", "second"]);
+
+ const staleRestore = shareSelectionStore.exitForShare();
+ shareSelectionStore.enter("task-b", "new");
+ expect(staleRestore()).toBe(false);
+ expect(shareSelectionStore.getSelectedIds()).toEqual(["new"]);
+ shareSelectionStore.exit();
+ expect(staleRestore()).toBe(false);
+ expect(shareSelectionStore.getActiveSessionId()).toBeNull();
+ } finally {
+ shareSelectionStore.exit();
+ }
+});
diff --git a/apps/mobile/src/session/ConversationShareSvg.tsx b/apps/mobile/src/session/ConversationShareSvg.tsx
index ccd06a4b8c..c4969c2cd7 100644
--- a/apps/mobile/src/session/ConversationShareSvg.tsx
+++ b/apps/mobile/src/session/ConversationShareSvg.tsx
@@ -1,13 +1,28 @@
import {
forwardRef,
+ createElement,
+ type ComponentType,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from "react";
-import { Image as NativeImage, PixelRatio, Platform, StyleSheet, View } from "react-native";
+import {
+ Image as NativeImage,
+ PixelRatio,
+ Platform,
+ StyleSheet,
+ View,
+} from "react-native";
import Svg, {
+ G,
+ Path,
+ Circle,
+ Ellipse,
+ Line,
+ Polygon,
+ Polyline,
ClipPath,
Defs,
Image as SvgImage,
@@ -16,6 +31,7 @@ import Svg, {
TSpan,
} from "react-native-svg";
+import type { ShareVector } from "./conversationShareRichAnswer";
import {
CONVERSATION_SHARE_HAIRLINE,
type ConversationShareMessage,
@@ -294,7 +310,11 @@ export const ConversationShareSvg = forwardRef<
{!renderSize.sourceTooLarge ? (
<>
{layout.bubbles.map((bubble, bubbleIndex) => (
- <SvgBubbleView bubble={bubble} key={`bubble-${bubbleIndex}`} />
+ <SvgBubbleView
+ bubble={bubble}
+ key={`bubble-${bubbleIndex}`}
+ clipIdPrefix={`share-bubble-${bubbleIndex}`}
+ />
))}
{keyedImages.map((image) => (
<SvgImage
@@ -378,7 +398,13 @@ export const ConversationShareSvg = forwardRef<
);
});
-function SvgBubbleView({ bubble }: { bubble: ConversationShareSvgBubble }) {
+function SvgBubbleView({
+ bubble,
+ clipIdPrefix,
+}: {
+ bubble: ConversationShareSvgBubble;
+ clipIdPrefix: string;
+}) {
return (
<>
{bubble.fill || bubble.stroke ? (
@@ -400,6 +426,13 @@ function SvgBubbleView({ bubble }: { bubble: ConversationShareSvgBubble }) {
strokeWidth={SHARE_BUBBLE_STROKE_WIDTH}
/>
))}
+ {bubble.vectors?.map((vector, index) => (
+ <ShareVectorView
+ key={`vector-${index}`}
+ item={vector}
+ clipId={`${clipIdPrefix}-vector-${index}`}
+ />
+ ))}
{bubble.textBlocks.map((block, blockIndex) => (
<SvgText
fill={block.color}
@@ -438,3 +471,51 @@ const styles = StyleSheet.create({
top: 0,
},
});
+
+// A nested Svg creates a native root/viewport and can clip the rest of a long export.
+// Keep every shape in the single capture root; map the component viewBox with groups.
+function ShareVectorView({
+ item,
+ clipId,
+}: {
+ item: ShareVector;
+ clipId: string;
+}) {
+ const [vx, vy, vw, vh] = item.vector.viewBox.split(" ").map(Number);
+ const scale = Math.min(item.width / vw!, item.height / vh!);
+ const dx = item.x + (item.width - vw! * scale) / 2 - vx! * scale;
+ const dy = item.y + (item.height - vh! * scale) / 2 - vy! * scale;
+ const types = {
+ path: Path,
+ rect: Rect,
+ circle: Circle,
+ ellipse: Ellipse,
+ line: Line,
+ polyline: Polyline,
+ polygon: Polygon,
+ text: SvgText,
+ };
+ return (
+ <>
+ <Defs>
+ <ClipPath id={clipId}>
+ <Rect x={item.x} y={item.y} width={item.width} height={item.height} />
+ </ClipPath>
+ </Defs>
+ <G clipPath={`url(#${clipId})`}>
+ <G
+ transform={`translate(${dx},${dy}) scale(${scale})`}
+ fill={item.color}
+ >
+ {item.vector.shapes.map((shape, index) =>
+ createElement(
+ types[shape.type] as ComponentType<any>,
+ { ...shape.props, key: index },
+ shape.text,
+ ),
+ )}
+ </G>
+ </G>
+ </>
+ );
+}
diff --git a/apps/mobile/src/session/RichAnswer.tsx b/apps/mobile/src/session/RichAnswer.tsx
index bd9d769b06..d6ae8123dd 100644
--- a/apps/mobile/src/session/RichAnswer.tsx
+++ b/apps/mobile/src/session/RichAnswer.tsx
@@ -62,6 +62,8 @@ import {
type ThemeColors,
} from "@/theme";
import {
+ splitRichAnswer,
+ type RichValues,
richVisualStyle,
richColor,
richVector,
@@ -120,6 +122,18 @@ const memory = new RichInteractionMemory({
await AsyncStorage.setItem("cindy.richAnswer.viewState.v1", value);
},
});
+/** Click-time copy: an export never changes the conversation's local controls. */
+export function snapshotRichAnswerValues(
+ source: string,
+ stateKey: string,
+): Readonly<Record<number, RichValues>> {
+ return Object.fromEntries(
+ splitRichAnswer(source)
+ .filter((part) => part.kind === "rich")
+ .map((part) => [part.key, { ...memory.get(`${stateKey}:${part.key}`) }]),
+ );
+}
+
const submissions = new RichSubmissionController(memory);
function RichSendAction({ node, text, receiptKey, ready, style, buttonTextStyle }: {
diff --git a/apps/mobile/src/session/conversationShareImages.ts b/apps/mobile/src/session/conversationShareImages.ts
index 795bacea6e..8151ad1f39 100644
--- a/apps/mobile/src/session/conversationShareImages.ts
+++ b/apps/mobile/src/session/conversationShareImages.ts
@@ -1,3 +1,4 @@
+import { conversationShareReadableBody } from "./conversationShareRichAnswer";
import {
collectMobileMarkdownImages,
mobileMarkdownImageUrlForWorkdir,
@@ -11,6 +12,9 @@ export interface ConversationShareImageContext {
workdir?: string;
remoteHostId?: string;
sessionId?: string;
+ snapshotRichValues?: (
+ message: ConversationShareMessage,
+ ) => ConversationShareMessage["richValues"];
}
// Compressed bytes do not bound native bitmap memory. Charge every rendered
@@ -60,7 +64,9 @@ export async function prepareConversationShareImages(
: [message.body];
if (message.secondaryBody) texts.push(message.secondaryBody);
for (const text of texts) {
- for (const image of collectMobileMarkdownImages(text)) {
+ for (const image of collectMobileMarkdownImages(
+ conversationShareReadableBody(message, text),
+ )) {
const url = mobileMarkdownImageUrlForWorkdir(
image.url,
context.workdir,
diff --git a/apps/mobile/src/session/conversationShareMessages.ts b/apps/mobile/src/session/conversationShareMessages.ts
index 9732d5ac98..b0aa08d4b4 100644
--- a/apps/mobile/src/session/conversationShareMessages.ts
+++ b/apps/mobile/src/session/conversationShareMessages.ts
@@ -74,7 +74,10 @@ export function collectConversationShareMessages(
if (projected?.kind === 'user' && !item.message.hookSource && isOwnUserMessage?.(item.message)) {
projected.ownUserBubble = true;
}
- if (projected) messages.push(projected);
+ if (projected) {
+ projected.richStateKey = item.message.source.clientId ?? item.message.key;
+ messages.push(projected);
+ }
return;
}
if (item.type === 'work_group') {
diff --git a/apps/mobile/src/session/conversationShareRichAnswer.ts b/apps/mobile/src/session/conversationShareRichAnswer.ts
new file mode 100644
index 0000000000..bdad2fd13d
--- /dev/null
+++ b/apps/mobile/src/session/conversationShareRichAnswer.ts
@@ -0,0 +1,754 @@
+import {
+ RichAnswerStream,
+ splitRichAnswer,
+ richResolvedValues,
+ richString,
+ richNumber,
+ richLabel,
+ richMarkdown,
+ richChart,
+ richLinePlot,
+ richVector,
+ richVisualStyle,
+ richColor,
+ richOptions,
+ richRange,
+ richCalculationUnavailable,
+ type RichNode,
+ type RichValues,
+ type RichPalette,
+} from "@cindy/maker-shared/rich-answer";
+import { redactSensitiveText } from "@cindy/maker-shared/error-redaction";
+import type {
+ ConversationShareMessage,
+ ConversationShareWebViewColors,
+} from "./conversationShareWebViewHtml";
+import type {
+ ConversationShareSvgLayout,
+ ConversationShareSvgTextBlock,
+} from "./conversationShareSvgLayout";
+import type { ShareSvgRect } from "./conversationShareRichSvg";
+import { typeScale, spacing } from "@/theme/tokens";
+import { i18n } from "@/i18n";
+
+export interface ShareVector {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ vector: ReturnType<typeof richVector>;
+ color: string;
+}
+export interface ShareRichLayout {
+ textBlocks: ConversationShareSvgTextBlock[];
+ rectangles: ShareSvgRect[];
+ images: ConversationShareSvgLayout["images"];
+ vectors: ShareVector[];
+ height: number;
+}
+export type ShareMarkdownLayout = (
+ source: string,
+ x: number,
+ y: number,
+ width: number,
+) => ShareRichLayout;
+
+/** Read the same document and local values as the conversation. Hidden tabs/details stay hidden. */
+export function shareRichDocument(source: string, edited?: RichValues) {
+ const doc = new RichAnswerStream().update(source, true);
+ const values = richResolvedValues(doc, edited);
+ const children = (node: RichNode) => {
+ const current = values[richString(node, "bind", node.id)];
+ if (node.kind === "details" && !current) return [];
+ if (node.kind === "tabs")
+ return [
+ node.children.includes(String(current))
+ ? String(current)
+ : node.children[0],
+ ].filter((id): id is string => !!id);
+ return node.children;
+ };
+ return { doc, values, children };
+}
+
+/** Markdown projection used for image admission and whole-message redaction, never raw operations. */
+export function conversationShareReadableBody(
+ message: ConversationShareMessage,
+ source: string,
+): string {
+ if (message.kind !== "assistant") return source;
+ return splitRichAnswer(source)
+ .map((part) => {
+ if (part.kind === "markdown") return part.source;
+ const { doc, values, children } = shareRichDocument(
+ part.source,
+ message.richValues?.[part.key],
+ );
+ const visit = (id: string): string => {
+ const node = doc.nodes.get(id);
+ if (!node) return "";
+ const md = richMarkdown(node);
+ let text =
+ md ??
+ (node.kind === "stat"
+ ? `${richString(node, "label")}: ${richLabel(node, values)}`
+ : ["text", "heading"].includes(node.kind)
+ ? richLabel(node, values)
+ : node.kind === "chart"
+ ? [
+ richString(node, "label"),
+ ...richChart(node, values).map(
+ (item) => `${item.label}: ${item.value}`,
+ ),
+ ].join("\n")
+ : [
+ richString(node, "label"),
+ richString(node, "text"),
+ richString(node, "alt"),
+ ]
+ .filter(Boolean)
+ .join("\n"));
+ if (node.kind === "svg")
+ text +=
+ "\n" +
+ richVector(node, sharePalette())
+ .shapes.map((shape) => shape.text ?? "")
+ .join("\n");
+ const current = values[richString(node, "bind", node.id)];
+ if (node.kind === "select")
+ text += `: ${richOptions(node).find((option) => option.value === current)?.label ?? current ?? ""}`;
+ else if (["input", "range", "check"].includes(node.kind))
+ text += `: ${current ?? ""}${richString(node, "suffix")}`;
+ return [text, richString(node, "caption"), ...children(node).map(visit)]
+ .filter(Boolean)
+ .join("\n\n");
+ };
+ return doc.roots.map(visit).join("\n\n");
+ })
+ .join("\n\n");
+}
+
+function sharePalette(colors?: ConversationShareWebViewColors): RichPalette {
+ return {
+ primary: colors?.textPrimary ?? "currentColor",
+ secondary: colors?.textSecondary ?? "currentColor",
+ tertiary: colors?.textTertiary ?? "currentColor",
+ border: colors?.border ?? "currentColor",
+ success: colors?.success ?? colors?.textPrimary ?? "currentColor",
+ warning: colors?.warning ?? colors?.textPrimary ?? "currentColor",
+ danger: colors?.danger ?? colors?.textPrimary ?? "currentColor",
+ };
+}
+
+/** Static layout for native SVG export; graphic geometry is also reused by WKWebView. */
+export function layoutConversationShareRichAnswer(
+ source: string,
+ edited: RichValues | undefined,
+ colors: ConversationShareWebViewColors,
+ x: number,
+ y: number,
+ width: number,
+ markdown: ShareMarkdownLayout,
+): ShareRichLayout {
+ const { doc, values, children } = shareRichDocument(source, edited);
+ const palette = sharePalette(colors);
+ const result: ShareRichLayout = {
+ textBlocks: [],
+ rectangles: [],
+ images: [],
+ vectors: [],
+ height: 0,
+ };
+ const add = (layout: ShareRichLayout) => {
+ result.textBlocks.push(...layout.textBlocks);
+ result.rectangles.push(...layout.rectangles);
+ result.images.push(...layout.images);
+ result.vectors.push(...layout.vectors);
+ return layout.height;
+ };
+ const text = (
+ value: string,
+ left: number,
+ top: number,
+ available: number,
+ size: number = typeScale.bodyLarge,
+ color = colors.textPrimary,
+ bold = false,
+ ) => {
+ // Reuse the existing measured/conservative native Markdown layout, including CJK wrapping.
+ const layout = markdown(
+ value.replace(/([\\`*_{}[\]<>#])/g, "\\$1"),
+ left,
+ top,
+ available,
+ );
+ const ratio = Math.max(1, size) / typeScale.bodyLarge;
+ // Reflow at the requested size before scaling positions, not after wrapping.
+ const scaled =
+ ratio === 1
+ ? layout
+ : markdown(
+ value.replace(/([\\`*_{}[\]<>#])/g, "\\$1"),
+ 0,
+ 0,
+ available / ratio,
+ );
+ if (ratio !== 1)
+ for (const block of scaled.textBlocks) {
+ block.x = left + block.x * ratio;
+ block.y = top + block.y * ratio;
+ block.fontSize *= ratio;
+ block.lineHeight *= ratio;
+ }
+ for (const block of scaled.textBlocks) {
+ block.color = color;
+ block.bold = bold;
+ }
+ add(scaled);
+ return scaled.height * ratio;
+ };
+ const visit = (
+ id: string,
+ left: number,
+ top: number,
+ available: number,
+ ): number => {
+ const node = doc.nodes.get(id);
+ if (!node) return 0;
+ const visual = richVisualStyle(node, palette);
+ const number = (key: string, fallback = 0) =>
+ typeof visual[key] === "number"
+ ? Math.max(0, visual[key] as number)
+ : fallback;
+ const length = (value: unknown, fallback: number) =>
+ typeof value === "number"
+ ? value
+ : typeof value === "string" && value.endsWith("%")
+ ? (available * parseFloat(value)) / 100
+ : fallback;
+ const outerWidth = Math.max(
+ 1,
+ Math.min(
+ available,
+ length(visual.width, available),
+ length(visual.maxWidth, available),
+ ),
+ );
+ const pad = number("padding");
+ const pl = number("paddingLeft", pad),
+ pr = number("paddingRight", pad),
+ pt = number("paddingTop", pad),
+ pb = number("paddingBottom", pad);
+ const margin = number("marginTop");
+ const innerX = left + pl,
+ innerY = top + margin + pt,
+ innerWidth = Math.max(1, outerWidth - pl - pr);
+ const gap = number("gap", spacing.sm);
+ const label = richString(node, "label"),
+ current = values[richString(node, "bind", id)];
+ const color =
+ typeof visual.color === "string" ? visual.color : colors.textPrimary;
+ let height = 0;
+ const prose = (
+ value: string,
+ size: number = typeScale.bodyLarge,
+ tone = color,
+ bold = false,
+ ) => {
+ height += text(
+ value,
+ innerX,
+ innerY + height,
+ innerWidth,
+ size,
+ tone,
+ bold,
+ );
+ };
+ if (richCalculationUnavailable(node, values))
+ prose(i18n.t("message.richAnswer.calculationUnavailable"));
+ else if (["row", "grid"].includes(node.kind)) {
+ const aside = richString(node, "layout") === "aside";
+ const mobile = innerWidth <= 600 && !aside;
+ const weights = Array.isArray(node.props.weights)
+ ? node.props.weights.filter(
+ (n): n is number =>
+ typeof n === "number" && Number.isFinite(n) && n > 0,
+ )
+ : aside
+ ? [0.7, 1.8]
+ : [];
+ const columns = Math.min(
+ Math.max(1, node.children.length),
+ Math.max(
+ 1,
+ Math.round(
+ visual.flexDirection === "column"
+ ? 1
+ : mobile
+ ? richNumber(node, "mobileColumns", 1)
+ : weights.length || richNumber(node, "columns", 2),
+ ),
+ ),
+ );
+ const usable = Math.max(1, innerWidth - gap * (columns - 1));
+ for (let row = 0; row < node.children.length; row += columns) {
+ let offset = 0,
+ rowHeight = 0;
+ for (
+ let column = 0;
+ column < columns && row + column < node.children.length;
+ column++
+ ) {
+ const childWidth =
+ !mobile && weights.length === columns
+ ? (usable * weights[column]!) / weights.reduce((a, b) => a + b, 0)
+ : usable / columns;
+ rowHeight = Math.max(
+ rowHeight,
+ visit(
+ node.children[row + column]!,
+ innerX + offset,
+ innerY + height,
+ childWidth,
+ ),
+ );
+ offset += childWidth + gap;
+ }
+ height += rowHeight + gap;
+ }
+ height = Math.max(0, height - gap);
+ } else if (
+ ["stack", "group", "form", "tabs", "details"].includes(node.kind)
+ ) {
+ if (node.kind === "details" || node.kind === "tabs") {
+ const title =
+ node.kind === "tabs"
+ ? richString(doc.nodes.get(children(node)[0]!) ?? node, "label")
+ : label;
+ if (title) {
+ prose(title, typeScale.bodyLarge, color, true);
+ height += gap;
+ }
+ }
+ for (const child of children(node))
+ height += visit(child, innerX, innerY + height, innerWidth) + gap;
+ height = Math.max(0, height - gap);
+ } else if (node.kind === "stat") {
+ prose(label, typeScale.footnote, colors.textSecondary);
+ height += spacing.xs;
+ prose(
+ richLabel(node, values),
+ number("fontSize", typeScale.headline),
+ color,
+ true,
+ );
+ } else if (node.kind === "svg") {
+ const vector = richVector(node, palette),
+ dims = vector.viewBox.split(" ").map(Number);
+ height = Math.max(
+ 1,
+ Math.min(
+ number("maxHeight", Infinity),
+ number("height", (innerWidth * dims[3]!) / dims[2]!),
+ ),
+ );
+ result.vectors.push({
+ vector,
+ x: innerX,
+ y: innerY,
+ width: innerWidth,
+ height,
+ color,
+ });
+ } else if (node.kind === "chart") {
+ if (label) {
+ prose(label, typeScale.bodyLarge, color, true);
+ height += spacing.sm;
+ }
+ const data = richChart(node, values);
+ const chartColor = richColor(node.props.color, palette) ?? color;
+ if (richString(node, "variant") === "line") {
+ const plot = richLinePlot(data, innerWidth, node.props);
+ const shapes: Array<Record<string, unknown>> = [];
+ for (const tick of plot.ticks) {
+ if (node.props.showGrid !== false)
+ shapes.push({
+ type: "line",
+ x1: plot.left,
+ x2: plot.width - plot.right,
+ y1: tick.y,
+ y2: tick.y,
+ stroke: "tertiary",
+ strokeWidth: 0.5,
+ });
+ shapes.push({
+ type: "text",
+ x: plot.left - 8,
+ y: tick.y + 4,
+ text: tick.label,
+ textAnchor: "end",
+ fontSize: 12,
+ fill: "secondary",
+ });
+ }
+ shapes.push({
+ type: "polyline",
+ points: plot.points.map((p) => `${p.x},${p.y}`).join(" "),
+ stroke: node.props.color ?? "primary",
+ fill: "none",
+ strokeWidth: richNumber(node, "strokeWidth", 2),
+ });
+ for (const point of plot.points) {
+ if (node.props.showPoints !== false)
+ shapes.push({
+ type: "circle",
+ cx: point.x,
+ cy: point.y,
+ r: richNumber(node, "pointRadius", 3),
+ fill: node.props.color ?? "primary",
+ });
+ if (plot.showValues)
+ shapes.push({
+ type: "text",
+ x: point.x,
+ y: point.y - 10,
+ text: String(point.value),
+ textAnchor: "middle",
+ fontSize: 12,
+ });
+ }
+ for (const item of plot.labels)
+ shapes.push({
+ type: "text",
+ x: item.x,
+ y: plot.labelY,
+ text: item.label,
+ textAnchor: "middle",
+ fontSize: 12,
+ });
+ const vector = richVector(
+ {
+ ...node,
+ props: { viewBox: [0, 0, plot.width, plot.height], shapes },
+ },
+ palette,
+ );
+ const chartHeight = (plot.height * innerWidth) / plot.width;
+ result.vectors.push({
+ vector,
+ x: innerX,
+ y: innerY + height,
+ width: innerWidth,
+ height: chartHeight,
+ color: chartColor,
+ });
+ height += chartHeight;
+ } else {
+ const min = Math.min(0, ...data.map((item) => item.value));
+ const max = Math.max(0, ...data.map((item) => item.value));
+ const span = max - min || 1;
+ for (const [index, item] of data.entries()) {
+ prose(`${item.label} ${item.value}`, typeScale.bodyLarge);
+ const fill = Array.isArray(node.props.colors)
+ ? (richColor(node.props.colors[index], palette) ?? chartColor)
+ : chartColor;
+ result.rectangles.push({
+ x: innerX + (innerWidth * (Math.min(0, item.value) - min)) / span,
+ y: innerY + height + spacing.xs,
+ width: (innerWidth * Math.abs(item.value)) / span,
+ height: 6,
+ rx: 3,
+ fill,
+ });
+ height += spacing.lg;
+ }
+ }
+ } else if (node.kind === "divider") {
+ result.rectangles.push({
+ x: innerX,
+ y: innerY,
+ width: innerWidth,
+ height: 1,
+ fill: colors.border,
+ });
+ height = 1;
+ } else if (node.kind === "text" || node.kind === "heading") {
+ prose(
+ richLabel(node, values),
+ number(
+ "fontSize",
+ node.kind === "heading" ? typeScale.title : typeScale.bodyLarge,
+ ),
+ color,
+ node.kind === "heading" || Number(visual.fontWeight) >= 600,
+ );
+ } else if (node.kind === "check")
+ prose(`${current ? "☑" : "☐"} ${label || richString(node, "text")}`);
+ else if (node.kind === "range")
+ prose(
+ `${label} ${richRange(node, current).value}${richString(node, "suffix")}`,
+ );
+ else if (node.kind === "select")
+ prose(
+ `${label} ${richOptions(node).find((option) => option.value === current)?.label ?? current ?? ""}`,
+ );
+ else if (node.kind === "input") prose(`${label}\n${current ?? ""}`);
+ else if (node.kind === "video" || node.kind === "audio")
+ prose(
+ richString(node, "alt", i18n.t("message.renderer.imageFallbackTitle")),
+ );
+ else {
+ const md = richMarkdown(node);
+ if (md !== null) height = add(markdown(md, innerX, innerY, innerWidth));
+ else prose([label, richString(node, "text")].filter(Boolean).join("\n"));
+ }
+ const caption = richString(node, "caption");
+ if (caption) {
+ height += spacing.xs;
+ prose(caption, typeScale.footnote, colors.textSecondary);
+ }
+ height = Math.max(height + pt + pb, number("minHeight"));
+ if (visual.borderWidth)
+ result.rectangles.push({
+ x: left,
+ y: top + margin,
+ width: outerWidth,
+ height,
+ rx: number("borderRadius"),
+ fill: "none",
+ stroke: colors.border,
+ });
+ return margin + height + number("marginBottom");
+ };
+ for (const id of doc.roots)
+ result.height += visit(id, x, y + result.height, width) + spacing.lg;
+ result.height = Math.max(0, result.height - spacing.lg);
+ if (doc.issues)
+ result.height += text(
+ i18n.t("message.richAnswer.incomplete"),
+ x,
+ y + result.height,
+ width,
+ );
+ // Redact visible output after expressions resolve; the caller separately checks cross-node secrets.
+ for (const block of result.textBlocks)
+ block.lines = block.lines.map(redactSensitiveText);
+ for (const { vector } of result.vectors)
+ for (const shape of vector.shapes)
+ if (shape.text) shape.text = redactSensitiveText(shape.text);
+ return result;
+}
+
+const escape = (value: unknown) =>
+ String(value)
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+const attributes = (props: Record<string, unknown>) =>
+ Object.entries(props)
+ .map(
+ ([key, value]) =>
+ `${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}="${escape(value)}"`,
+ )
+ .join(" ");
+export function shareVectorMarkup(item: ShareVector): string {
+ return `<svg x="${item.x}" y="${item.y}" width="${item.width}" height="${item.height}" viewBox="${item.vector.viewBox}" fill="${escape(item.color)}">${item.vector.shapes.map((shape) => `<${shape.type} ${attributes(shape.props)}>${escape(shape.text ?? "")}</${shape.type}>`).join("")}</svg>`;
+}
+export function shareRichLayoutMarkup(
+ layout: ShareRichLayout,
+ width: number,
+): string {
+ return (
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${layout.height}" viewBox="0 0 ${width} ${layout.height}" style="display:block;max-width:100%;height:auto;font-family:-apple-system,BlinkMacSystemFont,Arial,sans-serif">` +
+ layout.rectangles
+ .map(
+ (rect) =>
+ `<rect ${attributes(rect as unknown as Record<string, unknown>)} />`,
+ )
+ .join("") +
+ layout.images
+ .map(
+ (image) =>
+ `<image x="${image.x}" y="${image.y}" width="${image.width}" height="${image.height}" href="${escape(image.uri)}" />`,
+ )
+ .join("") +
+ layout.vectors.map(shareVectorMarkup).join("") +
+ layout.textBlocks
+ .map((block) =>
+ block.lines
+ .map(
+ (line, index) =>
+ `<text x="${block.x}" y="${block.y + index * block.lineHeight}" fill="${escape(block.color)}" font-size="${block.fontSize}" font-weight="${block.bold ? 600 : 400}"${block.monospace ? ' font-family="monospace"' : ""}${block.italic ? ' font-style="italic"' : ""}${block.decoration ? ` text-decoration="${block.decoration}"` : ""}>${escape(line)}</text>`,
+ )
+ .join(""),
+ )
+ .join("") +
+ "</svg>"
+ );
+}
+
+/** The iOS capture keeps browser text shaping and the existing formula/diagram loaders. */
+export function conversationShareRichHtml(
+ source: string,
+ edited: RichValues | undefined,
+ colors: ConversationShareWebViewColors,
+ width: number,
+ markdown: (source: string) => string,
+ layoutMarkdown: ShareMarkdownLayout,
+): string {
+ const { doc, values, children } = shareRichDocument(source, edited);
+ const palette = sharePalette(colors);
+ const visit = (id: string, available: number): string => {
+ const node = doc.nodes.get(id);
+ if (!node) return "";
+ const visual = richVisualStyle(node, palette);
+ const style: Record<string, string | number> = {
+ minWidth: 0,
+ maxWidth: "100%",
+ ...visual,
+ };
+ if (typeof style.minWidth === "number")
+ style.minWidth = Math.min(style.minWidth, available);
+ const css = () =>
+ escape(
+ Object.entries(style)
+ .map(([key, value]) => {
+ const unitless =
+ ["opacity", "flexGrow", "flexShrink", "fontWeight"].includes(
+ key,
+ ) ||
+ (key === "lineHeight" && Number(value) <= 4);
+ return `${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${value}${typeof value === "number" && !unitless ? "px" : ""}`;
+ })
+ .join(";"),
+ );
+ const label = richString(node, "label"),
+ current = values[richString(node, "bind", id)];
+ let content = "";
+ if (richCalculationUnavailable(node, values))
+ content = escape(i18n.t("message.richAnswer.calculationUnavailable"));
+ else if (["row", "grid"].includes(node.kind)) {
+ const aside = richString(node, "layout") === "aside";
+ const mobile = available <= 600 && !aside;
+ const weights = Array.isArray(node.props.weights)
+ ? node.props.weights.filter(
+ (n): n is number =>
+ typeof n === "number" && Number.isFinite(n) && n > 0,
+ )
+ : aside
+ ? [0.7, 1.8]
+ : [];
+ const columns = Math.min(
+ Math.max(1, node.children.length),
+ Math.max(
+ 1,
+ Math.round(
+ visual.flexDirection === "column"
+ ? 1
+ : mobile
+ ? richNumber(node, "mobileColumns", 1)
+ : weights.length || richNumber(node, "columns", 2),
+ ),
+ ),
+ );
+ const gap = Number(visual.gap ?? spacing.sm);
+ const tracks =
+ !mobile && weights.length === columns
+ ? weights
+ : Array.from({ length: columns }, () => 1);
+ const usable = Math.max(1, available - gap * (columns - 1));
+ style.display = "grid";
+ style.gridTemplateColumns = tracks
+ .map((n) => `minmax(0,${n}fr)`)
+ .join(" ");
+ style.gap = gap;
+ content = node.children
+ .map((child, index) =>
+ visit(
+ child,
+ (usable * tracks[index % columns]!) /
+ tracks.reduce((a, b) => a + b, 0),
+ ),
+ )
+ .join("");
+ } else if (
+ ["stack", "group", "form", "details", "tabs"].includes(node.kind)
+ ) {
+ style.display = "flex";
+ style.flexDirection ??= "column";
+ style.gap ??= spacing.sm;
+ if (node.kind === "details" || node.kind === "tabs")
+ content = `<strong>${escape(node.kind === "details" ? label : richString(doc.nodes.get(children(node)[0]!) ?? node, "label"))}</strong>`;
+ content += children(node)
+ .map((child) => visit(child, available))
+ .join("");
+ } else if (node.kind === "svg" || node.kind === "chart") {
+ // Graphics share native geometry, while prose is shaped by the browser.
+ const isolated = JSON.stringify({
+ version: 1,
+ seq: 1,
+ op: "create",
+ ...node,
+ props: { ...node.props, style: undefined, caption: undefined },
+ });
+ content = shareRichLayoutMarkup(
+ layoutConversationShareRichAnswer(
+ isolated,
+ values,
+ colors,
+ 0,
+ 0,
+ available,
+ layoutMarkdown,
+ ),
+ available,
+ );
+ } else if (node.kind === "stat")
+ content = `<div style="font-size:${typeScale.footnote}px;line-height:1.5;color:${escape(colors.textSecondary)}">${escape(label)}</div><div style="font-size:${typeScale.headline}px;line-height:1.3;font-weight:600;margin-top:${spacing.xs}px">${escape(richLabel(node, values))}</div>`;
+ else if (node.kind === "text" || node.kind === "heading") {
+ style.whiteSpace = "pre-wrap";
+ if (node.kind === "heading") {
+ style.fontSize ??= typeScale.title;
+ style.fontWeight ??= 600;
+ }
+ content = escape(richLabel(node, values));
+ } else if (node.kind === "divider") {
+ style.borderTop = `1px solid ${colors.border}`;
+ } else if (node.kind === "check")
+ content = escape(
+ `${current ? "☑" : "☐"} ${label || richString(node, "text")}`,
+ );
+ else if (node.kind === "input")
+ content = `${escape(label)}<div>${escape(current ?? "")}</div>`;
+ else if (node.kind === "range")
+ content = escape(
+ `${label} ${richRange(node, current).value}${richString(node, "suffix")}`,
+ );
+ else if (node.kind === "select")
+ content = escape(
+ `${label} ${richOptions(node).find((option) => option.value === current)?.label ?? current ?? ""}`,
+ );
+ else if (node.kind === "video" || node.kind === "audio")
+ content = escape(richString(node, "alt", node.kind));
+ else {
+ const md = richMarkdown(node);
+ content =
+ md !== null
+ ? markdown(md)
+ : [label, richString(node, "text")]
+ .filter(Boolean)
+ .map(escape)
+ .join("<br>");
+ style.display = "flex";
+ style.flexDirection ??= "column";
+ style.gap ??= spacing.sm;
+ }
+ if (richString(node, "caption"))
+ content += `<div style="font-size:${typeScale.footnote}px;line-height:1.5;color:${escape(colors.textSecondary)};margin-top:${spacing.xs}px">${escape(richString(node, "caption"))}</div>`;
+ return `<div style="box-sizing:border-box;${css()}">${content}</div>`;
+ };
+ return `<div style="display:flex;flex-direction:column;gap:${spacing.lg}px;min-width:0">${doc.roots.map((id) => visit(id, width)).join("")}${doc.issues ? `<div>${escape(i18n.t("message.richAnswer.incomplete"))}</div>` : ""}</div>`;
+}
diff --git a/apps/mobile/src/session/conversationShareRichSvg.ts b/apps/mobile/src/session/conversationShareRichSvg.ts
index 24d5acb407..9a798ba2aa 100644
--- a/apps/mobile/src/session/conversationShareRichSvg.ts
+++ b/apps/mobile/src/session/conversationShareRichSvg.ts
@@ -1,3 +1,8 @@
+import { splitRichAnswer } from "@cindy/maker-shared/rich-answer";
+import {
+ layoutConversationShareRichAnswer,
+ type ShareVector,
+} from "./conversationShareRichAnswer";
import { latexToUnicodeApproximation } from "@cindy/maker-shared/math-markdown";
import { i18n } from "@/i18n";
import { tokenizeCode } from "@/session/codeHighlight";
@@ -63,16 +68,17 @@ export function layoutConversationShareRichBody(
const textBlocks: ConversationShareSvgTextBlock[] = [];
const rectangles: ShareSvgRect[] = [];
const images: ConversationShareSvgLayout["images"] = [];
+ const vectors: ShareVector[] = [];
let cursor = y;
- const gap = spacing.md;
+ const gap = spacing.lg;
function text(
runs: Run[],
left: number,
top: number,
available: number,
- size: number = typeScale.body,
- leading: number = lineHeight.body,
+ size: number = typeScale.bodyLarge,
+ leading: number = lineHeight.bodyLarge,
): number {
if (available <= 0) return 0;
// Even a single wide, bold glyph must fit in a narrow table cell.
@@ -131,8 +137,8 @@ export function layoutConversationShareRichBody(
left: number,
top: number,
available: number,
- size: number = typeScale.body,
- leading: number = lineHeight.body,
+ size: number = typeScale.bodyLarge,
+ leading: number = lineHeight.bodyLarge,
bold = false,
): number {
let height = 0;
@@ -277,7 +283,7 @@ export function layoutConversationShareRichBody(
);
const markerWidth = Math.max(
spacing.xl,
- markerUnits * typeScale.body + spacing.sm,
+ markerUnits * typeScale.bodyLarge + spacing.sm,
);
text(
[{ text: marker, color: colors.textPrimary }],
@@ -297,22 +303,59 @@ export function layoutConversationShareRichBody(
: value.level === 2
? typeScale.subtitle
: typeScale.body
- : typeScale.body;
+ : typeScale.bodyLarge;
cursor += inlines(
value.inlines,
x,
cursor,
width,
size,
- heading ? lineHeight.listTitle : lineHeight.body,
+ heading ? lineHeight.listTitle : lineHeight.bodyLarge,
heading,
);
}
cursor += gap;
}
- const markdown = (source: string) =>
- parseMobileMarkdown(source).forEach(block);
+ const markdown = (source: string) => {
+ if (message.kind !== "assistant") {
+ parseMobileMarkdown(source).forEach(block);
+ return;
+ }
+ for (const part of splitRichAnswer(source)) {
+ if (part.kind === "markdown") {
+ parseMobileMarkdown(part.source).forEach(block);
+ continue;
+ }
+ const layout = layoutConversationShareRichAnswer(
+ part.source,
+ message.richValues?.[part.key],
+ colors,
+ x,
+ cursor,
+ width,
+ (text, left, top, available) =>
+ layoutConversationShareRichBody(
+ {
+ ...message,
+ kind: "user",
+ body: text,
+ bodyParts: undefined,
+ secondaryBody: undefined,
+ },
+ colors,
+ left,
+ top,
+ available,
+ ),
+ );
+ textBlocks.push(...layout.textBlocks);
+ rectangles.push(...layout.rectangles);
+ images.push(...layout.images);
+ vectors.push(...layout.vectors);
+ cursor += layout.height + gap;
+ }
+ };
if (message.bodyParts) {
for (const part of message.bodyParts) {
if (part.kind === "text") markdown(part.text);
@@ -332,6 +375,7 @@ export function layoutConversationShareRichBody(
textBlocks,
rectangles,
images,
+ vectors,
height: Math.max(0, cursor - y - gap),
};
}
diff --git a/apps/mobile/src/session/conversationShareSvgLayout.ts b/apps/mobile/src/session/conversationShareSvgLayout.ts
index b13584788f..326debb553 100644
--- a/apps/mobile/src/session/conversationShareSvgLayout.ts
+++ b/apps/mobile/src/session/conversationShareSvgLayout.ts
@@ -1,3 +1,8 @@
+import { hasRichAnswer } from "@cindy/maker-shared/rich-answer";
+import {
+ conversationShareReadableBody,
+ type ShareVector,
+} from "./conversationShareRichAnswer";
import { redactSensitiveText } from "@cindy/maker-shared/error-redaction";
import { summarizeMessageBubblePresentation } from "@cindy/maker-shared/message-presentation";
@@ -21,13 +26,13 @@ import {
type ConversationShareWebViewColors,
} from "@/session/conversationShareWebViewHtml";
import { buildMessageContentLayout } from "@/session/messageContentLayout";
-import { spacing } from "@/theme/tokens";
+import { spacing, typeScale, lineHeight } from "@/theme/tokens";
const PADDING_X = CONVERSATION_SHARE_PADDING_X;
const PADDING_Y = CONVERSATION_SHARE_PADDING_Y;
const MESSAGE_GAP = spacing.lg;
-const TEXT_FONT_SIZE = 15;
-const TEXT_LINE_HEIGHT = 22;
+const TEXT_FONT_SIZE = typeScale.bodyLarge;
+const TEXT_LINE_HEIGHT = lineHeight.bodyLarge;
const META_FONT_SIZE = 12;
const META_LINE_HEIGHT = 18;
const MAX_OUTPUT_PIXELS = 12_000_000;
@@ -48,6 +53,7 @@ export interface ConversationShareSvgTextBlock {
export interface ConversationShareSvgBubble {
rectangles?: ShareSvgRect[];
+ vectors?: ShareVector[];
fill?: string;
height: number;
stroke?: string;
@@ -85,7 +91,10 @@ export function conversationShareSvgRenderSize(
// SvgView allocates its bitmap in physical pixels, not React Native points.
Math.sqrt(
MAX_OUTPUT_PIXELS /
- Math.max(1, layout.width * layout.height * Math.max(1, pixelRatio) ** 2),
+ Math.max(
+ 1,
+ layout.width * layout.height * Math.max(1, pixelRatio) ** 2,
+ ),
),
);
return {
@@ -141,11 +150,14 @@ export function buildConversationShareSvgLayout({
}).density === "compact";
const paddingY = user ? (compact ? spacing.sm : spacing.md) : spacing.xs;
const minBubbleHeight = user ? 20 + paddingY * 2 : 30;
- const ownBubble = user && message.ownUserBubble ? colors.ownUserBubble : null;
+ const ownBubble =
+ user && message.ownUserBubble ? colors.ownUserBubble : null;
const bubbleFill = user
? (ownBubble?.background ?? colors.surfaceElevated)
: undefined;
- const bubbleStroke = user ? (ownBubble?.border ?? colors.border) : undefined;
+ const bubbleStroke = user
+ ? (ownBubble?.border ?? colors.border)
+ : undefined;
const textWidth = bubbleWidth - horizontalPadding * 2;
const appendMetadata = (text: string, color: string, gap: number) => {
const lines = wrapSvgText(
@@ -213,7 +225,11 @@ export function buildConversationShareSvgLayout({
});
// Preserve the existing whole-message redaction path for secrets spanning
// formatting, paragraphs or images. Never redact isolated styled runs.
- if (!needsRedaction && bodyParts.length > 0) {
+ if (
+ !needsRedaction &&
+ (bodyParts.length > 0 ||
+ (message.kind === "assistant" && hasRichAnswer(message.body)))
+ ) {
const body = layoutConversationShareRichBody(
message,
colors,
@@ -231,6 +247,7 @@ export function buildConversationShareSvgLayout({
stroke: bubbleStroke,
textBlocks: body.textBlocks,
rectangles: body.rectangles,
+ vectors: body.vectors,
});
images.push(...body.images);
cursorY += height + MESSAGE_GAP;
@@ -330,7 +347,9 @@ function conversationShareBodyParts(
else parts.push(part);
};
const markdown = (text: string) => {
- for (const block of parseMobileMarkdown(text)) {
+ for (const block of parseMobileMarkdown(
+ conversationShareReadableBody(message, text),
+ )) {
for (const part of markdownBlockParts(block, message.images))
append(part);
append({ text: "\n" });
@@ -448,7 +467,8 @@ function markdownInlineParts(
let struck = false;
for (const inline of inlines) {
const image = inline.type === "image" ? images?.get(inline.url) : undefined;
- const nextStruck = !image && mobileMarkdownInlineHasMark(inline, "strikethrough");
+ const nextStruck =
+ !image && mobileMarkdownInlineHasMark(inline, "strikethrough");
if (struck !== nextStruck) {
appendText("~~");
struck = nextStruck;
diff --git a/apps/mobile/src/session/conversationShareWebViewHtml.ts b/apps/mobile/src/session/conversationShareWebViewHtml.ts
index 9ccd61b4e4..cb52d869a8 100644
--- a/apps/mobile/src/session/conversationShareWebViewHtml.ts
+++ b/apps/mobile/src/session/conversationShareWebViewHtml.ts
@@ -1,3 +1,12 @@
+import {
+ splitRichAnswer,
+ type RichValues,
+} from "@cindy/maker-shared/rich-answer";
+import {
+ conversationShareReadableBody,
+ conversationShareRichHtml,
+} from "./conversationShareRichAnswer";
+import { layoutConversationShareRichBody } from "./conversationShareRichSvg";
import { redactSensitiveText } from "@cindy/maker-shared/error-redaction";
import { summarizeMessageBubblePresentation } from "@cindy/maker-shared/message-presentation";
import { buildKatexLoaderJs } from "@/session/mathWebViewHtml";
@@ -24,6 +33,8 @@ export interface ConversationShareMessage {
ownUserBubble?: boolean;
/** Export-only decoded images, keyed by attachment/Markdown source. */
images?: ReadonlyMap<string, ConversationShareImage>;
+ richStateKey?: string;
+ richValues?: Readonly<Record<number, RichValues>>;
}
export interface ConversationShareImage {
@@ -44,6 +55,9 @@ export type ConversationShareBodyPart =
export interface ConversationShareWebViewColors {
background: string;
+ success?: string;
+ warning?: string;
+ danger?: string;
surfaceElevated: string;
border: string;
codeSurface: string;
@@ -74,11 +88,19 @@ export const CONVERSATION_SHARE_PADDING_Y = spacing.xl;
export const CONVERSATION_SHARE_HAIRLINE = 0.5;
/** 使用聊天面板的视口(双栏时不是整个窗口),两种出图路径共用可读宽度。 */
-export function buildConversationShareContentWidth(viewport: { width: number; height: number }): number {
- return Math.max(280, Math.round(buildMobileReadableViewportLayout({
- screenWidth: viewport.width,
- screenHeight: viewport.height,
- }).contentWidth));
+export function buildConversationShareContentWidth(viewport: {
+ width: number;
+ height: number;
+}): number {
+ return Math.max(
+ 280,
+ Math.round(
+ buildMobileReadableViewportLayout({
+ screenWidth: viewport.width,
+ screenHeight: viewport.height,
+ }).contentWidth,
+ ),
+ );
}
export function buildConversationShareHtml({
@@ -90,10 +112,7 @@ export function buildConversationShareHtml({
selectedMessages,
}: BuildConversationShareHtmlOptions): string {
const messageIndex = new Map(allShareableIds.map((id, index) => [id, index]));
- const markdownOptions = buildConversationShareMarkdownOptions(
- contentWidth,
- colors,
- );
+ const markdownOptions = buildConversationShareMarkdownOptions(colors);
const messagesHtml: string[] = [];
let previousIndex: number | null = null;
@@ -106,7 +125,14 @@ export function buildConversationShareHtml({
) {
messagesHtml.push('<div class="share-gap" aria-hidden="true">⋯</div>');
}
- messagesHtml.push(buildMessageHtml(message, markdownOptions));
+ messagesHtml.push(
+ buildMessageHtml(
+ message,
+ markdownOptions,
+ colors,
+ contentWidth - CONVERSATION_SHARE_PADDING_X * 2,
+ ),
+ );
previousIndex = currentIndex;
}
@@ -153,6 +179,8 @@ export function buildConversationShareHtml({
function buildMessageHtml(
message: ConversationShareMessage,
markdownOptions: SelectableMarkdownHtmlOptions,
+ colors: ConversationShareWebViewColors,
+ width: number,
): string {
markdownOptions = {
...markdownOptions,
@@ -164,27 +192,72 @@ function buildMessageHtml(
)
: [message.body];
if (message.secondaryBody) texts.push(message.secondaryBody);
+ const visibleTexts = texts.map((text) =>
+ conversationShareReadableBody(message, text),
+ );
// Redaction can consume image delimiters as well as URLs. Let the existing
// SVG path own all image-bearing text that needs redaction, even when image
// preparation failed; never parse damaged Markdown or expose its source URL.
if (
- texts.some((text) => redactSensitiveText(text) !== text) &&
- texts.some((text) => collectMobileMarkdownImages(text).length > 0)
+ visibleTexts.some((text) => redactSensitiveText(text) !== text) &&
+ visibleTexts.some((text) => collectMobileMarkdownImages(text).length > 0)
) {
throw new Error("conversation-share-image-requires-svg");
}
- const body = redactSensitiveText(message.body).trim();
+ const readable = conversationShareReadableBody(message, message.body);
+ // Parse operations before redaction: changing a string inside JSON can invalidate the whole document.
+ // Cross-node secrets still take the existing whole-message redaction fallback.
+ if (readable !== redactSensitiveText(readable)) {
+ message = { ...message, body: readable, richValues: undefined };
+ }
+ const body = (
+ message.kind === "assistant"
+ ? message.body
+ : redactSensitiveText(message.body)
+ ).trim();
+ const renderBody = (source: string) =>
+ message.kind === "assistant"
+ ? splitRichAnswer(source)
+ .map((part) => {
+ if (part.kind === "markdown")
+ return buildSelectableMarkdownFragmentHtml(
+ redactSensitiveText(part.source),
+ markdownOptions,
+ );
+ return conversationShareRichHtml(
+ part.source,
+ message.richValues?.[part.key],
+ colors,
+ width,
+ (text) =>
+ buildSelectableMarkdownFragmentHtml(text, markdownOptions),
+ (text, left, top, available) =>
+ layoutConversationShareRichBody(
+ {
+ ...message,
+ kind: "user",
+ body: text,
+ bodyParts: undefined,
+ secondaryBody: undefined,
+ },
+ colors,
+ left,
+ top,
+ available,
+ ),
+ );
+ })
+ .join("")
+ : buildSelectableMarkdownFragmentHtml(source, markdownOptions);
const secondaryBody = message.secondaryBody
? redactSensitiveText(message.secondaryBody).trim()
: "";
const bodyHtml = message.bodyParts
? buildBodyPartsHtml(message.bodyParts, markdownOptions)
: body
- ? buildSelectableMarkdownFragmentHtml(body, markdownOptions)
+ ? renderBody(body)
: "";
- const secondaryHtml = secondaryBody
- ? buildSelectableMarkdownFragmentHtml(secondaryBody, markdownOptions)
- : "";
+ const secondaryHtml = secondaryBody ? renderBody(secondaryBody) : "";
const attachmentsHtml = buildAttachmentsHtml(
message.attachments ?? [],
message.images,
@@ -267,12 +340,10 @@ function buildAttachmentsHtml(
}
function buildConversationShareMarkdownOptions(
- contentWidth: number,
colors: ConversationShareWebViewColors,
): SelectableMarkdownHtmlOptions {
- const layout = buildMessageContentLayout({ screenWidth: contentWidth });
return {
- bodyGap: layout.markdownBodyGap,
+ bodyGap: spacing.lg,
borderColor: colors.border,
chipColor: colors.codeSurface,
fontSize: typeScale.bodyLarge,
@@ -307,7 +378,7 @@ function buildConversationShareCss({
}): string {
// 尺寸与间距照搬聊天消息流(MessageRenderer):同屏宽下换行、气泡与附件一致。
const layout = buildMessageContentLayout({ screenWidth: width });
- const bodyGap = layout.markdownBodyGap;
+ const bodyGap = spacing.lg;
return `
html, body {
margin: 0;
diff --git a/apps/mobile/src/session/shareSelectionStore.ts b/apps/mobile/src/session/shareSelectionStore.ts
index 94de9d4f9a..2478c24450 100644
--- a/apps/mobile/src/session/shareSelectionStore.ts
+++ b/apps/mobile/src/session/shareSelectionStore.ts
@@ -68,6 +68,21 @@ export const shareSelectionStore = {
selectedIds.clear();
notify();
},
+ /** Hand off to the system sheet now; restore only if opening it fails. */
+ exitForShare(): () => boolean {
+ const sessionId = activeSessionId;
+ const selection = Array.from(selectedIds);
+ shareSelectionStore.exit();
+ const exitedRevision = revision;
+ return () => {
+ // A newer selection (even one subsequently cancelled) owns the UI now.
+ if (!sessionId || revision !== exitedRevision) return false;
+ activeSessionId = sessionId;
+ for (const id of selection) selectedIds.add(id);
+ notify();
+ return true;
+ };
+ },
toggle(clientId: string): void {
if (!clientId) return;
if (selectedIds.has(clientId)) selectedIds.delete(clientId);
diff --git a/apps/mobile/src/session/useConversationShareImages.ts b/apps/mobile/src/session/useConversationShareImages.ts
index dc8d71da02..4a84f2fd31 100644
--- a/apps/mobile/src/session/useConversationShareImages.ts
+++ b/apps/mobile/src/session/useConversationShareImages.ts
@@ -52,9 +52,13 @@ async function readShareImageFile(
if (!file.exists || file.size <= 0 || file.size > MAX_IMAGE_BYTES)
return null;
// Android's encoded-image size reader accepts file:// but rejects data:.
- const size = await readWithShareImageCancellation(() => Image.getSize(uri), signal);
+ const size = await readWithShareImageCancellation(
+ () => Image.getSize(uri),
+ signal,
+ );
if (!canRead()) return null;
- const dataUri = embeddedUri ?? `data:${mimeType};base64,${await file.base64()}`;
+ const dataUri =
+ embeddedUri ?? `data:${mimeType};base64,${await file.base64()}`;
return canRead() ? { uri: dataUri, ...size } : null;
}
@@ -69,7 +73,10 @@ async function readShareImageDataUri(
if (!header) {
// iOS can size other data-image encodings. Preserve that existing support;
// an unsupported native format still follows the usual placeholder path.
- const size = await readWithShareImageCancellation(() => Image.getSize(uri), signal);
+ const size = await readWithShareImageCancellation(
+ () => Image.getSize(uri),
+ signal,
+ );
return canRead() ? { uri, ...size } : null;
}
if (uri.length === header[0].length) return null;
@@ -97,7 +104,9 @@ async function readShareImageDataUri(
});
// Cancellation cannot stop this native write. Clean up again if a late
// completion recreates the file after the immediate finally cleanup.
- const cleanupLateWrite = () => { if (signal.aborted) cleanup(); };
+ const cleanupLateWrite = () => {
+ if (signal.aborted) cleanup();
+ };
void write.then(cleanupLateWrite, cleanupLateWrite);
return write;
}, signal);
@@ -152,8 +161,11 @@ async function loadShareImage(
// Only download objects whose size the controlled desktop resolver knows.
// Arbitrary HTTP sources have no trusted pre-transfer bound: keep alt text.
if (/^https?:\/\//i.test(uri)) {
- return withDownloadedRemoteMediaFile(uri, mimeType, MAX_IMAGE_BYTES, (file) =>
- readShareImageFile(file.uri, mimeType, canRead, signal),
+ return withDownloadedRemoteMediaFile(
+ uri,
+ mimeType,
+ MAX_IMAGE_BYTES,
+ (file) => readShareImageFile(file.uri, mimeType, canRead, signal),
);
}
}
@@ -181,19 +193,28 @@ interface ShareImageJob {
export function useConversationShareImages(
messages: readonly ConversationShareMessage[],
resolve: ResolveRemoteMediaFn,
- { workdir, remoteHostId, sessionId }: ConversationShareImageContext,
+ {
+ workdir,
+ remoteHostId,
+ sessionId,
+ snapshotRichValues,
+ }: ConversationShareImageContext,
) {
const [job, setJob] = useState<ShareImageJob | null>(null);
const prepare = useCallback(() => {
return new Promise<readonly ConversationShareMessage[]>((finish) => {
setJob({
- sourceMessages: messages,
+ sourceMessages: messages.map((message) =>
+ message.kind === "assistant" && snapshotRichValues
+ ? { ...message, richValues: snapshotRichValues(message) }
+ : message,
+ ),
resolve,
context: { workdir, remoteHostId, sessionId },
finish,
});
});
- }, [messages, resolve, workdir, remoteHostId, sessionId]);
+ }, [messages, resolve, workdir, remoteHostId, sessionId, snapshotRichValues]);
const cancel = useCallback(() => setJob(null), []);
const selectionKey = JSON.stringify(
messages.map((message) => message.clientId),