Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修复分享图片内容渲染和分享按钮布局 (#5083)
Dash80186f898661
diff --git a/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsxindex b75d05eb85..d63576940c 100644--- a/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx+++ b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx@@ -281,8 +281,12 @@ describe("SVG export lifecycle", () => {expect(native.capture).not.toHaveBeenCalled();expect(svgNodes(bad)).toHaveLength(0);expect(svgNodes(good)).toEqual(goodNodes);- expect(host.textContent).toContain("broken attachment");- expect(host.textContent).toContain("broken inline");+ expect(host.textContent?.replace(/\u00a0/g, " ")).toContain(+ "broken attachment",+ );+ expect(host.textContent?.replace(/\u00a0/g, " ")).toContain(+ "broken inline",+ );expect(host.textContent).not.toContain("cindy-media://bad");await act(async () => {lateLoads.forEach((load) => load());@@ -315,7 +319,9 @@ describe("SVG export lifecycle", () => {});expect(svgNodes(good)).toHaveLength(2);expect(svgNodes(bad)).toHaveLength(0);- expect(host.textContent).toContain("broken inline");+ expect(host.textContent?.replace(/\u00a0/g, " ")).toContain(+ "broken inline",+ );// Bundled resource names are not queryable via Android's URI-only cache API.expect(native.queryCache.mock.calls.every(([uris]) =>diff --git a/apps/mobile/src/__tests__/ShareSelectionBar.test.tsx b/apps/mobile/src/__tests__/ShareSelectionBar.test.tsxnew file mode 100644index 0000000000..7b9ccc78a0--- /dev/null+++ b/apps/mobile/src/__tests__/ShareSelectionBar.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { act, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vitest";+import { ShareSelectionBar } from "@/session/ShareSelectionBar";++const state = vi.hoisted(() => ({ fontScale: 1, layout: undefined as any }));+vi.mock("react-native", () => ({+ useWindowDimensions: () => ({ width: 1000, fontScale: state.fontScale }),+ StyleSheet: { create: (styles: any) => styles, hairlineWidth: 1 },+ View: ({ children, testID, onLayout, style }: any) => {+ if (testID === "session.shareImage.bar") state.layout = onLayout;+ return (+ <div+ data-testid={testID}+ data-direction={+ Object.assign({}, ...[style].flat().filter(Boolean)).flexDirection+ }+ >+ {children}+ </div>+ );+ },+ Pressable: ({ children }: any) => <button>{children}</button>,+}));+vi.mock("@/theme", () => ({+ useTheme: () => ({ colors: {} }),+ useThemedStyles: (factory: any) => factory({}),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("lucide-react-native", () => ({ Share: () => null, X: () => null }));+vi.mock("@/components/AppText", () => ({+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}));+vi.mock("@/session/HomeHeaderGlassButton", () => ({+ HomeHeaderGlassButton: () => null,+}));+vi.mock("@/session/ShareImageNativeButton", () => ({+ ShareImageNativeButton: ({ children }: { children: ReactNode }) => (+ <>{children}</>+ ),+}));++it("uses panel width and responds to resizing and larger fonts", async () => {+ const host = document.createElement("div");+ const root = createRoot(host);+ const render = () =>+ root.render(+ <ShareSelectionBar count={1} onCancel={() => {}} onShare={() => {}} />,+ );+ try {+ await act(render);+ const bar = () =>+ host.querySelector('[data-testid="session.shareImage.bar"]')!;+ await act(() => state.layout({ nativeEvent: { layout: { width: 320 } } }));+ expect(bar().getAttribute("data-direction")).toBe("column");+ await act(() => state.layout({ nativeEvent: { layout: { width: 500 } } }));+ expect(bar().getAttribute("data-direction")).toBe("row");+ state.fontScale = 1.5;+ await act(render);+ expect(bar().getAttribute("data-direction")).toBe("column");+ } finally {+ await act(() => root.unmount());+ state.fontScale = 1;+ }+});diff --git a/apps/mobile/src/__tests__/conversationShareRichSvg.test.ts b/apps/mobile/src/__tests__/conversationShareRichSvg.test.tsnew file mode 100644index 0000000000..84ef04585e--- /dev/null+++ b/apps/mobile/src/__tests__/conversationShareRichSvg.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from "vitest";+import { buildConversationShareSvgLayout } from "@/session/conversationShareSvgLayout";+import { lightColors, darkColors } from "@/theme/tokens";+import {+ layoutConversationShareRichBody,+ conservativeArialGlyphWidthEm,+} from "@/session/conversationShareRichSvg";++describe("structured share fallback", () => {+ it("fits Chinese, emoji and bold text inside extremely narrow cells", () => {+ const cells = Array.from({ length: 30 }, () => "**中😀@**");+ const row = `|${cells.join("|")}|`;+ const layout = layoutConversationShareRichBody(+ {+ clientId: "m",+ kind: "assistant",+ body: `${row}\n|${cells.map(() => "---").join("|")}|\n${row}`,+ },+ {+ background: "white",+ surfaceElevated: "white",+ border: "gray",+ codeSurface: "gray",+ inlineCode: "black",+ surfaceChip: "gray",+ textPrimary: "black",+ textSecondary: "gray",+ textTertiary: "gray",+ syntax: {},+ },+ 20,+ 0,+ 240,+ );+ expect(layout.rectangles).toHaveLength(60);+ expect(+ layout.textBlocks.map((block) => block.lines.join("")).join(""),+ ).toBe("中😀@".repeat(60));+ for (const block of layout.textBlocks) {+ const cell = layout.rectangles.find(+ (r) =>+ block.x >= r.x &&+ block.x < r.x + r.width &&+ block.y > r.y &&+ block.y <= r.y + r.height,+ )!;+ expect(cell).toBeDefined();+ const width = Array.from(block.lines[0]!).reduce(+ (sum, char) =>+ sum ++ conservativeArialGlyphWidthEm(char) *+ block.fontSize *+ (block.bold ? 1.08 : 1),+ 0,+ );+ expect(block.x + width).toBeLessThanOrEqual(cell.x + cell.width);+ }+ });+ it.each([lightColors, darkColors])(+ "retains Markdown styles and table cells within the canvas",+ (c) => {+ const colors = {+ background: c.surface,+ surfaceElevated: c.surfaceElevated,+ border: c.border,+ codeSurface: c.chatCodeSurface,+ inlineCode: c.chatInlineCodeText,+ surfaceChip: c.surfaceChip,+ textPrimary: c.textPrimary,+ textSecondary: c.textSecondary,+ textTertiary: c.textTertiary,+ syntax: { keyword: c.syntaxKeyword, string: c.syntaxString },+ };+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ colors,+ width: 320,+ messages: [+ {+ clientId: "m",+ kind: "assistant",+ body: '# Heading\n\n**bold** *italic* ~~deleted~~ [link](https://example.com) `code`\n\n| A | B | C | D |\n|---|---|---|---|\n| 中文很长需要换行 | **value** | 12345678901234567890 | last |\n\n```js\nconst value = "hello";\n return value;\n```',+ },+ ],+ });+ const body = layout.bubbles[0]!;+ const text = body.textBlocks;+ const find = (word: string) =>+ text.find((t) => t.lines.join("") === word);+ expect(find("Heading")?.fontSize).toBeGreaterThan(find("bold")!.fontSize);+ expect(find("bold")?.bold).toBe(true);+ expect(find("italic")?.italic).toBe(true);+ expect(find("deleted")?.decoration).toBe("line-through");+ expect(find("link")?.decoration).toBe("underline");+ expect(find("code")?.monospace).toBe(true);+ expect(find("const")?.color).toBe(c.syntaxKeyword);+ expect(+ text.some((t) => t.monospace && t.lines[0]?.startsWith(" ")),+ ).toBe(true);+ const cells = body.rectangles!.filter((r) => r.rx === undefined);+ expect(cells).toHaveLength(8);+ expect(+ cells.slice(0, 4).every((cell) => cell.fill === colors.surfaceChip),+ ).toBe(true);+ expect(cells.slice(4).every((cell) => cell.fill === "none")).toBe(true);+ expect(cells[4]!.height).toBeGreaterThan(cells[0]!.height);+ for (const r of body.rectangles!) {+ expect(r.x).toBeGreaterThanOrEqual(body.x);+ expect(r.x + r.width).toBeLessThanOrEqual(body.x + body.width + 0.01);+ expect(r.y + r.height).toBeLessThanOrEqual(body.y + body.height);+ }+ expect(text.map((t) => t.lines.join("")).join("")).not.toContain(" | ");+ },+ );++ it("keeps repeated images inside their own table cells and grows the row", () => {+ const image = {+ uri: "data:image/png;base64,YQ==",+ width: 100,+ height: 150,+ };+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ width: 390,+ colors: {+ background: "white",+ surfaceElevated: "white",+ border: "gray",+ codeSurface: "gray",+ inlineCode: "black",+ surfaceChip: "gray",+ textPrimary: "black",+ textSecondary: "gray",+ textTertiary: "gray",+ syntax: {},+ },+ messages: [+ {+ clientId: "m",+ kind: "user",+ body: "| A | B |\n|---|---|\n|  |  |",+ images: new Map([["cindy-media://same", image]]),+ },+ ],+ });+ expect(layout.images).toHaveLength(2);+ const [left, right] = layout.images;+ expect(left!.y).toBe(right!.y);+ expect(left!.x + left!.width).toBeLessThan(right!.x);+ const row = layout.bubbles[0]!.rectangles![2]!;+ expect(row.fill).toBe("none");+ expect(left!.y + left!.height).toBeLessThan(row.y + row.height);+ });+});diff --git a/apps/mobile/src/__tests__/conversationShareSvg.test.ts b/apps/mobile/src/__tests__/conversationShareSvg.test.tsindex bde997609c..4c3b39557d 100644--- a/apps/mobile/src/__tests__/conversationShareSvg.test.ts+++ b/apps/mobile/src/__tests__/conversationShareSvg.test.ts@@ -232,7 +232,7 @@ describe("ConversationShareSvg", () => {expect(layout.images).toHaveLength(3);const bubble = layout.bubbles[0]!;const text = bubble.textBlocks;- expect(text.map((block) => block.lines.join(""))).toEqual([+ expect(text.map((block) => block.lines.join("").trim())).toEqual(["before","middle","after",@@ -418,17 +418,25 @@ describe("ConversationShareSvg", () => {width: 390,});- expect(layout.bubbles[0]?.textBlocks[0]?.lines).toEqual([- "[x] shipped",- "[ ] pending",- "1. first",- "* bullet",- "2. [x] ordered done",- "3. [ ] ordered pending",+ expect(+ layout.bubbles[0]?.textBlocks.flatMap((block) => block.lines),+ ).toEqual([+ "☑",+ "shipped",+ "☐",+ "pending",+ "1.",+ "first",+ "*",+ "bullet",+ "2. ☑",+ "ordered done",+ "3. ☐",+ "ordered pending",]);});- it("preserves semantic plaintext markers without altering chip labels", () => {+ it("renders quote and strikethrough styling without altering chip labels", () => {const layout = buildConversationShareSvgLayout({allShareableIds: ["chips", "markdown"],colors,@@ -452,16 +460,19 @@ describe("ConversationShareSvg", () => {width: 390,});- expect(layout.bubbles[0]?.textBlocks[0]?.lines).toEqual([- "quoted context",- "pasted text",- "/review",- ]);- expect(layout.bubbles[1]?.textBlocks[0]?.lines).toEqual([- "> do not deploy",- "> until reviewed",- "Use v2, ~~not v1~~",- ]);+ expect(+ layout.bubbles[0]?.textBlocks.flatMap((block) => block.lines),+ ).toEqual(["quoted context", "pasted text", "/review"]);+ expect(+ layout.bubbles[1]?.textBlocks.flatMap((block) => block.lines),+ ).toEqual(["do not deploy", "until reviewed", "Use v2, ", "not v1"]);+ expect(layout.bubbles[1]?.rectangles?.[0]).toMatchObject({+ width: 2,+ fill: colors.border,+ });+ expect(layout.bubbles[1]?.textBlocks.at(-1)?.decoration).toBe(+ "line-through",+ );});it("waits for both footer assets before allowing export", async () => {diff --git a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.tsindex 21e8dcc1c7..ec2afe9ad6 100644--- a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts+++ b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts@@ -1,303 +1,390 @@-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { describe, expect, it } from "vitest";import {buildConversationShareHtml,type ConversationShareWebViewColors,-} from '@/session/conversationShareWebViewHtml';-import { i18n } from '@/i18n';-import { buildConversationShareSvgLayout } from '@/session/conversationShareSvgLayout';+} from "@/session/conversationShareWebViewHtml";+import { i18n } from "@/i18n";+import { buildConversationShareSvgLayout } from "@/session/conversationShareSvgLayout";const colors: ConversationShareWebViewColors = {- background: '#ffffff',- border: '#dddddd',- codeSurface: '#f5f5f5',+ background: "#ffffff",+ border: "#dddddd",+ codeSurface: "#f5f5f5",dark: true,- inlineCode: '#333333',- surfaceChip: '#f2f2f2',- surfaceElevated: '#fafafa',+ inlineCode: "#333333",+ surfaceChip: "#f2f2f2",+ surfaceElevated: "#fafafa",syntax: {- comment: '#777777',- function: '#0055aa',- keyword: '#aa0055',- number: '#995500',- property: '#006655',- string: '#885500',+ comment: "#777777",+ function: "#0055aa",+ keyword: "#aa0055",+ number: "#995500",+ property: "#006655",+ string: "#885500",},- textPrimary: '#111111',- textSecondary: '#555555',- textTertiary: '#888888',+ textPrimary: "#111111",+ textSecondary: "#555555",+ textTertiary: "#888888",};function buildRichConversationHtml(): string {return buildConversationShareHtml({- allShareableIds: ['math', 'diagram'],+ allShareableIds: ["math", "diagram"],colors,contentWidth: 390,selectedMessages: [{- body: ['$$', 'x^2 + y^2', '$$'].join('\n'),- clientId: 'math',- kind: 'assistant',+ body: ["$$", "x^2 + y^2", "$$"].join("\n"),+ clientId: "math",+ kind: "assistant",},{- body: ['```mermaid', 'graph TD', 'A --> B', '```'].join('\n'),- clientId: 'diagram',- kind: 'assistant',+ body: ["```mermaid", "graph TD", "A --> B", "```"].join("\n"),+ clientId: "diagram",+ kind: "assistant",},],});}-describe('buildConversationShareHtml 富内容导出', () => {+describe("buildConversationShareHtml 富内容导出", () => {it.each([- { contentWidth: 360, minWidth: 96, dark: false },- { contentWidth: 360, minWidth: 96, dark: true },- { contentWidth: 390, minWidth: 112, dark: false },- { contentWidth: 390, minWidth: 112, dark: true },- ])('分享表格保留列宽($contentWidth / dark=$dark),不套用文件预览等宽布局', ({ contentWidth, minWidth, dark }) => {- const html = buildConversationShareHtml({- allShareableIds: ['table'], colors: { ...colors, dark }, contentWidth,- selectedMessages: [{- clientId: 'table', kind: 'assistant',- body: '| A | B | C | D |\n| --- | --- | --- | --- |\n| Alpha | Beta | Gamma | Delta |',- }],- });- expect(html).toContain('<table>');- expect(html).toMatch(new RegExp(`th, td \\{[^}]*min-width:\\s*${minWidth}px`, 's'));- expect(html).toMatch(/table \{[^}]*display:\s*block[^}]*max-width:\s*100%[^}]*overflow-x:\s*auto/s);- expect(html).not.toMatch(/table \{[^}]*table-layout:\s*fixed/s);- });+ { contentWidth: 360, dark: false },+ { contentWidth: 360, dark: true },+ { contentWidth: 390, dark: false },+ { contentWidth: 390, dark: true },+ ])(+ "分享图片的表格换行适配画布($contentWidth / dark=$dark)",+ ({ contentWidth, dark }) => {+ const html = buildConversationShareHtml({+ allShareableIds: ["table"],+ colors: { ...colors, dark },+ contentWidth,+ selectedMessages: [+ {+ clientId: "table",+ kind: "assistant",+ body: "| A | B | C | D |\n| --- | --- | --- | --- |\n| Alpha | Beta | Gamma | Delta |",+ },+ ],+ });+ expect(html).toContain("<table>");+ expect(html).toMatch(/th, td \{[^}]*min-width:\s*0px/s);+ expect(html).toMatch(+ /#xdt-content table \{[^}]*table-layout:\s*fixed[^}]*width:\s*100%/s,+ );+ expect(html).not.toContain("width: max-content");+ },+ );- it('继续脱敏跨行内格式和段落拆开的凭证', () => {+ it("继续脱敏跨行内格式和段落拆开的凭证", () => {const html = buildConversationShareHtml({- allShareableIds: ['secret'], colors, contentWidth: 390,- selectedMessages: [{ clientId: 'secret', kind: 'assistant', body: 'password: `private-code-secret`\n\nAuthorization: Basic **private-strong-secret**\n\npassword:\n\nprivate-paragraph-secret' }],+ allShareableIds: ["secret"],+ colors,+ contentWidth: 390,+ selectedMessages: [+ {+ clientId: "secret",+ kind: "assistant",+ body: "password: `private-code-secret`\n\nAuthorization: Basic **private-strong-secret**\n\npassword:\n\nprivate-paragraph-secret",+ },+ ],});- expect(html).not.toContain('private-');- expect(html).toContain('[REDACTED]');+ expect(html).not.toContain("private-");+ expect(html).toContain("[REDACTED]");});- it.each(['token', 'access_token', 'api_key'])(- '带 %s 的已准备图片使用 SVG 备用成图,保留图片和脱敏文字',+ it.each(["token", "access_token", "api_key"])(+ "带 %s 的已准备图片使用 SVG 备用成图,保留图片和脱敏文字",(parameter) => {const url = `https://example.com/pic.png?${parameter}=private-image-secret`;- const uri = 'data:image/png;base64,aGVsbG8=';+ const uri = "data:image/png;base64,aGVsbG8=";const picture = ``;const options = {- allShareableIds: ['plain', 'parts'], colors, contentWidth: 390,+ allShareableIds: ["plain", "parts"],+ colors,+ contentWidth: 390,selectedMessages: [- { clientId: 'plain', kind: 'assistant' as const, body: picture, images: new Map([[url, { uri, width: 40, height: 20 }]]) },{- clientId: 'parts', kind: 'user' as const, body: '',- bodyParts: [{ kind: 'text' as const, text: `| image |\n| --- |\n| ${picture} |` }],+ clientId: "plain",+ kind: "assistant" as const,+ body: picture,+ images: new Map([[url, { uri, width: 40, height: 20 }]]),+ },+ {+ clientId: "parts",+ kind: "user" as const,+ body: "",+ bodyParts: [+ {+ kind: "text" as const,+ text: `| image |\n| --- |\n| ${picture} |`,+ },+ ],secondaryBody: `${picture}\n\npassword=private-text-secret\n\n[link](https://example.com/?token=private-link-secret)\n\n\`\`\`text\npassword=private-code-secret\n\`\`\``,images: new Map([[url, { uri, width: 40, height: 20 }]]),},],};- expect(() => buildConversationShareHtml(options)).toThrow('conversation-share-image-requires-svg');- const svg = buildConversationShareSvgLayout({ ...options, width: 390, messages: options.selectedMessages });+ expect(() => buildConversationShareHtml(options)).toThrow(+ "conversation-share-image-requires-svg",+ );+ const svg = buildConversationShareSvgLayout({+ ...options,+ width: 390,+ messages: options.selectedMessages,+ });expect(svg.images).toHaveLength(3);expect(svg.images.every((image) => image.uri === uri)).toBe(true);- expect(JSON.stringify(svg)).not.toContain('private-');+ expect(JSON.stringify(svg)).not.toContain("private-");expect(JSON.stringify(svg)).not.toContain(url);- expect(JSON.stringify(svg)).toContain('[REDACTED]');+ expect(JSON.stringify(svg)).toContain("[REDACTED]");},);- it.each(['body', 'bodyParts', 'secondaryBody'] as const)(- '%s 中图片语法受到脱敏影响时由 SVG 保留图片或替代文字',+ it.each(["body", "bodyParts", "secondaryBody"] as const)(+ "%s 中图片语法受到脱敏影响时由 SVG 保留图片或替代文字",(field) => {- const url = 'https://example.com/p.png';+ const url = "https://example.com/p.png";const body = `password: private`;for (const prepared of [false, true]) {const message = {- clientId: 'm', kind: 'assistant' as const, body: '',- ...(field === 'bodyParts' ? { bodyParts: [{ kind: 'text' as const, text: body }] } : { [field]: body }),- images: new Map(prepared ? [[url, { uri: 'data:image/png;base64,aGVsbG8=', width: 40, height: 20 }]] : []),+ clientId: "m",+ kind: "assistant" as const,+ body: "",+ ...(field === "bodyParts"+ ? { bodyParts: [{ kind: "text" as const, text: body }] }+ : { [field]: body }),+ images: new Map(+ prepared+ ? [+ [+ url,+ {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 40,+ height: 20,+ },+ ],+ ]+ : [],+ ),+ };+ const options = {+ allShareableIds: ["m"],+ colors,+ contentWidth: 390,+ selectedMessages: [message],};- const options = { allShareableIds: ['m'], colors, contentWidth: 390, selectedMessages: [message] };- expect(() => buildConversationShareHtml(options)).toThrow('conversation-share-image-requires-svg');- const svg = buildConversationShareSvgLayout({ ...options, width: 390, messages: [message] });+ expect(() => buildConversationShareHtml(options)).toThrow(+ "conversation-share-image-requires-svg",+ );+ const svg = buildConversationShareSvgLayout({+ ...options,+ width: 390,+ messages: [message],+ });expect(svg.images).toHaveLength(prepared ? 1 : 0);- expect(JSON.stringify(svg)).not.toContain('private');+ expect(JSON.stringify(svg)).not.toContain("private");expect(JSON.stringify(svg)).not.toContain(url);}},);- it('只按选中内容嵌入对应的富内容运行时', () => {+ it("只按选中内容嵌入对应的富内容运行时", () => {const plainHtml = buildConversationShareHtml({- allShareableIds: ['plain'],+ allShareableIds: ["plain"],colors,contentWidth: 390,- selectedMessages: [{ body: 'plain text', clientId: 'plain', kind: 'assistant' }],+ selectedMessages: [+ { body: "plain text", clientId: "plain", kind: "assistant" },+ ],});const mathHtml = buildConversationShareHtml({- allShareableIds: ['math'],+ allShareableIds: ["math"],colors,contentWidth: 390,- selectedMessages: [{- body: ['$$', 'x^2 + y^2', '$$'].join('\n'),- clientId: 'math',- kind: 'assistant',- }],+ selectedMessages: [+ {+ body: ["$$", "x^2 + y^2", "$$"].join("\n"),+ clientId: "math",+ kind: "assistant",+ },+ ],});const mermaidHtml = buildConversationShareHtml({- allShareableIds: ['diagram'],+ allShareableIds: ["diagram"],colors,contentWidth: 390,- selectedMessages: [{- body: ['```mermaid', 'graph TD', 'A --> B', '```'].join('\n'),- clientId: 'diagram',- kind: 'assistant',- }],+ selectedMessages: [+ {+ body: ["```mermaid", "graph TD", "A --> B", "```"].join("\n"),+ clientId: "diagram",+ kind: "assistant",+ },+ ],});- expect(plainHtml).not.toContain('window.katex.render');- expect(plainHtml).not.toContain('window.mermaid.render');- expect(mathHtml).toContain('window.katex.render');- expect(mathHtml).not.toContain('window.mermaid.render');- expect(mermaidHtml).not.toContain('window.katex.render');- expect(mermaidHtml).toContain('window.mermaid.render');+ expect(plainHtml).not.toContain("window.katex.render");+ expect(plainHtml).not.toContain("window.mermaid.render");+ expect(mathHtml).toContain("window.katex.render");+ expect(mathHtml).not.toContain("window.mermaid.render");+ expect(mermaidHtml).not.toContain("window.katex.render");+ expect(mermaidHtml).toContain("window.mermaid.render");});- it('把自动化来源放在对应用户消息上方', () => {+ it("把自动化来源放在对应用户消息上方", () => {const html = buildConversationShareHtml({- allShareableIds: ['automation'],+ allShareableIds: ["automation"],colors,contentWidth: 390,- selectedMessages: [{- automationOriginLabel: '由自动化「每日摘要」发送',- body: '自动化消息',- clientId: 'automation',- kind: 'user',- }],+ selectedMessages: [+ {+ automationOriginLabel: "由自动化「每日摘要」发送",+ body: "自动化消息",+ clientId: "automation",+ kind: "user",+ },+ ],});- expect(html).toContain('share-automation-origin');- expect(html).toContain('由自动化「每日摘要」发送');+ expect(html).toContain("share-automation-origin");+ expect(html).toContain("由自动化「每日摘要」发送");});- it('保留公式与 Mermaid 语义,并注入对应运行时升级脚本', () => {+ it("保留公式与 Mermaid 语义,并注入对应运行时升级脚本", () => {const html = buildRichConversationHtml();expect(html).toContain('data-latex="x^2 + y^2"');expect(html).toContain('data-mermaid-source="graph TD\nA --> B"');- expect(html).toContain('window.katex.render');- expect(html).toContain('window.mermaid.render');+ expect(html).toContain("window.katex.render");+ expect(html).toContain("window.mermaid.render");expect(html).toContain("theme: 'dark'");expect(html).toContain(- 'window.__cindyConversationShareRichContentReady = true',+ "window.__cindyConversationShareRichContentReady = true",);});- it('只使用离线资源,并在导出前等待富内容和图片解码', () => {+ it("只使用离线资源,并在导出前等待富内容和图片解码", () => {const html = buildRichConversationHtml();expect(html).toContain("default-src 'none';");- expect(html).toContain('img-src data:;');- expect(html).not.toContain('img-src data: https:');+ expect(html).toContain("img-src data:;");+ expect(html).not.toContain("img-src data: https:");expect(html).toContain("script-src 'unsafe-inline';");expect(html).toContain(- 'waitForRichContent().then(waitForImages).then(waitForFonts)',+ "waitForRichContent().then(waitForImages).then(waitForFonts)",);- expect(html).toContain('image.decode().catch(function () {})');- expect(html).toContain('document.fonts.ready');+ expect(html).toContain("image.decode().catch(function () {})");+ expect(html).toContain("document.fonts.ready");expect(html).toContain("document.querySelectorAll('style')");expect(html).toContain("throw new Error('conversation-share-content-too-large')",);});- it('外链图片无法离线带入时保留可见占位', () => {+ it("外链图片无法离线带入时保留可见占位", () => {const html = buildConversationShareHtml({- allShareableIds: ['image'],+ allShareableIds: ["image"],colors,contentWidth: 390,- selectedMessages: [{- body: '',- clientId: 'image',- kind: 'assistant',- }],+ selectedMessages: [+ {+ body: "",+ clientId: "image",+ kind: "assistant",+ },+ ],});- expect(html).toContain(`<span class="xdt-image-chip">${i18n.t('message.renderer.imageFallbackTitle')}</span>`);- expect(html).not.toContain('https://example.com/image.png');+ expect(html).toContain(+ `<span class="xdt-image-chip">${i18n.t("message.renderer.imageFallbackTitle")}</span>`,+ );+ expect(html).not.toContain("https://example.com/image.png");});- it('限制原生与降级 renderer 的完整源尺寸,并安全保留已分享 PNG', () => {+ it("限制原生与降级 renderer 的完整源尺寸,并安全保留已分享 PNG", () => {const nativeSource = readFileSync(resolve(process.cwd(),- 'modules/xdt-screenshot-monitor/ios/XdtScreenshotMonitorModule.swift',+ "modules/xdt-screenshot-monitor/ios/XdtScreenshotMonitorModule.swift",),- 'utf8',+ "utf8",);const webViewSource = readFileSync(- resolve(process.cwd(), 'src/session/ConversationShareWebView.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ConversationShareWebView.tsx"),+ "utf8",);const sessionSource = readFileSync(- resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),- 'utf8',- ).replace(/\r\n/g, '\n');+ resolve(process.cwd(), "app/sessions/[sessionId].tsx"),+ "utf8",+ ).replace(/\r\n/g, "\n");- expect(nativeSource).toContain('conversationShareMaxSourcePixels');- expect(nativeSource).toContain('UIWindow(windowScene: windowScene)');- expect(nativeSource).toContain('hostingWindow.rootViewController = viewController');- expect(nativeSource).toContain('hostingWindow?.isHidden = true');- expect(nativeSource).toContain('no active window scene');- expect(nativeSource).toContain('UIWindow.Level.normal.rawValue + 1');- expect(nativeSource).toContain('hostingWindow.alpha = 0.01');- expect(nativeSource).toContain('waitForWebContentPaint(webView)');- expect(nativeSource).toContain('requestAnimationFrame(resolve)');- expect(nativeSource).toContain('merged.hasVisibleVariation');- expect(nativeSource).toContain('Conversation share PNG is blank.');- expect(nativeSource).toContain('format.scale = 1');+ expect(nativeSource).toContain("conversationShareMaxSourcePixels");+ expect(nativeSource).toContain("UIWindow(windowScene: windowScene)");+ expect(nativeSource).toContain(+ "hostingWindow.rootViewController = viewController",+ );+ expect(nativeSource).toContain("hostingWindow?.isHidden = true");+ expect(nativeSource).toContain("no active window scene");+ expect(nativeSource).toContain("UIWindow.Level.normal.rawValue + 1");+ expect(nativeSource).toContain("hostingWindow.alpha = 0.01");+ expect(nativeSource).toContain("waitForWebContentPaint(webView)");+ expect(nativeSource).toContain("requestAnimationFrame(resolve)");+ expect(nativeSource).toContain("merged.hasVisibleVariation");+ expect(nativeSource).toContain("Conversation share PNG is blank.");+ expect(nativeSource).toContain("format.scale = 1");+ expect(nativeSource).toContain(+ "captureWidth * captureHeight <= conversationShareMaxSourcePixels",+ );expect(nativeSource).toContain(- 'captureWidth * captureHeight <= conversationShareMaxSourcePixels',+ "return numericValue.isFinite ? numericValue : nil",);- expect(nativeSource).toContain('return numericValue.isFinite ? numericValue : nil');expect(webViewSource).toContain(- 'await deleteConversationSharePngTemp(file.uri);',+ "await deleteConversationSharePngTemp(file.uri);",);- expect(webViewSource).toContain('SHARE_PNG_RETAIN_COUNT = 3');- expect(webViewSource).toContain('SHARE_PNG_CLEANUP_BATCH = 8');+ expect(webViewSource).toContain("SHARE_PNG_RETAIN_COUNT = 3");+ expect(webViewSource).toContain("SHARE_PNG_CLEANUP_BATCH = 8");expect(webViewSource).toContain(- 'files.slice(SHARE_PNG_RETAIN_COUNT, SHARE_PNG_RETAIN_COUNT + SHARE_PNG_CLEANUP_BATCH)',+ "files.slice(SHARE_PNG_RETAIN_COUNT, SHARE_PNG_RETAIN_COUNT + SHARE_PNG_CLEANUP_BATCH)",);- expect(sessionSource).toContain('deleteConversationSharePngTemp');- expect(sessionSource).toContain('cleanupConversationSharePngTemps');- expect(sessionSource).toContain('cache 目录交给下一次有界清理');- expect(sessionSource).toContain('if (!shareCompleted && localUri)');- expect(sessionSource).toContain('<ConversationShareSvg');+ expect(sessionSource).toContain("deleteConversationSharePngTemp");+ expect(sessionSource).toContain("cleanupConversationSharePngTemps");+ expect(sessionSource).toContain("cache 目录交给下一次有界清理");+ expect(sessionSource).toContain("if (!shareCompleted && localUri)");+ expect(sessionSource).toContain("<ConversationShareSvg");expect(sessionSource).toContain("nativeConversationShareAvailable = Platform.OS === 'ios'",);expect(sessionSource).toContain(- 'if (!nativeConversationShareAvailable || !shareSelectionActive) return undefined;',+ "if (!nativeConversationShareAvailable || !shareSelectionActive) return undefined;",);expect(sessionSource).toContain(- 'const messages = await shareImages.prepare();',+ "const messages = await shareImages.prepare();",);expect(sessionSource).toContain(- 'nativeConversationShareAvailable\n && shareCharacterSrc',- );- expect(sessionSource).toContain('renderConversationShareHtmlToPng({');- expect(sessionSource).toContain('nativeShareAssetsReady');- expect(sessionSource).toContain('native webview export succeeded');- expect(sessionSource).toContain('falling back to svg');- expect(sessionSource).not.toContain('OTA webview export failed; falling back to svg');- expect(sessionSource).toContain('return svg.exportPng();');+ "nativeConversationShareAvailable\n && shareCharacterSrc",+ );+ expect(sessionSource).toContain("renderConversationShareHtmlToPng({");+ expect(sessionSource).toContain("nativeShareAssetsReady");+ expect(sessionSource).toContain("native webview export succeeded");+ expect(sessionSource).toContain("falling back to svg");+ expect(sessionSource).not.toContain(+ "OTA webview export failed; falling back to svg",+ );+ expect(sessionSource).toContain("return svg.exportPng();");const shareAsyncIndex = sessionSource.indexOf("await sharing.shareAsync(localUri, { mimeType: 'image/png' });",);- const shareCompletedIndex = sessionSource.indexOf('shareCompleted = true;', shareAsyncIndex);+ const shareCompletedIndex = sessionSource.indexOf(+ "shareCompleted = true;",+ shareAsyncIndex,+ );const postShareActiveCheckIndex = sessionSource.indexOf(- 'if (!isShareOperationActive()) return;',+ "if (!isShareOperationActive()) return;",shareAsyncIndex,);expect(shareAsyncIndex).toBeGreaterThanOrEqual(0);@@ -305,187 +392,209 @@ describe('buildConversationShareHtml 富内容导出', () => {expect(shareCompletedIndex).toBeLessThan(postShareActiveCheckIndex);});- it('使用 Mobile 获批的克制页脚尺寸', () => {+ it("使用 Mobile 获批的克制页脚尺寸", () => {const designSource = readFileSync(- resolve(process.cwd(), '../../docs/design-rules/DESIGN.md'),- 'utf8',+ resolve(process.cwd(), "../../docs/design-rules/DESIGN.md"),+ "utf8",);const svgSource = readFileSync(- resolve(process.cwd(), 'src/session/ConversationShareSvg.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ConversationShareSvg.tsx"),+ "utf8",);const html = buildRichConversationHtml();- expect(designSource).toContain('Mobile approved 2026-08-08');- expect(designSource).toContain('src/session/ConversationShareSvg.tsx');- expect(designSource).toContain('22×22px (6px radius)');- expect(designSource).toContain('18px-high wordmark with a 6px gap');- expect(svgSource).toContain('const SHARE_CHARACTER_SIZE = 22;');- expect(svgSource).toContain('const SHARE_LOGO_HEIGHT = 18;');- expect(svgSource).toContain('const SHARE_LOCKUP_GAP = 6;');- expect(svgSource).toContain('rx={6}');- expect(svgSource).toContain('assetGate.waitUntilSettled()');+ expect(designSource).toContain("Mobile approved 2026-08-08");+ expect(designSource).toContain("src/session/ConversationShareSvg.tsx");+ expect(designSource).toContain("22×22px (6px radius)");+ expect(designSource).toContain("18px-high wordmark with a 6px gap");+ expect(svgSource).toContain("const SHARE_CHARACTER_SIZE = 22;");+ expect(svgSource).toContain("const SHARE_LOGO_HEIGHT = 18;");+ expect(svgSource).toContain("const SHARE_LOCKUP_GAP = 6;");+ expect(svgSource).toContain("rx={6}");+ expect(svgSource).toContain("assetGate.waitUntilSettled()");expect(svgSource).toContain('assetGate.markReady("character")');expect(svgSource).toContain('assetGate.markReady("logo")');- expect(html).toContain('width: 22px;');- expect(html).toContain('height: 18px;');- expect(html).toContain('gap: 6px;');+ expect(html).toContain("width: 22px;");+ expect(html).toContain("height: 18px;");+ expect(html).toContain("gap: 6px;");});- it('分享导出保持消息间距,并为隐藏 WebView 复用安全边界', () => {+ it("分享导出保持消息间距,并为隐藏 WebView 复用安全边界", () => {const html = buildConversationShareHtml({- allShareableIds: ['first', 'middle', 'third'],+ allShareableIds: ["first", "middle", "third"],colors,contentWidth: 390,selectedMessages: [- { body: 'first', clientId: 'first', kind: 'user' },- { body: 'third', clientId: 'third', kind: 'assistant' },+ { body: "first", clientId: "first", kind: "user" },+ { body: "third", clientId: "third", kind: "assistant" },],});const webViewSource = readFileSync(- resolve(process.cwd(), 'src/session/ConversationShareWebView.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ConversationShareWebView.tsx"),+ "utf8",);const shareBarSource = readFileSync(- resolve(process.cwd(), 'src/session/ShareSelectionBar.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ShareSelectionBar.tsx"),+ "utf8",);const selectAllSource = readFileSync(- resolve(process.cwd(), 'src/session/ShareSelectAllButton.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ShareSelectAllButton.tsx"),+ "utf8",);const messageCheckboxSource = readFileSync(- resolve(process.cwd(), 'src/session/ShareMessageCheckbox.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/ShareMessageCheckbox.tsx"),+ "utf8",);const messageRendererSource = readFileSync(- resolve(process.cwd(), 'src/session/MessageRenderer.tsx'),- 'utf8',+ resolve(process.cwd(), "src/session/MessageRenderer.tsx"),+ "utf8",);const sessionSource = readFileSync(- resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),- 'utf8',+ resolve(process.cwd(), "app/sessions/[sessionId].tsx"),+ "utf8",);expect(html).toContain('<div class="share-gap" aria-hidden="true">⋯</div>');expect(html).toMatch(/#xdt-content\.share-stage\s*\{[\s\S]*?display: flex;[\s\S]*?flex-direction: column;[\s\S]*?gap: 16px;/,);- expect(shareBarSource).toContain('<HomeHeaderGlassButton');- const chromeStyle = readFileSync(resolve(process.cwd(), 'src/platform/chrome/nativeGlassButtonStyle.ios.ts'), 'utf8');- expect(chromeStyle).toContain('size = navigationChrome.target');- expect(chromeStyle).toContain(': { width: size, height: size })');- expect(shareBarSource).toContain('minHeight: 44,');- expect(shareBarSource).toContain('minWidth: 112,');- expect(shareBarSource).toContain('fontSize: typeScale.body,');+ expect(shareBarSource).toContain("<HomeHeaderGlassButton");+ const chromeStyle = readFileSync(+ resolve(+ process.cwd(),+ "src/platform/chrome/nativeGlassButtonStyle.ios.ts",+ ),+ "utf8",+ );+ expect(chromeStyle).toContain("size = navigationChrome.target");+ expect(chromeStyle).toContain(": { width: size, height: size })");+ expect(shareBarSource).toContain("minHeight: 44,");+ expect(shareBarSource).toContain("minWidth: 112,");+ expect(shareBarSource).toContain("fontSize: typeScale.body,");+ expect(selectAllSource).toContain("shareableIds.filter((clientId) =>");expect(selectAllSource).toContain(- 'shareableIds.filter((clientId) =>',+ "selectionBeforeSelectAllRef.current?.includes(clientId)",);expect(selectAllSource).toContain(- 'selectionBeforeSelectAllRef.current?.includes(clientId)',- );- expect(selectAllSource).toContain('<ShareCheckboxMark checked={allSelected} />');- expect(selectAllSource).not.toContain('backgroundColor: colors.surfaceChip');- expect(messageCheckboxSource).toContain('onStartShouldSetResponder={() => !disabled}');- expect(messageCheckboxSource).toContain('onResponderTerminationRequest={() => true}');- expect(messageCheckboxSource).toContain('shouldCommitShareSelectionTap({');- expect(messageCheckboxSource).toContain('<ShareSelectionRowInteractionContext.Provider');- expect(messageCheckboxSource).toContain('if (!gesture.consumed) toggle();');- expect(messageCheckboxSource).not.toContain('fill ? styles.rowButton : styles.button');- expect(messageRendererSource).toContain('<View style={styles.shareSelectionContent}>');+ "<ShareCheckboxMark checked={allSelected} />",+ );+ expect(selectAllSource).not.toContain(+ "backgroundColor: colors.surfaceChip",+ );+ expect(messageCheckboxSource).toContain(+ "onStartShouldSetResponder={() => !disabled}",+ );+ expect(messageCheckboxSource).toContain(+ "onResponderTerminationRequest={() => true}",+ );+ expect(messageCheckboxSource).toContain("shouldCommitShareSelectionTap({");+ expect(messageCheckboxSource).toContain(+ "<ShareSelectionRowInteractionContext.Provider",+ );+ expect(messageCheckboxSource).toContain("if (!gesture.consumed) toggle();");+ expect(messageCheckboxSource).not.toContain(+ "fill ? styles.rowButton : styles.button",+ );+ expect(messageRendererSource).toContain(+ "<View style={styles.shareSelectionContent}>",+ );expect(messageRendererSource).not.toContain('pointerEvents="none" style={styles.shareSelectionContent}',);- expect(messageRendererSource).toContain('useCancelShareSelectionRowTap()');- expect(messageRendererSource).toContain('fill');+ expect(messageRendererSource).toContain("useCancelShareSelectionRowTap()");+ expect(messageRendererSource).toContain("fill");expect(messageRendererSource).toContain('testID="message.shareStickyCheck"',);expect(messageRendererSource).toContain(- 'const shareableViews = Array.from(shareableMessageViewsRef.current.entries())',+ "const shareableViews = Array.from(shareableMessageViewsRef.current.entries())",);expect(messageRendererSource).toContain(- 'candidates.sort((a, b) => (a.frame?.y ?? Number.POSITIVE_INFINITY)',+ "candidates.sort((a, b) => (a.frame?.y ?? Number.POSITIVE_INFINITY)",);expect(messageRendererSource).toContain(- 'const pinned = candidates.find(({ frame }) => frame',+ "const pinned = candidates.find(({ frame }) => frame",);expect(messageRendererSource).toContain(- 'frame.y + frame.height > dockY + SHARE_STICKY_CHECK_HEIGHT',+ "frame.y + frame.height > dockY + SHARE_STICKY_CHECK_HEIGHT",);expect(messageRendererSource).toContain('pointerEvents="box-none"');- expect(messageRendererSource).toContain('marginLeft: wideContentInset + spacing.lg');- expect(messageRendererSource).not.toContain('styles.stickyShareSpacer');+ expect(messageRendererSource).toContain(+ "marginLeft: wideContentInset + spacing.lg",+ );+ expect(messageRendererSource).not.toContain("styles.stickyShareSpacer");expect(sessionSource).toContain(- 'shareSelectionLeadingInset={nativeShellLayout.wideViewport',+ "shareSelectionLeadingInset={nativeShellLayout.wideViewport",);expect(sessionSource).toContain(- '{ paddingLeft: shareSelectionLeadingInset + spacing.sm }',+ "{ paddingLeft: shareSelectionLeadingInset + spacing.sm }",);expect(webViewSource).toContain(- 'onShouldStartLoadWithRequest={interceptNavigation}',+ "onShouldStartLoadWithRequest={interceptNavigation}",);expect(webViewSource).toContain(- 'interceptHtmlNavigation(request, documentSettledRef.current)',+ "interceptHtmlNavigation(request, documentSettledRef.current)",);- expect(webViewSource).toContain('allowFileAccess={false}');+ expect(webViewSource).toContain("allowFileAccess={false}");expect(webViewSource).toContain('mediaCapturePermissionGrantType="deny"');});- it('导出结构化正文和附件时保留可见投影,不泄露隐藏引用或外链', () => {+ it("导出结构化正文和附件时保留可见投影,不泄露隐藏引用或外链", () => {const html = buildConversationShareHtml({- allShareableIds: ['message'],+ allShareableIds: ["message"],colors,contentWidth: 390,selectedMessages: [{attachments: [- { kind: 'image', name: 'preview.png' },- { kind: 'image', name: 'remote.png' },- { kind: 'file', name: 'notes.md' },+ { kind: "image", name: "preview.png" },+ { kind: "image", name: "remote.png" },+ { kind: "file", name: "notes.md" },],- body: 'visible fallback',+ body: "visible fallback",bodyParts: [- { kind: 'quote', label: 'quoted context' },- { kind: 'pasted', label: 'Pasted text · 120 chars' },- { kind: 'slash', label: '/review' },- { kind: 'text', text: 'reply' },+ { kind: "quote", label: "quoted context" },+ { kind: "pasted", label: "Pasted text · 120 chars" },+ { kind: "slash", label: "/review" },+ { kind: "text", text: "reply" },],- clientId: 'message',- kind: 'user',+ clientId: "message",+ kind: "user",},],});- expect(html).toContain('quoted context');- expect(html).toContain('Pasted text · 120 chars');- expect(html).toContain('/review');- expect(html).not.toContain('share-inline-chip-icon" aria-hidden="true">/</span>');- expect(html).toContain('preview.png');+ expect(html).toContain("quoted context");+ expect(html).toContain("Pasted text · 120 chars");+ expect(html).toContain("/review");+ expect(html).not.toContain(+ 'share-inline-chip-icon" aria-hidden="true">/</span>',+ );+ expect(html).toContain("preview.png");expect(html).not.toContain('<img class="share-attachment-image"');- expect(html).toContain('remote.png');- expect(html).toContain('notes.md');- expect(html).not.toContain('visible fallback');- expect(html).not.toContain('https://example.com/private.png');+ expect(html).toContain("remote.png");+ expect(html).toContain("notes.md");+ expect(html).not.toContain("visible fallback");+ expect(html).not.toContain("https://example.com/private.png");});- it('附件-only 消息不生成空白文字气泡', () => {+ it("附件-only 消息不生成空白文字气泡", () => {const html = buildConversationShareHtml({- allShareableIds: ['attachment'],+ allShareableIds: ["attachment"],colors,contentWidth: 390,selectedMessages: [{- attachments: [{ kind: 'file', name: 'report.pdf' }],- body: '',- clientId: 'attachment',- kind: 'user',+ attachments: [{ kind: "file", name: "report.pdf" }],+ body: "",+ clientId: "attachment",+ kind: "user",},],});- expect(html).toContain('share-attachment-chip-file');+ expect(html).toContain("share-attachment-chip-file");expect(html).not.toContain('share-bubble-user">');});});diff --git a/apps/mobile/src/__tests__/nativeGlassControls.test.tsx b/apps/mobile/src/__tests__/nativeGlassControls.test.tsxindex b218787937..ec0369fc8b 100644--- a/apps/mobile/src/__tests__/nativeGlassControls.test.tsx+++ b/apps/mobile/src/__tests__/nativeGlassControls.test.tsx@@ -1,92 +1,250 @@// @vitest-environment jsdom-import { act, type ReactNode } from 'react';-import { createRoot } from 'react-dom/client';-import { afterEach, expect, it, vi } from 'vitest';-import { NativeChromeButton } from '../platform/chrome/NativeChromeButton.ios';-import { LoginNativeButton } from '../components/LoginNativeButton.ios';-import { useNativeGlassButtonStyle } from '../platform/chrome/nativeGlassButtonStyle.ios';+import { act, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, expect, it, vi } from "vitest";+import { NativeChromeButton } from "../platform/chrome/NativeChromeButton.ios";+import { LoginNativeButton } from "../components/LoginNativeButton.ios";+import { ShareImageNativeButton } from "../session/ShareImageNativeButton.ios";+import { useNativeGlassButtonStyle } from "../platform/chrome/nativeGlassButtonStyle.ios";-const state = vi.hoisted(() => ({ glass: true, mode: 'light' }));-vi.mock('@/theme', () => ({- navigationChrome: { target: 44, clear: { light: { foreground: 'black', scrim: 'light-scrim' }, dark: { foreground: 'white', scrim: 'dark-scrim' } } },- iconSize: { action: 20 }, iconStroke: { regular: 2 }, radius: { pill: 9999 },- useTheme: () => ({ mode: state.mode, colors: { textPrimary: 'primary', textSecondary: 'secondary', cta: 'cta', destructive: 'danger', surfaceElevated: 'surface' } }),+const state = vi.hoisted(() => ({ glass: true, mode: "light" }));+vi.mock("@/theme", () => ({+ navigationChrome: {+ target: 44,+ clear: {+ light: { foreground: "black", scrim: "light-scrim" },+ dark: { foreground: "white", scrim: "dark-scrim" },+ },+ },+ iconSize: { action: 20 },+ iconStroke: { regular: 2 },+ radius: { pill: 9999 },+ typeScale: { body: 16 },+ useTheme: () => ({+ mode: state.mode,+ colors: {+ textPrimary: "primary",+ textSecondary: "secondary",+ cta: "cta",+ ctaText: state.mode === "dark" ? "black" : "white",+ destructive: "danger",+ surfaceElevated: "surface",+ },+ }),}));-vi.mock('@/session/useLiquidGlassAvailable', () => ({ useLiquidGlassAvailable: () => state.glass }));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));-vi.mock('react-native', () => ({ View: ({ children }: any) => <div>{children}</div>, Image: () => null }));-vi.mock('lucide-react-native', () => {+vi.mock("@/session/useLiquidGlassAvailable", () => ({+ useLiquidGlassAvailable: () => state.glass,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("react-native", () => ({+ View: ({ children }: any) => <div>{children}</div>,+ Image: () => null,+}));+vi.mock("lucide-react-native", () => {const Icon = () => null;- return { LogOut: Icon, Monitor: Icon, Search: Icon, Settings: Icon, UsersRound: Icon };+ return {+ LogOut: Icon,+ Monitor: Icon,+ Search: Icon,+ Settings: Icon,+ UsersRound: Icon,+ };});-vi.mock('@expo/ui', () => ({ Host: ({ children }: any) => <div>{children}</div> }));-vi.mock('@expo/ui/swift-ui', () => {+vi.mock("@expo/ui", () => ({+ Host: ({ children }: any) => <div>{children}</div>,+}));+vi.mock("@expo/ui/swift-ui", () => {const Container = ({ children }: any) => <div>{children}</div>;return {- HStack: Container, VStack: Container, RNHostView: Container, Text: Container, Image: () => null,+ HStack: Container,+ VStack: Container,+ RNHostView: Container,+ Text: Container,+ Image: () => null,+ Label: ({ title, modifiers }: any) => (+ <span data-label-style={JSON.stringify(modifiers)}>{title}</span>+ ),ProgressView: () => <span role="progressbar" />,- Button: ({ children, label, onPress, testID, modifiers = [] }: any) => <button data-testid={testID}- disabled={modifiers.some((m: any) => m.name === 'disabled' && m.value)} onClick={onPress}>{children ?? label}</button>,+ Button: ({ children, label, onPress, testID, modifiers = [] }: any) => (+ <button+ data-testid={testID}+ disabled={modifiers.some((m: any) => m.name === "disabled" && m.value)}+ onClick={onPress}+ >+ {children ?? label}+ </button>+ ),};});-vi.mock('@expo/ui/swift-ui/modifiers', () => {- const names = ['background', 'buttonBorderShape', 'buttonStyle', 'contentShape', 'controlSize', 'foregroundStyle', 'frame', 'glassEffect', 'accessibilityElement', 'accessibilityLabel', 'accessibilityAddTraits', 'disabled', 'font', 'labelStyle', 'lineLimit'];- return { ...Object.fromEntries(names.map(name => [name, (value: any) => ({ name, value })])), shapes: { circle: () => 'circle', capsule: () => 'capsule' } };+vi.mock("@expo/ui/swift-ui/modifiers", () => {+ const names = [+ "background",+ "buttonBorderShape",+ "buttonStyle",+ "contentShape",+ "controlSize",+ "foregroundStyle",+ "frame",+ "glassEffect",+ "accessibilityElement",+ "accessibilityLabel",+ "accessibilityAddTraits",+ "disabled",+ "font",+ "labelStyle",+ "lineLimit",+ ];+ return {+ ...Object.fromEntries(+ names.map((name) => [name, (value: any) => ({ name, value })]),+ ),+ shapes: { circle: () => "circle", capsule: () => "capsule" },+ };});const roots: ReturnType<typeof createRoot>[] = [];-afterEach(() => { act(() => roots.splice(0).forEach(root => root.unmount())); state.glass = true; state.mode = 'light'; });+afterEach(() => {+ act(() => roots.splice(0).forEach((root) => root.unmount()));+ state.glass = true;+ state.mode = "light";+});function mount(children: ReactNode) {- const host = document.createElement('div');- const root = createRoot(host); roots.push(root);+ const host = document.createElement("div");+ const root = createRoot(host);+ roots.push(root);act(() => root.render(children));return host;}-it('prevents disabled glass actions', () => {+it("prevents disabled glass actions", () => {const click = vi.fn();- const host = mount(<NativeChromeButton label="disabled" testID="disabled" disabled onPress={click} />);- act(() => (host.querySelector('[data-testid="disabled"]') as HTMLButtonElement).click());+ const host = mount(+ <NativeChromeButton+ label="disabled"+ testID="disabled"+ disabled+ onPress={click}+ />,+ );+ act(() =>+ (+ host.querySelector('[data-testid="disabled"]') as HTMLButtonElement+ ).click(),+ );expect(click).not.toHaveBeenCalled();});-it.each(['light', 'dark'])('keeps clear glass foreground/backing paired in %s', mode => {- state.mode = mode;+it.each(["light", "dark"])(+ "pairs the share label with the CTA foreground and disables activation in %s",+ (mode) => {+ state.mode = mode;+ const click = vi.fn();+ const host = mount(+ <ShareImageNativeButton label="Share image" disabled onPress={click}>+ <button>fallback</button>+ </ShareImageNativeButton>,+ );+ expect(host.querySelectorAll("button")).toHaveLength(1);+ const label = host.querySelector("[data-label-style]")!;+ expect(label.textContent).toBe("Share image");+ // Inherit the native button's Dynamic Type font instead of fixing its size.+ expect(+ JSON.parse(label.getAttribute("data-label-style")!),+ ).not.toContainEqual(expect.objectContaining({ name: "font" }));+ expect(JSON.parse(label.getAttribute("data-label-style")!)).toContainEqual({+ name: "foregroundStyle",+ value: mode === "dark" ? "black" : "white",+ });+ act(() => host.querySelector("button")!.click());+ expect(click).not.toHaveBeenCalled();+ },+);+it.each(["light", "dark"])(+ "keeps clear glass foreground/backing paired in %s",+ (mode) => {+ state.mode = mode;+ let modifiers: any[] = [];+ function Probe() {+ modifiers = useNativeGlassButtonStyle({ shape: "circle", clear: true });+ return null;+ }+ mount(<Probe />);+ expect(modifiers).toContainEqual({+ name: "foregroundStyle",+ value: mode === "light" ? "black" : "white",+ });+ expect(modifiers).toContainEqual({+ name: "background",+ value: `${mode}-scrim`,+ });+ expect(modifiers).toContainEqual({+ name: "frame",+ value: { width: 44, height: 44 },+ });+ },+);+it("keeps unsupported-glass controls native with bordered prominent styling", () => {+ state.glass = false;let modifiers: any[] = [];- function Probe() { modifiers = useNativeGlassButtonStyle({ shape: 'circle', clear: true }); return null; }- mount(<Probe />);- expect(modifiers).toContainEqual({ name: 'foregroundStyle', value: mode === 'light' ? 'black' : 'white' });- expect(modifiers).toContainEqual({ name: 'background', value: `${mode}-scrim` });- expect(modifiers).toContainEqual({ name: 'frame', value: { width: 44, height: 44 } });-});-it('keeps unsupported-glass controls native with bordered prominent styling', () => {- state.glass = false; let modifiers: any[] = [];- function Probe() { modifiers = useNativeGlassButtonStyle({ prominent: true }); return null; }+ function Probe() {+ modifiers = useNativeGlassButtonStyle({ prominent: true });+ return null;+ }mount(<Probe />);- expect(modifiers).toContainEqual({ name: 'buttonStyle', value: 'borderedProminent' });- expect(modifiers.some(m => m.name === 'glassEffect')).toBe(false);+ expect(modifiers).toContainEqual({+ name: "buttonStyle",+ value: "borderedProminent",+ });+ expect(modifiers.some((m) => m.name === "glassEffect")).toBe(false);});-it.each(['light', 'dark'])('blocks repeated login submissions while busy, then re-enables in %s', mode => {- state.mode = mode;- const click = vi.fn();- const host = document.createElement('div');- const root = createRoot(host); roots.push(root);- const render = (busy: boolean) => root.render(<LoginNativeButton label="Verify" onPress={click}- busy={busy} width={540} height={80} fontSize={24} variant="primary" />);- act(() => render(true));- expect(host.querySelector('[role="progressbar"]')).not.toBeNull();- act(() => host.querySelector('button')!.click());- expect(click).not.toHaveBeenCalled();- act(() => render(false));- expect(host.querySelector('[role="progressbar"]')).toBeNull();- act(() => host.querySelector('button')!.click());- expect(click).toHaveBeenCalledTimes(1);-});+it.each(["light", "dark"])(+ "blocks repeated login submissions while busy, then re-enables in %s",+ (mode) => {+ state.mode = mode;+ const click = vi.fn();+ const host = document.createElement("div");+ const root = createRoot(host);+ roots.push(root);+ const render = (busy: boolean) =>+ root.render(+ <LoginNativeButton+ label="Verify"+ onPress={click}+ busy={busy}+ width={540}+ height={80}+ fontSize={24}+ variant="primary"+ />,+ );+ act(() => render(true));+ expect(host.querySelector('[role="progressbar"]')).not.toBeNull();+ act(() => host.querySelector("button")!.click());+ expect(click).not.toHaveBeenCalled();+ act(() => render(false));+ expect(host.querySelector('[role="progressbar"]')).toBeNull();+ act(() => host.querySelector("button")!.click());+ expect(click).toHaveBeenCalledTimes(1);+ },+);-it('keeps provider artwork inside a native button and prevents disabled activation', () => {+it("keeps provider artwork inside a native button and prevents disabled activation", () => {const click = vi.fn();- const host = mount(<LoginNativeButton label="Provider" disabled onPress={click}- width={80} height={80} fontSize={24} variant="circle"><span data-brand="original" /></LoginNativeButton>);- expect(host.querySelectorAll('button')).toHaveLength(1);+ const host = mount(+ <LoginNativeButton+ label="Provider"+ disabled+ onPress={click}+ width={80}+ height={80}+ fontSize={24}+ variant="circle"+ >+ <span data-brand="original" />+ </LoginNativeButton>,+ );+ expect(host.querySelectorAll("button")).toHaveLength(1);expect(host.querySelector('button [data-brand="original"]')).not.toBeNull();- act(() => host.querySelector('button')!.click());+ act(() => host.querySelector("button")!.click());expect(click).not.toHaveBeenCalled();});diff --git a/apps/mobile/src/session/ConversationShareSvg.tsx b/apps/mobile/src/session/ConversationShareSvg.tsxindex 28da65f214..f83d2982c3 100644--- a/apps/mobile/src/session/ConversationShareSvg.tsx+++ b/apps/mobile/src/session/ConversationShareSvg.tsx@@ -26,7 +26,7 @@ import {conversationShareSvgRenderSize,type ConversationShareSvgBubble,} from "@/session/conversationShareSvgLayout";-import { typeScale } from "@/theme";+import { monoFont, typeScale } from "@/theme";export interface ConversationShareSvgHandle {exportPng(): Promise<string>;@@ -387,11 +387,21 @@ function SvgBubbleView({ bubble }: { bubble: ConversationShareSvgBubble }) {y={bubble.y}/>) : null}+ {bubble.rectangles?.map((rect, index) => (+ <Rect+ key={`rect-${index}`}+ {...rect}+ strokeWidth={SHARE_BUBBLE_STROKE_WIDTH}+ />+ ))}{bubble.textBlocks.map((block, blockIndex) => (<SvgTextfill={block.color}- fontFamily="Arial"+ fontFamily={block.monospace ? monoFont : "Arial"}fontSize={block.fontSize}+ fontWeight={block.bold ? "bold" : "normal"}+ fontStyle={block.italic ? "italic" : "normal"}+ textDecoration={block.decoration}key={`text-${blockIndex}`}x={block.x}y={block.y}@@ -402,7 +412,9 @@ function SvgBubbleView({ bubble }: { bubble: ConversationShareSvgBubble }) {key={`line-${lineIndex}`}x={block.x}>- {line || " "}+ {/* Lines are already laid out: preserve code indentation and the+ spaces at styled-run boundaries in native SVG text. */}+ {line ? line.replace(/ /g, "\u00a0") : " "}</TSpan>))}</SvgText>diff --git a/apps/mobile/src/session/ShareImageNativeButton.ios.tsx b/apps/mobile/src/session/ShareImageNativeButton.ios.tsxindex b15d4ab341..022f6baab6 100644--- a/apps/mobile/src/session/ShareImageNativeButton.ios.tsx+++ b/apps/mobile/src/session/ShareImageNativeButton.ios.tsx@@ -1,7 +1,9 @@import { Host } from "@expo/ui";-import { Button } from "@expo/ui/swift-ui";+import { Button, Label } from "@expo/ui/swift-ui";import {disabled,+ controlSize,+ foregroundStyle,frame,} from "@expo/ui/swift-ui/modifiers";import { useTheme } from "@/theme";@@ -21,18 +23,23 @@ export function ShareImageNativeButton(props: ShareImageNativeButtonProps) {style={{ flexShrink: 0 }}><Button- label={props.label}- systemImage="square.and.arrow.up"testID="session.shareImage.share"onPress={() => {if (!props.disabled) props.onPress();}}modifiers={[...glassStyle,+ controlSize("large"),frame({ minWidth: 112, minHeight: 44 }),disabled(props.disabled),]}- />+ >+ <Label+ title={props.label}+ systemImage="square.and.arrow.up"+ modifiers={[foregroundStyle(colors.ctaText)]}+ />+ </Button></Host>);}diff --git a/apps/mobile/src/session/ShareSelectionBar.tsx b/apps/mobile/src/session/ShareSelectionBar.tsxindex e343d4c9ce..63bf971842 100644--- a/apps/mobile/src/session/ShareSelectionBar.tsx+++ b/apps/mobile/src/session/ShareSelectionBar.tsx@@ -1,6 +1,7 @@import { HomeHeaderGlassButton } from "./HomeHeaderGlassButton";+import { useState } from "react";import { Share as ShareIcon, X } from "lucide-react-native";-import { Pressable, StyleSheet, View } from "react-native";+import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native";import { useTranslation } from "react-i18next";import { Text } from "@/components/AppText";import { ShareImageNativeButton } from "@/session/ShareImageNativeButton";@@ -32,6 +33,9 @@ export function ShareSelectionBar({const { t } = useTranslation();const { colors } = useTheme();const styles = useThemedStyles(makeStyles);+ const { width, fontScale } = useWindowDimensions();+ const [barWidth, setBarWidth] = useState<number | null>(null);+ const stacked = (barWidth ?? width) / fontScale < 360;const cancelIcon = (<X@@ -89,20 +93,28 @@ export function ShareSelectionBar({);return (- <View style={styles.container} testID="session.shareImage.bar">- {cancelButton}- {countLabel}- <ShareImageNativeButton- label={- busy- ? t("session.shareImage.generating")- : t("session.shareImage.share")- }- disabled={busy === true || count === 0}- onPress={onShare}- >- {shareButton}- </ShareImageNativeButton>+ <View+ onLayout={({ nativeEvent }) => setBarWidth(nativeEvent.layout.width)}+ style={[styles.container, stacked && styles.stacked]}+ testID="session.shareImage.bar"+ >+ <View style={[styles.summary, stacked && styles.fullWidth]}>+ {cancelButton}+ {countLabel}+ </View>+ <View style={[styles.action, stacked && styles.stackedAction]}>+ <ShareImageNativeButton+ label={+ busy+ ? t("session.shareImage.generating")+ : t("session.shareImage.share")+ }+ disabled={busy === true || count === 0}+ onPress={onShare}+ >+ {shareButton}+ </ShareImageNativeButton>+ </View></View>);}@@ -121,6 +133,17 @@ const makeStyles = (colors: ThemeColors) =>paddingVertical: spacing.sm,},count: { flex: 1, minWidth: 0 },+ summary: {+ flex: 1,+ minWidth: 0,+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ },+ stacked: { flexDirection: "column", alignItems: "stretch" },+ fullWidth: { flex: 0 },+ action: { flexShrink: 0 },+ stackedAction: { alignSelf: "flex-end" },titleText: {color: colors.textPrimary,fontSize: typeScale.body,@@ -141,6 +164,7 @@ const makeStyles = (colors: ThemeColors) =>backgroundColor: colors.cta,borderRadius: radius.pill,flexDirection: "row",+ justifyContent: "center",gap: spacing.sm,minHeight: 44,minWidth: 112,@@ -150,6 +174,7 @@ const makeStyles = (colors: ThemeColors) =>color: colors.ctaText,fontSize: typeScale.body,fontWeight: fontWeight.medium,+ lineHeight: lineHeight.body,},disabled: { opacity: 0.46 },pressed: { opacity: 0.72 },diff --git a/apps/mobile/src/session/conversationShareRichSvg.ts b/apps/mobile/src/session/conversationShareRichSvg.tsnew file mode 100644index 0000000000..18642f551d--- /dev/null+++ b/apps/mobile/src/session/conversationShareRichSvg.ts@@ -0,0 +1,336 @@+import { latexToUnicodeApproximation } from "@cindy/maker-shared/math-markdown";+import { i18n } from "@/i18n";+import { tokenizeCode } from "@/session/codeHighlight";+import {+ parseMobileMarkdown,+ type MobileMarkdownBlock,+ type MobileMarkdownInline,+} from "@/session/messageMarkdown";+import type {+ ConversationShareMessage,+ ConversationShareWebViewColors,+} from "@/session/conversationShareWebViewHtml";+import type {+ ConversationShareSvgLayout,+ ConversationShareSvgTextBlock,+} from "@/session/conversationShareSvgLayout";+import { typeScale, lineHeight, spacing, radius } from "@/theme/tokens";++export interface ShareSvgRect {+ x: number;+ y: number;+ width: number;+ height: number;+ fill: string;+ stroke?: string;+ rx?: number;+}++type Run = Pick<+ ConversationShareSvgTextBlock,+ "color" | "bold" | "italic" | "decoration" | "monospace"+> & { text: string };++export function conservativeArialGlyphWidthEm(character: string): number {+ // Native SVG has no synchronous glyph measurement. Round wide glyphs up so+ // both the rich and redacted fallback layouts wrap before clipping.+ if (character === " ") return 0.33;+ if (character.codePointAt(0)! > 0x7f) return 1;+ if (character === "@") return 1.05;+ if ("W%".includes(character)) return 1;+ if ("Mm".includes(character)) return 0.9;+ if ("CGOQw".includes(character)) return 0.82;+ if ("ABDGHKNRUVXY&".includes(character)) return 0.75;+ if ("EFLPSTZ".includes(character)) return 0.68;+ if ("0123456789#?$+=<>^_~abdeghnopqu".includes(character)) return 0.62;+ if ("Jckrsvxyz".includes(character)) return 0.55;+ if ("(){}[]ft*".includes(character)) return 0.4;+ if (`!"',.:;\`il|/\\-`.includes(character)) return 0.36;+ return 0.68;+}++/** Pure native fallback layout. Keep Markdown structure instead of flattening it.+ * The caller retains whole-message redaction before choosing this path.+ */+export function layoutConversationShareRichBody(+ message: ConversationShareMessage,+ colors: ConversationShareWebViewColors,+ x: number,+ y: number,+ width: number,+) {+ const textBlocks: ConversationShareSvgTextBlock[] = [];+ const rectangles: ShareSvgRect[] = [];+ const images: ConversationShareSvgLayout["images"] = [];+ let cursor = y;+ const gap = spacing.md;++ function text(+ runs: Run[],+ left: number,+ top: number,+ available: number,+ size: number = typeScale.body,+ leading: number = lineHeight.body,+ ): number {+ if (available <= 0) return 0;+ // Even a single wide, bold glyph must fit in a narrow table cell.+ // Keep the normal line spacing while shrinking only constrained text.+ size = Math.min(size, available / (1.05 * 1.08));+ let dx = 0;+ let dy = 0;+ let hasText = false;+ for (const run of runs) {+ let fragment = "";+ let fragmentX = dx;+ const flush = () => {+ if (!fragment) return;+ const { text: _text, ...style } = run;+ textBlocks.push({+ ...style,+ fontSize: size,+ lineHeight: leading,+ lines: [fragment],+ x: left + fragmentX,+ y: top + dy + size,+ });+ fragment = "";+ };+ for (const char of Array.from(+ run.text.replace(/\r\n?/g, "\n").replace(/\t/g, " "),+ )) {+ const units = run.monospace+ ? char.codePointAt(0)! > 0x7f+ ? 1+ : 0.62+ : conservativeArialGlyphWidthEm(char);+ const advance = units * size * (run.bold ? 1.08 : 1);+ if (char === "\n" || (dx > 0 && dx + advance > available)) {+ flush();+ dx = 0;+ dy += leading;+ fragmentX = 0;+ if (char === "\n") {+ hasText = true;+ continue;+ }+ }+ if (!fragment) fragmentX = dx;+ fragment += char;+ dx += advance;+ hasText = true;+ }+ flush();+ }+ return hasText ? dy + leading : 0;+ }++ function inlines(+ items: readonly MobileMarkdownInline[],+ left: number,+ top: number,+ available: number,+ size: number = typeScale.body,+ leading: number = lineHeight.body,+ bold = false,+ ): number {+ let height = 0;+ let runs: Run[] = [];+ const flush = () => {+ height += text(runs, left, top + height, available, size, leading);+ runs = [];+ };+ for (const inline of items) {+ const image =+ inline.type === "image" ? message.images?.get(inline.url) : undefined;+ if (image) {+ flush();+ const scale = Math.min(1, available / image.width, 320 / image.height);+ images.push({+ uri: image.uri,+ x: left,+ y: top + height,+ width: image.width * scale,+ height: image.height * scale,+ });+ height += image.height * scale + 5;+ continue;+ }+ runs.push({+ text:+ inline.type === "image"+ ? inline.alt.trim() || i18n.t("message.renderer.imageFallbackTitle")+ : inline.type === "math"+ ? latexToUnicodeApproximation(inline.text)+ : inline.text,+ color: inline.type === "code" ? colors.inlineCode : colors.textPrimary,+ bold: bold || inline.type === "strong",+ italic: inline.type === "emphasis",+ monospace: inline.type === "code",+ decoration:+ inline.type === "link"+ ? "underline"+ : inline.type === "strikethrough"+ ? "line-through"+ : undefined,+ });+ }+ flush();+ return height;+ }++ function block(value: MobileMarkdownBlock) {+ if (value.type === "table") {+ const rows = [value.header, ...value.rows.map((row) => row.cells)];+ const columns = Math.max(...rows.map((row) => row.length), 1);+ const cellWidth = width / columns;+ const padding = Math.min(8, cellWidth / 8);+ rows.forEach((row, rowIndex) => {+ const top = cursor;+ let height = lineHeight.body + padding * 2;+ for (let column = 0; column < columns; column++) {+ height = Math.max(+ height,+ padding * 2 ++ inlines(+ row[column] ?? [],+ x + column * cellWidth + padding,+ top + padding,+ cellWidth - padding * 2,+ typeScale.footnote,+ lineHeight.code,+ rowIndex === 0,+ ),+ );+ }+ for (let column = 0; column < columns; column++) {+ rectangles.push({+ x: x + column * cellWidth,+ y: top,+ width: cellWidth,+ height,+ fill: rowIndex === 0 ? colors.surfaceChip : "none",+ stroke: colors.border,+ });+ }+ cursor += height;+ });+ } else if (+ value.type === "code" ||+ value.type === "mermaid" ||+ value.type === "math"+ ) {+ const top = cursor;+ const runs =+ value.type === "code"+ ? tokenizeCode(value.text, value.language).map((token) => ({+ text: token.text,+ color:+ token.kind === "plain"+ ? colors.textPrimary+ : (colors.syntax[token.kind] ?? colors.textPrimary),+ monospace: true,+ }))+ : [+ {+ text:+ value.type === "math"+ ? latexToUnicodeApproximation(value.text)+ : value.text,+ color: colors.textPrimary,+ monospace: true,+ },+ ];+ cursor +=+ 12 ++ text(+ runs,+ x + 12,+ cursor + 12,+ width - 24,+ typeScale.footnote,+ lineHeight.code,+ ) ++ 12;+ rectangles.push({+ x,+ y: top,+ width,+ height: cursor - top,+ fill: colors.codeSurface,+ stroke: colors.border,+ rx: radius.container,+ });+ } else if (value.type === "blockquote") {+ const height = inlines(value.inlines, x + 12, cursor, width - 12);+ rectangles.push({ x, y: cursor, width: 2, height, fill: colors.border });+ cursor += height;+ } else if (value.type === "list_item") {+ const marker =+ typeof value.checked === "boolean"+ ? `${value.ordered ? `${value.marker} ` : ""}${value.checked ? "☑" : "☐"}`+ : value.marker;+ const markerUnits = Array.from(marker).reduce(+ (sum, character) => sum + conservativeArialGlyphWidthEm(character),+ 0,+ );+ const markerWidth = Math.max(+ spacing.xl,+ markerUnits * typeScale.body + spacing.sm,+ );+ text(+ [{ text: marker, color: colors.textPrimary }],+ x,+ cursor,+ markerWidth,+ );+ cursor += Math.max(+ lineHeight.body,+ inlines(value.inlines, x + markerWidth, cursor, width - markerWidth),+ );+ } else {+ const heading = value.type === "heading";+ const size = heading+ ? value.level === 1+ ? typeScale.title+ : value.level === 2+ ? typeScale.subtitle+ : typeScale.body+ : typeScale.body;+ cursor += inlines(+ value.inlines,+ x,+ cursor,+ width,+ size,+ heading ? lineHeight.listTitle : lineHeight.body,+ heading,+ );+ }+ cursor += gap;+ }++ const markdown = (source: string) =>+ parseMobileMarkdown(source).forEach(block);+ if (message.bodyParts) {+ for (const part of message.bodyParts) {+ if (part.kind === "text") markdown(part.text);+ else {+ cursor +=+ text(+ [{ text: part.label, color: colors.textSecondary }],+ x,+ cursor,+ width,+ ) + gap;+ }+ }+ } else markdown(message.body);+ if (message.secondaryBody) markdown(message.secondaryBody);+ return {+ textBlocks,+ rectangles,+ images,+ height: Math.max(0, cursor - y - gap),+ };+}diff --git a/apps/mobile/src/session/conversationShareSvgLayout.ts b/apps/mobile/src/session/conversationShareSvgLayout.tsindex 693693f831..f6e0c996aa 100644--- a/apps/mobile/src/session/conversationShareSvgLayout.ts+++ b/apps/mobile/src/session/conversationShareSvgLayout.ts@@ -1,6 +1,11 @@import { redactSensitiveText } from "@cindy/maker-shared/error-redaction";import { i18n } from "@/i18n";+import {+ conservativeArialGlyphWidthEm,+ layoutConversationShareRichBody,+ type ShareSvgRect,+} from "@/session/conversationShareRichSvg";import {parseMobileMarkdown,type MobileMarkdownBlock,@@ -22,6 +27,10 @@ const MAX_OUTPUT_PIXELS = 12_000_000;const DEFAULT_EXPORT_SCALE = 2;export interface ConversationShareSvgTextBlock {+ bold?: boolean;+ italic?: boolean;+ monospace?: boolean;+ decoration?: "underline" | "line-through";color: string;fontSize: number;lineHeight: number;@@ -31,6 +40,7 @@ export interface ConversationShareSvgTextBlock {}export interface ConversationShareSvgBubble {+ rectangles?: ShareSvgRect[];fill?: string;height: number;stroke?: string;@@ -167,6 +177,37 @@ export function buildConversationShareSvgLayout({);}}+ let needsRedaction = false;+ const bodyParts = conversationShareBodyParts(message, () => {+ needsRedaction = true;+ });+ // Preserve the existing whole-message redaction path for secrets spanning+ // formatting, paragraphs or images. Never redact isolated styled runs.+ if (!needsRedaction && bodyParts.length > 0) {+ const paddingY = user ? 12 : 4;+ const body = layoutConversationShareRichBody(+ message,+ colors,+ bubbleX + horizontalPadding,+ cursorY + paddingY,+ textWidth,+ );+ const height = Math.max(user ? 44 : 30, body.height + paddingY * 2);+ bubbles.push({+ x: bubbleX,+ y: cursorY,+ width: bubbleWidth,+ height,+ fill: user ? colors.surfaceElevated : undefined,+ stroke: user ? colors.textSecondary : undefined,+ textBlocks: body.textBlocks,+ rectangles: body.rectangles,+ });+ images.push(...body.images);+ cursorY += height + MESSAGE_GAP;+ previousIndex = currentIndex;+ continue;+ }const blocks: Array<| { image: ConversationShareImage }| {@@ -177,7 +218,7 @@ export function buildConversationShareSvgLayout({}> = [];- for (const part of conversationShareBodyParts(message)) {+ for (const part of bodyParts) {if ("image" in part) blocks.push(part);elseblocks.push({@@ -251,6 +292,7 @@ type ShareBodyPart = { text: string } | { image: ConversationShareImage };/** Traverse occurrences, using the source map only to look up decoded bytes. */function conversationShareBodyParts(message: ConversationShareMessage,+ onRedaction?: () => void,): ShareBodyPart[] {const parts: ShareBodyPart[] = [];const append = (part: ShareBodyPart) => {@@ -278,6 +320,7 @@ function conversationShareBodyParts(const redacted = redactSensitiveText(fullText);let safeParts = parts;if (redacted !== fullText) {+ onRedaction?.();safeParts = [];let sourceOffset = 0;let safeOffset = 0;@@ -418,22 +461,3 @@ export function wrapSvgText(}return lines.length > 0 ? lines : [""];}--function conservativeArialGlyphWidthEm(character: string): number {- // react-native-svg does not expose synchronous glyph measurement while this- // pure layout is built. These Arial-like buckets intentionally round wide- // glyphs up so an exported line wraps early instead of being clipped.- if (character === " ") return 0.33;- if (character.codePointAt(0)! > 0x7f) return 1;- if (character === "@") return 1.05;- if ("W%".includes(character)) return 1;- if ("Mm".includes(character)) return 0.9;- if ("CGOQw".includes(character)) return 0.82;- if ("ABDGHKNRUVXY&".includes(character)) return 0.75;- if ("EFLPSTZ".includes(character)) return 0.68;- if ("0123456789#?$+=<>^_~abdeghnopqu".includes(character)) return 0.62;- if ("Jckrsvxyz".includes(character)) return 0.55;- if ("(){}[]ft*".includes(character)) return 0.4;- if (`!"',.:;\`il|/\\-`.includes(character)) return 0.36;- return 0.68;-}diff --git a/apps/mobile/src/session/conversationShareWebViewHtml.ts b/apps/mobile/src/session/conversationShareWebViewHtml.tsindex 5172b3b7bf..38ed1d3c06 100644--- a/apps/mobile/src/session/conversationShareWebViewHtml.ts+++ b/apps/mobile/src/session/conversationShareWebViewHtml.ts@@ -134,9 +134,14 @@ function buildMessageHtml(message: ConversationShareMessage,markdownOptions: SelectableMarkdownHtmlOptions,): string {- markdownOptions = { ...markdownOptions, imageSources: message.images ?? new Map() };+ markdownOptions = {+ ...markdownOptions,+ imageSources: message.images ?? new Map(),+ };const texts = message.bodyParts- ? message.bodyParts.flatMap((part) => part.kind === "text" ? [part.text] : [])+ ? message.bodyParts.flatMap((part) =>+ part.kind === "text" ? [part.text] : [],+ ): [message.body];if (message.secondaryBody) texts.push(message.secondaryBody);// Redaction can consume image delimiters as well as URLs. Let the existing@@ -146,7 +151,7 @@ function buildMessageHtml(texts.some((text) => redactSensitiveText(text) !== text) &&texts.some((text) => collectMobileMarkdownImages(text).length > 0)) {- throw new Error('conversation-share-image-requires-svg');+ throw new Error("conversation-share-image-requires-svg");}const body = redactSensitiveText(message.body).trim();const secondaryBody = message.secondaryBody@@ -160,15 +165,21 @@ function buildMessageHtml(const secondaryHtml = secondaryBody? buildSelectableMarkdownFragmentHtml(secondaryBody, markdownOptions): "";- const attachmentsHtml = buildAttachmentsHtml(message.attachments ?? [], message.images);- const bubbleHtml = bodyHtml || secondaryHtml- ? [- `<div class="share-bubble share-bubble-${message.kind}">`,- bodyHtml,- secondaryHtml ? `<div class="share-secondary">${secondaryHtml}</div>` : "",- "</div>",- ].join("")- : "";+ const attachmentsHtml = buildAttachmentsHtml(+ message.attachments ?? [],+ message.images,+ );+ const bubbleHtml =+ bodyHtml || secondaryHtml+ ? [+ `<div class="share-bubble share-bubble-${message.kind}">`,+ bodyHtml,+ secondaryHtml+ ? `<div class="share-secondary">${secondaryHtml}</div>`+ : "",+ "</div>",+ ].join("")+ : "";const automationOriginHtml = message.automationOriginLabel? `<div class="share-automation-origin">${escapeHtml(redactSensitiveText(message.automationOriginLabel).trim())}</div>`: "";@@ -189,31 +200,40 @@ function buildBodyPartsHtml(if (part.kind === "text") {const text = redactSensitiveText(part.text).trim();return text- ? [`<div class="share-content-text">${buildSelectableMarkdownFragmentHtml(text, markdownOptions)}</div>`]+ ? [+ `<div class="share-content-text">${buildSelectableMarkdownFragmentHtml(text, markdownOptions)}</div>`,+ ]: [];}const label = redactSensitiveText(part.label).trim();- const icon = part.kind === "quote" ? "❝" : part.kind === "pasted" ? "▤" : "";+ const icon =+ part.kind === "quote" ? "❝" : part.kind === "pasted" ? "▤" : "";const iconHtml = icon? `<span class="share-inline-chip-icon" aria-hidden="true">${icon}</span>`: "";return label- ? [`<span class="share-inline-chip share-inline-chip-${part.kind}">${iconHtml}<span class="share-inline-chip-label">${escapeHtml(label)}</span></span>`]+ ? [+ `<span class="share-inline-chip share-inline-chip-${part.kind}">${iconHtml}<span class="share-inline-chip-label">${escapeHtml(label)}</span></span>`,+ ]: [];});- return items.length > 0 ? `<div class="share-inline-body">${items.join("")}</div>` : "";+ return items.length > 0+ ? `<div class="share-inline-body">${items.join("")}</div>`+ : "";}function buildAttachmentsHtml(attachments: readonly ConversationShareAttachment[],- images?: ConversationShareMessage['images'],+ images?: ConversationShareMessage["images"],): string {if (attachments.length === 0) return "";const items = attachments.map((attachment) => {const name = redactSensitiveText(attachment.name).trim();- const image = attachment.kind === "image" && attachment.uri- ? images?.get(attachment.uri) : undefined;- if (image?.uri.startsWith('data:image/')) {+ const image =+ attachment.kind === "image" && attachment.uri+ ? images?.get(attachment.uri)+ : undefined;+ if (image?.uri.startsWith("data:image/")) {return `<img class="share-attachment-image" src="${escapeAttribute(image.uri)}" alt="${escapeAttribute(name)}">`;}return `<div class="share-attachment-chip share-attachment-chip-${attachment.kind}"><span class="share-attachment-icon" aria-hidden="true"></span><span class="share-attachment-label">${escapeHtml(name)}</span></div>`;@@ -235,7 +255,6 @@ function buildConversationShareMarkdownOptions(lineHeight: lineHeight.bodyLarge,mutedColor: colors.textSecondary,syntaxColors: colors.syntax,- tableCellMinWidth: layout.markdownTableCellMinWidth,textColor: colors.textPrimary,};}@@ -259,6 +278,9 @@ function buildConversationShareCss({textTertiary: string;width: number;}): string {+ const bodyGap = buildMessageContentLayout({+ screenWidth: width,+ }).markdownBodyGap;return `html, body {margin: 0;@@ -356,6 +378,9 @@ function buildConversationShareCss({.share-bubble {box-sizing: border-box;min-width: 0;+ display: flex;+ flex-direction: column;+ gap: ${bodyGap}px;}.share-bubble-user {max-width: 86%;@@ -372,6 +397,11 @@ function buildConversationShareCss({margin-top: 8px;color: ${cssValue(textSecondary)};}+ .share-secondary, .share-content-text {+ display: flex;+ flex-direction: column;+ gap: ${bodyGap}px;+ }.share-inline-body {display: flex;align-items: center;@@ -412,16 +442,22 @@ function buildConversationShareCss({}#xdt-content table {display: table;- width: max-content;- max-width: none;+ table-layout: fixed;+ width: 100%;+ max-width: 100%;overflow: visible;}+ #xdt-content th, #xdt-content td {+ min-width: 0;+ overflow-wrap: anywhere;+ }#xdt-content pre {- width: max-content;- min-width: 100%;- max-width: none;+ width: 100%;+ min-width: 0;+ max-width: 100%;overflow: visible;- white-space: pre;+ white-space: pre-wrap;+ overflow-wrap: anywhere;}.share-gap {width: 100%;@@ -508,7 +544,7 @@ function buildConversationShareRichContentScript({const katexLoader = includeKatex? buildKatexLoaderJs(renderKatexJs,- 'clearTimeout(mathFallback); mathDone = true; maybeReady();',+ "clearTimeout(mathFallback); mathDone = true; maybeReady();",): "";const mermaidRenderer = includeMermaid@@ -577,8 +613,8 @@ function buildConversationShareRichContentScript({? `if (!mermaidDone) {${buildMermaidLoaderJs(- 'renderMermaidNodes();',- 'mermaidDone = true; maybeReady();',+ "renderMermaidNodes();",+ "mermaidDone = true; maybeReady();",)}}`@@ -596,7 +632,18 @@ function buildConversationShareRichContentScript({function maybeReady() {if (!ready && mathDone && mermaidDone) {ready = true;- window.__cindyConversationShareRichContentReady = true;+ // A PNG cannot scroll. Fit unbreakable formulae after fonts settle, before+ // the native snapshot measures the stage (which requires a fixed width).+ Promise.resolve(document.fonts && document.fonts.ready).then(function () {+ document.querySelectorAll('.katex').forEach(function (formula) {+ var parent = formula.closest('[data-latex]');+ if (!parent) return;+ var available = parent.clientWidth || parent.parentElement.clientWidth;+ var width = Math.max(formula.scrollWidth, formula.getBoundingClientRect().width);+ if (available > 0 && width > available) formula.style.zoom = String(available / width);+ });+ window.__cindyConversationShareRichContentReady = true;+ });}}