Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 分享聊天长图时保留粘贴和正文图片 (#3962)
Dash1f7b032b720b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 9116c076f0..40cfa85860 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -136,6 +136,7 @@ import {collectConversationShareBlockIds,collectConversationShareMessages,} from '@/session/conversationShareMessages';+import { useConversationShareImages } from '@/session/useConversationShareImages';import {isFoldableBlockExpanded,useFoldableExpandedBlocksSnapshot,@@ -5623,30 +5624,11 @@ export default function SessionScreen() {textTertiary: colors.textTertiary,dark: mode === 'dark',}), [colors, mode]);- const conversationShareHtml = useMemo(() => {- if (- !nativeConversationShareAvailable- || !shareSelectionActive- || selectedShareMessages.length === 0- ) return '';- return buildConversationShareHtml({- allShareableIds,- characterSrc: shareCharacterSrc ?? undefined,- colors: conversationShareColors,- contentWidth: windowDimensions.width,- logoSrc: shareLogoModeRef.current === mode ? shareLogoSrc ?? undefined : undefined,- selectedMessages: selectedShareMessages,- });- }, [- allShareableIds,- conversationShareColors,- mode,- selectedShareMessages,- shareCharacterSrc,- shareLogoSrc,- shareSelectionActive,- windowDimensions.width,- ]);+ const shareImages = useConversationShareImages(selectedShareMessages, resolveRemoteMedia, {+ workdir: currentSession?.workingDir ?? undefined,+ remoteHostId: currentSession?.remoteHostId ?? undefined,+ sessionId,+ });const enterShareSelection = useCallback((clientId: string) => {Keyboard.dismiss();setShareSelectionTriggeredByScreenshot(false);@@ -5654,21 +5636,31 @@ export default function SessionScreen() {}, [sessionId]);const cancelShareSelection = useCallback(() => {shareOperationSeqRef.current += 1;+ shareImages.cancel();setConversationShareBusy(false);setShareSelectionTriggeredByScreenshot(false);shareSelectionStore.exit();- }, []);+ }, [shareImages.cancel]);const exportConversationSharePng = useCallback(async () => {+ const messages = await shareImages.prepare();+ if (messages.length === 0) throw new Error('conversation share selection changed');const nativeShareAssetsReady = Boolean(nativeConversationShareAvailable&& shareCharacterSrc&& shareLogoSrc&& shareLogoModeRef.current === mode,);- if (conversationShareHtml && nativeShareAssetsReady) {+ if (nativeShareAssetsReady) {try {const nativeBase64 = await renderConversationShareHtmlToPng({- html: conversationShareHtml,+ html: buildConversationShareHtml({+ allShareableIds,+ characterSrc: shareCharacterSrc ?? undefined,+ colors: conversationShareColors,+ contentWidth: windowDimensions.width,+ logoSrc: shareLogoSrc ?? undefined,+ selectedMessages: messages,+ }),width: windowDimensions.width,});if (nativeBase64) {@@ -5682,7 +5674,7 @@ export default function SessionScreen() {const svg = conversationShareSvgRef.current;if (!svg) throw new Error('conversation share svg renderer is unavailable');return svg.exportPng();- }, [conversationShareHtml, mode, shareCharacterSrc, shareLogoSrc, windowDimensions.width]);+ }, [shareImages.prepare, allShareableIds, conversationShareColors, mode, shareCharacterSrc, shareLogoSrc, windowDimensions.width]);const shareSelectedConversation = useCallback(async () => {if (conversationShareBusy@@ -9415,9 +9407,10 @@ export default function SessionScreen() {</ComposerKeyboardAvoidingView>{shareSelectionActive && selectedShareMessages.length > 0 ? (<ConversationShareSvg+ key={`${shareImages.revision}-${mode}`}allShareableIds={allShareableIds}colors={conversationShareColors}- messages={selectedShareMessages}+ messages={shareImages.messages}ref={conversationShareSvgRef}width={windowDimensions.width}/>diff --git a/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsxnew file mode 100644index 0000000000..b75d05eb85--- /dev/null+++ b/apps/mobile/src/__tests__/ConversationShareSvgExport.test.tsx@@ -0,0 +1,390 @@+// @vitest-environment jsdom+import Module, { createRequire } from "node:module";+import { act, createRef, StrictMode } from "react";+import { createRoot, type Root } from "react-dom/client";+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import type { ConversationShareSvgHandle } from "@/session/ConversationShareSvg";+import type { ConversationShareMessage } from "@/session/conversationShareWebViewHtml";+import { lightColors, darkColors } from "@/theme/tokens";++const native = vi.hoisted(() => ({+ os: "ios",+ nextId: 0,+ svgLoads: new Map<number, () => void>(),+ imageLoads: new Map<string, () => void>(),+ imageErrors: new Map<string, () => void>(),+ barrier: undefined as (() => void) | undefined,+ queryCache: vi.fn(),+ capture: vi.fn(),+}));+vi.mock("@/theme", () => ({ typeScale: { body: 15 } }));+vi.mock("react-native", async () => {+ const { createElement, useLayoutEffect } = await import("react");+ const uri = (source: string | { uri: string }) =>+ typeof source === "string" ? source : source.uri;+ const Image = Object.assign(+ ({+ source,+ onLoad,+ onError,+ }: {+ source: string | { uri: string };+ onLoad: () => void;+ onError: () => void;+ }) => {+ native.imageLoads.set(uri(source), onLoad);+ native.imageErrors.set(uri(source), onError);+ return createElement("span", { "data-probe": uri(source) });+ },+ {+ resolveAssetSource: (source: string | { uri: string }) => ({+ uri: uri(source),+ width: 100,+ height: 20,+ }),+ queryCache: native.queryCache,+ },+ );+ return {+ Image,+ Platform: {+ get OS() {+ return native.os;+ },+ },+ StyleSheet: { create: (s: unknown) => s },+ View: ({+ children,+ onLayout,+ }: {+ children?: import("react").ReactNode;+ onLayout?: () => void;+ }) => {+ useLayoutEffect(() => {+ if (!onLayout) return;+ native.barrier = onLayout;+ return () => {+ native.barrier = undefined;+ };+ }, [onLayout]);+ return createElement(+ "div",+ { "data-barrier": onLayout ? "true" : undefined },+ children,+ );+ },+ };+});+vi.mock("react-native-svg", async () => {+ const { createElement, forwardRef, useImperativeHandle, useState } =+ await import("react");+ const element = ({ children }: { children?: import("react").ReactNode }) =>+ createElement("span", null, children);+ return {+ default: forwardRef(+ ({ children }: { children?: import("react").ReactNode }, ref) => {+ useImperativeHandle(ref, () => ({ toDataURL: native.capture }), []);+ return createElement("section", { "data-svg": "true" }, children);+ },+ ),+ ClipPath: element,+ Defs: element,+ Rect: element,+ Text: element,+ TSpan: element,+ Image: ({+ href,+ onLoad,+ }: {+ href: string | { uri: string };+ onLoad: () => void;+ }) => {+ const [id] = useState(() => ++native.nextId);+ native.svgLoads.set(id, onLoad);+ return createElement("span", {+ "data-svg-image": id,+ "data-uri": typeof href === "string" ? href : href.uri,+ });+ },+ };+});++let ConversationShareSvg: typeof import("@/session/ConversationShareSvg").ConversationShareSvg;+const require = createRequire(import.meta.url);+const oldJpg = require.extensions[".jpg"];+const oldPng = require.extensions[".png"];+const nodeModule = Module as unknown as {+ _resolveFilename(request: string, ...args: unknown[]): string;+};+const resolveFilename = nodeModule._resolveFilename;+beforeAll(async () => {+ // Metro's static require assets are opaque identifiers; native decoding is+ // driven explicitly below. Do not replace the component or layout builder.+ require.extensions[".jpg"] = require.extensions[".png"] = (module, file) => {+ module.exports = file;+ };+ // Metro also resolves an unsuffixed asset to its checked-in density variant.+ nodeModule._resolveFilename = function (request, ...args) {+ return resolveFilename.call(+ this,+ request.replace(+ /^(\.\.\/\.\.\/assets\/login\/login-wordmark(?:-dark)?)\.png$/,+ "[email protected]",+ ),+ ...args,+ );+ };+ ({ ConversationShareSvg } = await import("@/session/ConversationShareSvg"));+});+afterAll(() => {+ nodeModule._resolveFilename = resolveFilename;+ if (oldJpg) require.extensions[".jpg"] = oldJpg;+ else delete require.extensions[".jpg"];+ if (oldPng) require.extensions[".png"] = oldPng;+ else delete require.extensions[".png"];+});++const good = "data:image/png;base64,Z29vZA==";+const bad = "data:image/png;base64,YmFk";+const message: ConversationShareMessage = {+ clientId: "m",+ kind: "assistant",+ attachments: [+ { kind: "image", uri: "cindy-media://bad", name: "broken attachment" },+ ],+ body: "before  middle  after ",+ images: new Map([+ ["cindy-media://good", { uri: good, width: 40, height: 20 }],+ ["cindy-media://bad", { uri: bad, width: 40, height: 20 }],+ ]),+};+let root: Root;+let host: HTMLDivElement;+let ref: ReturnType<typeof createRef<ConversationShareSvgHandle>>;+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ native.os = "ios";+ native.svgLoads.clear();+ native.imageLoads.clear();+ native.imageErrors.clear();+ native.capture+ .mockReset()+ .mockImplementation((done: (s: string) => void) => done("png"));+ native.queryCache+ .mockReset()+ .mockImplementation(async (uris: string[]) =>+ Object.fromEntries(uris.map((uri) => [uri, "memory"])),+ );+ native.barrier = undefined;+ host = document.createElement("div");+ root = createRoot(host);+ ref = createRef();+});+afterEach(async () => {+ await act(async () => root.unmount());+ expect(vi.getTimerCount()).toBe(0);+ vi.useRealTimers();+});+function render(width = 390, dark = false) {+ const colors = dark ? darkColors : lightColors;+ root.render(+ <StrictMode>+ <ConversationShareSvg+ ref={ref}+ messages={[message]}+ allShareableIds={["m"]}+ colors={{+ ...colors,+ dark,+ background: colors.surface,+ codeSurface: colors.chatCodeSurface,+ inlineCode: colors.chatInlineCodeText,+ syntax: {+ comment: colors.syntaxComment,+ function: colors.syntaxFunction,+ keyword: colors.syntaxKeyword,+ number: colors.syntaxNumber,+ property: colors.syntaxProperty,+ string: colors.syntaxString,+ },+ }}+ width={width}+ />+ </StrictMode>,+ );+}+function svgNodes(uri?: string) {+ return Array.from(+ host.querySelectorAll<HTMLElement>("[data-svg-image]"),+ ).filter((node) => !uri || node.dataset.uri === uri);+}+function loadSvgExcept(excluded?: string) {+ for (const node of svgNodes())+ if (node.dataset.uri !== excluded)+ native.svgLoads.get(Number(node.dataset.svgImage))!();+}+async function start() {+ let result!: Promise<string>;+ await act(async () => {+ result = ref.current!.exportPng();+ });+ return { result };+}++describe("SVG export lifecycle", () => {+ it.each([false, true])(+ "waits for each cold iOS occurrence, then captures once after native layout (dark=%s)",+ async (dark) => {+ await act(async () => render(390, dark));+ const { result } = await start();+ const last = svgNodes(good).at(-1)!;+ await act(async () => {+ for (const node of svgNodes())+ if (node !== last)+ native.svgLoads.get(Number(node.dataset.svgImage))!();+ });+ expect(native.barrier).toBeUndefined();+ await act(async () =>+ native.svgLoads.get(Number(last.dataset.svgImage))!(),+ );+ expect(native.capture).not.toHaveBeenCalled();+ await act(async () => {+ native.barrier!();+ native.barrier!();+ });+ await expect(result).resolves.toBe("png");+ expect(native.capture).toHaveBeenCalledTimes(1);+ expect(svgNodes(good)).toHaveLength(2);+ expect(svgNodes(bad)).toHaveLength(2);+ },+ );++ it("freezes timeout fallback before capture, preserving normal occurrences and ignoring late loads", async () => {+ await act(async () => render());+ const goodNodes = svgNodes(good);+ const lateLoads = svgNodes(bad).map((node) =>+ native.svgLoads.get(Number(node.dataset.svgImage))!,+ );+ const { result } = await start();+ await act(async () => loadSvgExcept(bad));+ await act(async () => vi.advanceTimersByTimeAsync(15_000));+ 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).not.toContain("cindy-media://bad");+ await act(async () => {+ lateLoads.forEach((load) => load());+ render(420);+ });+ expect(svgNodes(bad)).toHaveLength(0);+ expect(svgNodes(good)).toEqual(goodNodes);+ await act(async () => native.barrier!());+ await expect(result).resolves.toBe("png");+ });++ it.each(["error", "disk", "empty-cache", "query-error"])(+ "handles Android cache hits with no SVG event and %s for a damaged image",+ async (failure) => {+ native.os = "android";+ native.queryCache.mockImplementation(async ([uri]: string[]) => {+ if (uri === bad && failure === "query-error")+ throw new Error("cache unavailable");+ if (uri === bad && failure === "empty-cache") return {};+ return { [uri!]: uri === bad ? "disk" : "memory" };+ });+ await act(async () => render());+ const { result } = await start();+ await act(async () => {+ for (const [uri, load] of native.imageLoads) {+ if (uri === bad && failure === "error")+ native.imageErrors.get(uri)!();+ else load();+ }+ });+ expect(svgNodes(good)).toHaveLength(2);+ expect(svgNodes(bad)).toHaveLength(0);+ expect(host.textContent).toContain("broken inline");+ // Bundled resource names are not queryable via Android's URI-only cache API.+ expect(+ native.queryCache.mock.calls.every(([uris]) =>+ uris[0].startsWith("data:"),+ ),+ ).toBe(true);+ expect(native.capture).not.toHaveBeenCalled();+ await act(async () => native.barrier!());+ await expect(result).resolves.toBe("png");+ },+ );++ it("rejects a missing footer within the deadline instead of capturing an incomplete footer", async () => {+ await act(async () => render());+ const { result } = await start();+ const rejected = expect(result).rejects.toThrow("footer is unavailable");+ await act(async () => {+ for (const node of [...svgNodes(good), ...svgNodes(bad)])+ native.svgLoads.get(Number(node.dataset.svgImage))!();+ await vi.advanceTimersByTimeAsync(15_000);+ });+ await rejected;+ expect(native.capture).not.toHaveBeenCalled();+ });++ it.each(["decoding", "layout", "capturing"])(+ "cancels on unmount during %s and ignores late native events",+ async (stage) => {+ native.capture.mockImplementation(() => {});+ await act(async () => render());+ const { result } = await start();+ const rejected = expect(result).rejects.toThrow("cancelled");+ if (stage !== "decoding") await act(async () => loadSvgExcept());+ const lateLayout = native.barrier;+ if (stage === "capturing") await act(async () => native.barrier!());+ const lateCapture = native.capture.mock.calls[0]?.[0];+ await act(async () => root.render(null));+ await rejected;+ await act(async () => {+ native.svgLoads.forEach((load) => load());+ lateLayout?.();+ lateCapture?.("late png");+ });+ expect(native.capture).toHaveBeenCalledTimes(+ stage === "capturing" ? 1 : 0,+ );+ },+ );++ it.each(["throw", "empty", "no-callback", "no-layout"])(+ "bounds capture failure: %s",+ async (failure) => {+ native.capture.mockImplementation((done: (s: string) => void) => {+ if (failure === "throw") throw new Error("capture failed");+ if (failure === "empty") done("");+ });+ await act(async () => render());+ const { result } = await start();+ const rejected = expect(result).rejects.toThrow(+ failure === "throw"+ ? "capture failed"+ : failure === "empty"+ ? "empty"+ : "timed out",+ );+ await act(async () => loadSvgExcept());+ if (failure !== "no-layout") await act(async () => native.barrier!());+ await act(async () => vi.advanceTimersByTimeAsync(20_000));+ await rejected;+ },+ );+});diff --git a/apps/mobile/src/__tests__/conversationShareImages.test.ts b/apps/mobile/src/__tests__/conversationShareImages.test.tsnew file mode 100644index 0000000000..a90850b0f5--- /dev/null+++ b/apps/mobile/src/__tests__/conversationShareImages.test.ts@@ -0,0 +1,337 @@+import { describe, expect, it, vi } from "vitest";+import { prepareConversationShareImages } from "@/session/conversationShareImages";+import { projectConversationShareMessage } from "@/session/conversationShareProjection";+import { buildConversationShareHtml } from "@/session/conversationShareWebViewHtml";+import { buildConversationShareSvgLayout } from "@/session/conversationShareSvgLayout";+import { lightColors, darkColors } from "@/theme/tokens";++const image = {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 640,+ height: 480,+};++describe("conversation share images", () => {+ it("lets free workers advance across messages while the first source is stalled", async () => {+ const finishes = new Map<string, (value: typeof image | null) => void>();+ let active = 0;+ let peak = 0;+ const load = vi.fn((url: string) => {+ peak = Math.max(peak, ++active);+ return new Promise<typeof image | null>((resolve) =>+ finishes.set(url, resolve),+ ).finally(() => {+ active--;+ });+ });+ const messages = Array.from({ length: 6 }, (_, i) => ({+ clientId: String(i),+ kind: "user" as const,+ body: "",+ attachments: [+ { kind: "image" as const, name: String(i), uri: `cindy-media://${i}` },+ ],+ }));+ const pending = prepareConversationShareImages(messages, load);+ expect(load).toHaveBeenCalledTimes(3);+ for (let i = 1; i < 6; i++) {+ await vi.waitFor(() =>+ expect(finishes.has(`cindy-media://${i}`)).toBe(true),+ );+ finishes.get(`cindy-media://${i}`)!(image);+ }+ finishes.get("cindy-media://0")!(null);+ const result = await pending;+ expect(peak).toBe(3);+ expect(load).toHaveBeenCalledTimes(6);+ expect(result.map((m) => m.clientId)).toEqual(+ messages.map((m) => m.clientId),+ );+ expect(result.map((m) => m.images!.size)).toEqual([0, 1, 1, 1, 1, 1]);+ });++ it("admits ready sources within both occurrence budgets and discards cancelled late loads", async () => {+ for (const cancel of [false, true]) {+ let active = true;+ const finishes = new Map<string, (value: typeof image) => void>();+ const load = vi.fn(+ (url: string) =>+ new Promise<typeof image>((done) => finishes.set(url, done)),+ );+ const urls = ["first", "second", "third", "queued"];+ const pending = prepareConversationShareImages(+ [+ {+ clientId: "m",+ kind: "user",+ body: "",+ attachments: urls.flatMap((url) =>+ Array.from({ length: 2 }, () => ({+ kind: "image" as const,+ name: url,+ uri: url,+ })),+ ),+ },+ ],+ load,+ {},+ () => active,+ );+ expect(load).toHaveBeenCalledTimes(3);+ if (cancel) active = false;+ const large = {+ ...image,+ width: 2000,+ height: 2000,+ uri: "data:image/png;base64," + "A".repeat(10 * 1024 * 1024),+ };+ finishes.get("second")!(large);+ finishes.get("third")!(large);+ finishes.get("first")!(large);+ const result = await pending;+ expect(load).toHaveBeenCalledTimes(3);+ if (cancel) expect(result).toEqual([]);+ else expect([...result[0]!.images!.keys()]).toEqual(["second"]);+ }+ });++ it("rejects compressed images above the single-image pixel limit without spending the batch budget", async () => {+ const load = vi.fn(async (url: string) => ({+ ...image,+ width: url.endsWith("huge") ? 100_000 : 2_000,+ height: url.endsWith("huge") ? 100_000 : 2_000,+ }));+ const messages = await prepareConversationShareImages(+ [+ {+ clientId: "m",+ kind: "user",+ body: "keep text",+ attachments: [+ { kind: "image", name: "huge", uri: "cindy-media://huge" },+ { kind: "image", name: "one", uri: "cindy-media://one" },+ { kind: "image", name: "two", uri: "cindy-media://two" },+ { kind: "image", name: "over batch", uri: "cindy-media://three" },+ ],+ },+ ],+ load,+ );+ expect([...messages[0]!.images!.keys()]).toEqual([+ "cindy-media://one",+ "cindy-media://two",+ ]);+ expect(messages[0]!.body).toBe("keep text");+ expect(messages[0]!.attachments).toHaveLength(4);+ });++ it("charges decoded pixels for repeated sources across attachments, structured/secondary text and messages", async () => {+ const url = "cindy-media://same";+ const load = vi.fn(async () => ({ ...image, width: 2_000, height: 1_000 }));+ const message = {+ clientId: "first",+ kind: "user" as const,+ body: "ignored",+ attachments: [{ kind: "image" as const, name: "paste", uri: url }],+ bodyParts: [{ kind: "text" as const, text: `` }],+ secondaryBody: ``,+ };+ const result = await prepareConversationShareImages(+ [+ message,+ { ...message, clientId: "over" },+ { clientId: "last", kind: "assistant", body: `` },+ ],+ load,+ );+ expect(result.map((m) => m.images!.size)).toEqual([1, 0, 1]);+ expect(load).toHaveBeenCalledTimes(1);+ // A rejected oversized occurrence group must not poison a later smaller group.+ const retry = await prepareConversationShareImages(+ [+ { ...message, secondaryBody: `` },+ { ...message, clientId: "later" },+ ],+ load,+ );+ expect(retry.map((m) => m.images!.size)).toEqual([0, 1]);+ });++ it("charges every attachment and Markdown occurrence even when bytes are reused across messages", async () => {+ const largeImage = {+ ...image,+ uri: "data:image/png;base64," + "A".repeat(6 * 1024 * 1024),+ };+ const source = "cindy-media://repeated";+ const load = vi.fn(async () => largeImage);+ const repeated = {+ clientId: "one",+ kind: "user" as const,+ body: ``,+ secondaryBody: ``,+ attachments: [{ kind: "image" as const, name: "paste", uri: source }],+ };+ const messages = await prepareConversationShareImages(+ [repeated, { ...repeated, clientId: "two" }],+ load,+ );+ expect(messages[0]?.images?.get(source)).toBe(largeImage);+ expect(messages[1]?.images?.size).toBe(0);+ expect(load).toHaveBeenCalledTimes(1);+ load.mockClear();+ const tooMany = await prepareConversationShareImages(+ [+ {+ ...repeated,+ attachments: Array.from(+ { length: 4 },+ () => repeated.attachments[0]!,+ ),+ },+ { ...repeated, clientId: "later" },+ ],+ load,+ );+ expect(tooMany[0]?.images?.size).toBe(0);+ expect(tooMany[1]?.images?.get(source)).toBe(largeImage);+ expect(load).toHaveBeenCalledTimes(1);+ });++ it.each([lightColors, darkColors])(+ "embeds pasted and inline images in both exporters without source URLs",+ async (theme) => {+ const source = "cindy-media://asset/pasted";+ const inline = "https://example.com/image.png?signature=private";+ const projected = projectConversationShareMessage("user", {+ kind: "user",+ body: `Picture: `,+ attachments: [+ { kind: "image", name: "pasted.png", uri: source, previewable: true },+ ],+ })!;+ const load = vi.fn(async () => image);+ const messages = await prepareConversationShareImages([projected], load);+ 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({+ selectedMessages: messages,+ allShareableIds: ["user"],+ colors,+ contentWidth: 390,+ });+ expect(html.split(`src="${image.uri}"`)).toHaveLength(3);+ expect(html).not.toContain(source);+ expect(html).not.toContain(inline);+ expect(html).toContain("img-src data:");+ const svg = buildConversationShareSvgLayout({+ messages,+ allShareableIds: ["user"],+ colors,+ width: 390,+ });+ expect(svg.images).toHaveLength(2);+ for (const rendered of svg.images) {+ expect(rendered.uri).toBe(image.uri);+ expect(rendered.width / rendered.height).toBeCloseTo(4 / 3);+ expect(rendered.x + rendered.width).toBeLessThanOrEqual(390);+ expect(rendered.y + rendered.height).toBeLessThan(svg.footerY);+ }+ },+ );++ it("reuses attachment bytes, skips code and hidden chip contents, and preserves failures", async () => {+ const load = vi.fn((url: string) => {+ if (url.includes("missing")) throw new Error("offline");+ return Promise.resolve(image);+ });+ const messages = await prepareConversationShareImages(+ [+ {+ clientId: "u",+ kind: "user",+ body: "",+ bodyParts: [+ { kind: "quote", label: "" },+ {+ kind: "text",+ text: "```md\n\n```",+ },+ ],+ attachments: [+ { kind: "image", name: "one", uri: "cindy-media://same" },+ { kind: "image", name: "two", uri: "cindy-media://same" },+ { kind: "image", name: "missing", uri: "cindy-media://missing" },+ { kind: "file", name: "file", uri: "file:///private/file" },+ ],+ },+ ],+ load,+ );+ expect(load.mock.calls.map(([url]) => url)).toEqual([+ "cindy-media://same",+ "cindy-media://missing",+ ]);+ expect(messages[0]?.images?.size).toBe(1);+ expect(messages[0]?.attachments?.[2]?.name).toBe("missing");+ });++ it("routes relative and forged SSH image URLs using the current trusted session", async () => {+ const load = vi.fn(async () => image);+ await prepareConversationShareImages(+ [+ {+ clientId: "m",+ kind: "assistant",+ body: "\n",+ },+ ],+ load,+ { workdir: "/work", remoteHostId: "host", sessionId: "session" },+ );+ for (const [url] of load.mock.calls as unknown as [string][]) {+ const parsed = new URL(url);+ expect(parsed.protocol).toBe("xdt-file:");+ expect(parsed.searchParams.get("sessionId")).toBe("session");+ expect(parsed.searchParams.get("remoteHostId")).toBe("host");+ expect(parsed.searchParams.get("v")).toBe("m");+ }+ expect(load).toHaveBeenCalled();+ });++ it("stops reading remaining images when selection is cancelled", async () => {+ let active = true;+ const load = vi.fn(async () => {+ active = false;+ return image;+ });+ const result = await prepareConversationShareImages(+ [+ {+ clientId: "u",+ kind: "user",+ body: "",+ attachments: [+ { kind: "image", name: "one", uri: "cindy-media://one" },+ { kind: "image", name: "two", uri: "cindy-media://two" },+ ],+ },+ ],+ load,+ {},+ () => active,+ );+ expect(load).toHaveBeenCalledTimes(1);+ expect(result).toEqual([]);+ });+});diff --git a/apps/mobile/src/__tests__/conversationShareProjection.test.ts b/apps/mobile/src/__tests__/conversationShareProjection.test.tsindex 7cf51760e5..eb3090ef04 100644--- a/apps/mobile/src/__tests__/conversationShareProjection.test.ts+++ b/apps/mobile/src/__tests__/conversationShareProjection.test.ts@@ -45,7 +45,7 @@ describe('projectConversationShareMessage', () => {);});- it('按气泡顺序保留图片和文件名,不把附件字节或来源带入导出', () => {+ it('保留图片读取地址和附件顺序,但不带入普通文件的本机路径', () => {const projected = projectConversationShareMessage('attachments', {attachments: [{@@ -72,12 +72,10 @@ describe('projectConversationShareMessage', () => {});expect(projected?.attachments).toEqual([- { kind: 'image', name: 'inline.png' },- { kind: 'image', name: 'remote.png' },+ { kind: 'image', name: 'inline.png', uri: 'data:image/png;base64,AA==' },+ { kind: 'image', name: 'remote.png', uri: 'https://example.com/private.png' },{ kind: 'file', name: 'notes.md' },]);- expect(JSON.stringify(projected)).not.toContain('example.com');expect(JSON.stringify(projected)).not.toContain('/private/project');- expect(JSON.stringify(projected)).not.toContain('data:image');});});diff --git a/apps/mobile/src/__tests__/conversationShareSvg.test.ts b/apps/mobile/src/__tests__/conversationShareSvg.test.tsindex 2a88607a73..bde997609c 100644--- a/apps/mobile/src/__tests__/conversationShareSvg.test.ts+++ b/apps/mobile/src/__tests__/conversationShareSvg.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from "vitest";+import { redactSensitiveText } from "@cindy/maker-shared/error-redaction";import { i18n } from "@/i18n";-import { createConversationShareFooterAssetGate } from "@/session/conversationShareAssetGate";+import { createConversationShareAssetGate } from "@/session/conversationShareAssetGate";import {buildConversationShareSvgLayout,conversationShareSvgRenderSize,@@ -29,6 +30,271 @@ const colors = {};describe("ConversationShareSvg", () => {+ it.each(["user", "assistant"] as const)(+ "preserves mixed attachment order through every image fallback combination for %s",+ (kind) => {+ for (let ready = 0; ready < 8; ready++) {+ const urls = ["first", "second", "third"];+ const images = new Map(+ urls.flatMap((url, index) =>+ ready & (1 << index)+ ? [+ [+ url,+ {+ uri: `data:image/png;base64,${url}`,+ width: 40,+ height: 20,+ },+ ] as const,+ ]+ : [],+ ),+ );+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ colors,+ width: 390,+ messages: [+ {+ clientId: "m",+ kind,+ automationOriginLabel: "automation",+ body: "body",+ attachments: [+ { kind: "image", name: "first", uri: "first" },+ { kind: "file", name: "document" },+ { kind: "image", name: "second", uri: "second" },+ { kind: "image", name: "third", uri: "third" },+ ],+ images,+ },+ ],+ });+ const visible = [+ ...layout.images.map((image) => ({+ y: image.y,+ text: image.uri.split(",")[1],+ })),+ ...layout.bubbles.map((bubble) => ({+ y: bubble.y,+ text: bubble.textBlocks+ .flatMap((block) => block.lines)+ .join(" ")+ .replace(/^[▧▤] /, ""),+ })),+ ].sort((a, b) => a.y - b.y);+ expect(visible.map((item) => item.text)).toEqual([+ "automation",+ "first",+ "document",+ "second",+ "third",+ "body",+ ]);+ for (let i = 1; i < visible.length; i++) {+ expect(visible[i]!.y).toBeGreaterThan(visible[i - 1]!.y);+ }+ }+ },+ );++ it.each([0, 1, 2])(+ "keeps attribution above all content with %i decoded attachments",+ (decodedCount) => {+ for (const body of ["", "message body"]) {+ const image = {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 40,+ height: 20,+ };+ const urls = ["cindy-media://first", "cindy-media://second"];+ const label = "Sent by automation: ".repeat(8);+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["previous", "skipped", "m", "next"],+ colors,+ width: 390,+ messages: [+ { clientId: "previous", kind: "assistant", body: "previous" },+ {+ clientId: "m",+ kind: "user",+ automationOriginLabel: label,+ attachments: urls.map((uri) => ({+ kind: "image",+ name: "attachment",+ uri,+ })),+ images: new Map(+ urls.slice(0, decodedCount).map((uri) => [uri, image]),+ ),+ body,+ },+ { clientId: "next", kind: "assistant", body: "next" },+ ],+ });+ const attribution = layout.bubbles[1]!;+ expect(attribution.fill).toBeUndefined();+ expect(attribution.stroke).toBeUndefined();+ expect(attribution.textBlocks).toHaveLength(1);+ expect(attribution.textBlocks[0]!.lines.length).toBeGreaterThan(1);+ expect(attribution.textBlocks[0]!.lines.join(" ")).toContain(+ "Sent by automation:",+ );+ expect(attribution.textBlocks[0]!.color).toBe(colors.textTertiary);+ expect(layout.gaps[0]!.y).toBeLessThan(attribution.y);+ expect(layout.images).toHaveLength(decodedCount);+ const attributionBottom = attribution.y + attribution.height;+ for (const item of [...layout.images, ...layout.bubbles.slice(2)]) {+ expect(item.y).toBeGreaterThan(attributionBottom);+ }+ const content = layout.bubbles.slice(2, -1);+ expect(content).toHaveLength(2 - decodedCount + (body ? 1 : 0));+ expect(+ content+ .flatMap((bubble) => bubble.textBlocks)+ .some((block) =>+ block.lines.join(" ").includes("Sent by automation:"),+ ),+ ).toBe(false);+ expect(layout.bubbles.at(-1)!.y).toBeGreaterThan(+ layout.images.at(-1)?.y ?? attributionBottom,+ );+ }+ },+ );++ it.each([+ ["password: ", "private-secret"],+ ["pass", "word: private-secret"],+ ["password: private-", "secret"],+ ["Authorization: Basic ", "private-secret"],+ ["sk-abcd", "12345678"],+ ["password: ", "`private-secret`"],+ ["password: ", "**private-secret**"],+ ["password:\n\n", "private-secret"],+ ["token: [REDACTED]\npassword: ", "private-secret"],+ ])("redacts across an image between %s and %s", (before, after) => {+ const url = "cindy-media://same";+ const image = {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 40,+ height: 20,+ };+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ colors,+ width: 390,+ messages: [+ {+ clientId: "m",+ kind: "assistant",+ body: `${before}${after}`,+ images: new Map([[url, image]]),+ },+ ],+ });+ const text = layout.bubbles+ .flatMap((bubble) => bubble.textBlocks.flatMap((block) => block.lines))+ .join("");+ const visible = (before + after).replace(/[`*]/g, "");+ expect(text.replace(/\s/g, "")).toBe(+ redactSensitiveText(visible).replace(/\s/g, ""),+ );+ expect(layout.images).toHaveLength(2);+ expect(layout.images[0]!.y).toBeLessThan(layout.images[1]!.y);+ expect(text).not.toContain("private-secret");+ });++ it.each(["user", "assistant"] as const)(+ "preserves repeated image positions inside a %s bubble, including an attachment with the same source",+ (kind) => {+ const url = "cindy-media://same";+ const image = {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 40,+ height: 20,+ };+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ colors,+ width: 390,+ messages: [+ {+ clientId: "m",+ kind,+ attachments: [{ kind: "image", name: "attachment", uri: url }],+ body: `before  middle  after`,+ images: new Map([[url, image]]),+ },+ ],+ });+ expect(layout.images).toHaveLength(3);+ const bubble = layout.bubbles[0]!;+ const text = bubble.textBlocks;+ expect(text.map((block) => block.lines.join(""))).toEqual([+ "before",+ "middle",+ "after",+ ]);+ expect(layout.images[0]!.y + layout.images[0]!.height).toBeLessThan(+ bubble.y,+ );+ expect(text[0]!.y).toBeLessThan(layout.images[1]!.y);+ expect(layout.images[1]!.y + layout.images[1]!.height).toBeLessThan(+ text[1]!.y,+ );+ expect(text[1]!.y).toBeLessThan(layout.images[2]!.y);+ expect(layout.images[2]!.y + layout.images[2]!.height).toBeLessThan(+ text[2]!.y,+ );+ expect(layout.images[2]!.y + layout.images[2]!.height).toBeLessThan(+ bubble.y + bubble.height,+ );+ },+ );++ it("traverses structured text, table cells, and secondary body without parsing code or chip labels as images", () => {+ const url = "cindy-media://same";+ const image = {+ uri: "data:image/png;base64,aGVsbG8=",+ width: 40,+ height: 20,+ };+ const layout = buildConversationShareSvgLayout({+ allShareableIds: ["m"],+ colors,+ width: 390,+ messages: [+ {+ clientId: "m",+ kind: "assistant",+ body: "ignored",+ images: new Map([[url, image]]),+ bodyParts: [+ { kind: "quote", label: `` },+ {+ kind: "text",+ text: `> quote \n\n- item \n\n| header  | next |\n| --- | --- |\n|  | last |\n\n\`\`\`md\n\n\`\`\``,+ },+ ],+ secondaryBody: `secondary  end`,+ },+ ],+ });+ expect(layout.images).toHaveLength(5);+ expect(layout.images.map((image) => image.y)).toEqual(+ layout.images.map((image) => image.y).sort((a, b) => a - b),+ );+ const text = layout.bubbles+ .flatMap((bubble) => bubble.textBlocks.flatMap((block) => block.lines))+ .join("\n");+ expect(text).toContain("![chip]");+ expect(text).toContain("![code]");+ expect(text).not.toContain("quote image");+ expect(text).toContain("secondary");+ });+it("wraps Chinese and Latin text within the available width", () => {expect(wrapSvgText("这是很长的一段中文消息", 60, 15).length,@@ -95,9 +361,9 @@ describe("ConversationShareSvg", () => {],width: 390,});- const renderedText =- layout.bubbles[0]?.textBlocks.flatMap((block) => block.lines).join(" ") ??- "";+ const renderedText = layout.bubbles+ .flatMap((bubble) => bubble.textBlocks.flatMap((block) => block.lines))+ .join(" ");expect(renderedText).not.toContain("sk-12345678");expect(renderedText).toContain("[REDACTED]");});@@ -199,9 +465,9 @@ describe("ConversationShareSvg", () => {});it("waits for both footer assets before allowing export", async () => {- const gate = createConversationShareFooterAssetGate();+ const gate = createConversationShareAssetGate(["character", "logo"]);let ready = false;- const wait = gate.waitUntilReady().then(() => {+ const wait = gate.waitUntilSettled().then(() => {ready = true;});diff --git a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.tsindex 3af2fed142..307813ecca 100644--- a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts+++ b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts@@ -7,6 +7,7 @@ import {type ConversationShareWebViewColors,} from '@/session/conversationShareWebViewHtml';import { i18n } from '@/i18n';+import { buildConversationShareSvgLayout } from '@/session/conversationShareSvgLayout';const colors: ConversationShareWebViewColors = {background: '#ffffff',@@ -50,6 +51,64 @@ function buildRichConversationHtml(): string {}describe('buildConversationShareHtml 富内容导出', () => {+ 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' }],+ });+ expect(html).not.toContain('private-');+ expect(html).toContain('[REDACTED]');+ });++ 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 picture = ``;+ const options = {+ 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} |` }],+ 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(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(url);+ expect(JSON.stringify(svg)).toContain('[REDACTED]');+ },+ );++ it.each(['body', 'bodyParts', 'secondaryBody'] as const)(+ '%s 中图片语法受到脱敏影响时由 SVG 保留图片或替代文字',+ (field) => {+ 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 }]] : []),+ };+ 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(svg.images).toHaveLength(prepared ? 1 : 0);+ expect(JSON.stringify(svg)).not.toContain('private');+ expect(JSON.stringify(svg)).not.toContain(url);+ }+ },+ );+it('只按选中内容嵌入对应的富内容运行时', () => {const plainHtml = buildConversationShareHtml({allShareableIds: ['plain'],@@ -146,7 +205,8 @@ describe('buildConversationShareHtml 富内容导出', () => {}],});- expect(html).toContain(`alt="${i18n.t('message.renderer.imageFallbackTitle')}"`);+ 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', () => {@@ -202,7 +262,7 @@ describe('buildConversationShareHtml 富内容导出', () => {'if (!nativeConversationShareAvailable || !shareSelectionActive) return undefined;',);expect(sessionSource).toContain(- '!nativeConversationShareAvailable\n || !shareSelectionActive',+ 'const messages = await shareImages.prepare();',);expect(sessionSource).toContain('nativeConversationShareAvailable\n && shareCharacterSrc',@@ -245,9 +305,9 @@ describe('buildConversationShareHtml 富内容导出', () => {expect(svgSource).toContain('const SHARE_LOGO_HEIGHT = 18;');expect(svgSource).toContain('const SHARE_LOCKUP_GAP = 6;');expect(svgSource).toContain('rx={6}');- expect(svgSource).toContain('footerAssetGate.waitUntilReady()');- expect(svgSource).toContain('footerAssetGate.markReady("character")');- expect(svgSource).toContain('footerAssetGate.markReady("logo")');+ 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;');@@ -381,7 +441,7 @@ describe('buildConversationShareHtml 富内容导出', () => {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('share-attachment-image');+ 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');diff --git a/apps/mobile/src/__tests__/useConversationShareImages.test.ts b/apps/mobile/src/__tests__/useConversationShareImages.test.tsnew file mode 100644index 0000000000..60c03ee476--- /dev/null+++ b/apps/mobile/src/__tests__/useConversationShareImages.test.ts@@ -0,0 +1,469 @@+// @vitest-environment jsdom+import { act, createElement, StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useConversationShareImages } from "@/session/useConversationShareImages";+import type { ConversationShareMessage } from "@/session/conversationShareWebViewHtml";+import type { ResolveRemoteMediaFn } from "@/session/remoteMedia";+import { downloadRemoteMediaAsDataUri } from "@/session/remoteMediaDiskCacheExpo";+import { createRemoteMediaResolveQueue } from "@/session/remoteMediaResolveQueue";++vi.mock("react-native", () => ({+ Image: { getSize: vi.fn(async () => ({ width: 40, height: 20 })) },+}));+const thumbs = vi.hoisted(() => ({+ entries: new Map<string, string>(),+ reads: vi.fn(async () => "aGVsbG8="),+}));+vi.mock("expo-file-system", () => ({+ File: class {+ exists = true;+ size = 5;+ base64 = thumbs.reads;+ },+}));+vi.mock("@/session/sentAttachmentThumbStore", () => ({+ ensureSentAttachmentThumbsHydrated: vi.fn(async () => undefined),+ getSentAttachmentThumbUri: (uri: string) => thumbs.entries.get(uri) ?? null,+}));+vi.mock("@/session/remoteMediaDiskCacheExpo", () => ({+ downloadRemoteMediaAsDataUri: vi.fn(),+}));++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const container = document.createElement("div");+let root = createRoot(container);+let current!: ReturnType<typeof useConversationShareImages>;+let ready!: Promise<readonly ConversationShareMessage[]>;+async function startShare() {+ await act(async () => {+ ready = current.prepare();+ });+}+function Probe({+ messages,+ resolve,+ sessionId = "session",+}: {+ messages: ConversationShareMessage[];+ resolve: ResolveRemoteMediaFn;+ sessionId?: string;+}) {+ current = useConversationShareImages(messages, resolve, {+ sessionId,+ });+ return null;+}+const source: ConversationShareMessage = {+ clientId: "user",+ kind: "user",+ body: "",+ attachments: [{ kind: "image", name: "paste", uri: "cindy-media://paste" }],+};+const media = {+ url: "data:image/png;base64,aGVsbG8=",+ mimeType: "image/png",+ size: 5,+ ossKey: "",+ expiresAt: "",+ previewable: true,+};+afterEach(async () => {+ await act(async () => root.unmount());+ vi.useRealTimers();+ thumbs.entries.clear();+ thumbs.reads.mockClear();+ vi.mocked(downloadRemoteMediaAsDataUri).mockReset();+ root = createRoot(container);+});++describe("share image readiness", () => {+ it.each(["timeout", "cancel", "selection", "session", "unmount"])(+ "removes queued media work on %s before a free slot can start it",+ async (event) => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ let finish!: (value: typeof media) => void;+ const fetch = vi.fn(+ () =>+ new Promise<typeof media>((done) => {+ finish = done;+ }),+ );+ const queue = createRemoteMediaResolveQueue(+ { resolve: fetch },+ { maxConcurrent: 1 },+ );+ const busy = queue.request({ kind: "image", url: "cindy-media://busy" });+ const resolve: ResolveRemoteMediaFn = (request, opts) =>+ queue.request(request, opts);+ await act(async () =>+ root.render(createElement(Probe, { messages: [source], resolve })),+ );+ await startShare();+ expect(queue.stats()).toEqual({ inFlight: 1, queued: 1 });+ await act(async () => {+ if (event === "timeout") await vi.advanceTimersByTimeAsync(20_000);+ if (event === "cancel") current.cancel();+ if (event === "selection")+ root.render(createElement(Probe, { messages: [], resolve }));+ if (event === "session")+ root.render(+ createElement(Probe, {+ messages: [source],+ resolve,+ sessionId: "next",+ }),+ );+ if (event === "unmount") root.render(null);+ });+ expect(queue.stats().queued).toBe(0);+ expect((await ready).length).toBe(event === "timeout" ? 1 : 0);+ await act(async () => {+ finish(media);+ await busy;+ });+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(queue.stats()).toEqual({ inFlight: 0, queued: 0 });+ },+ );++ it("cancels only the share waiter while a shared queued consumer still completes", async () => {+ let finish!: (value: typeof media) => void;+ const fetch = vi.fn(async ({ url }: { url: string }) =>+ url.endsWith("busy")+ ? new Promise<typeof media>((done) => {+ finish = done;+ })+ : media,+ );+ const queue = createRemoteMediaResolveQueue(+ { resolve: fetch },+ { maxConcurrent: 1 },+ );+ const busy = queue.request({ kind: "image", url: "cindy-media://busy" });+ const resolve: ResolveRemoteMediaFn = (request, opts) =>+ queue.request(request, opts);+ await act(async () =>+ root.render(createElement(Probe, { messages: [source], resolve })),+ );+ await startShare();+ const other = queue.request({+ kind: "image",+ url: "cindy-media://paste",+ thumbnail: true,+ });+ await act(async () => current.cancel());+ expect(await ready).toEqual([]);+ expect(queue.stats().queued).toBe(1);+ await act(async () => {+ finish(media);+ await busy;+ await other;+ });+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it("keeps direct HTTP images as placeholders without starting a download", async () => {+ const resolve = vi.fn<ResolveRemoteMediaFn>();+ const url = "https://example.com/unbounded.png";+ await act(async () =>+ root.render(+ createElement(Probe, {+ messages: [+ {+ ...source,+ body: ``,+ attachments: [{ kind: "image", name: "remote", uri: url }],+ },+ ],+ resolve,+ }),+ ),+ );+ await startShare();+ expect((await ready)[0]?.images?.size).toBe(0);+ expect(resolve).not.toHaveBeenCalled();+ expect(downloadRemoteMediaAsDataUri).not.toHaveBeenCalled();+ });++ it.each([5, 0, -1, NaN, Infinity, 8 * 1024 * 1024 + 1])(+ "downloads controlled images only with a valid known size (%s)",+ async (size) => {+ const url = "https://example.com/controlled.png";+ const resolve = vi.fn<ResolveRemoteMediaFn>(async () => ({+ ...media,+ size,+ url,+ }));+ vi.mocked(downloadRemoteMediaAsDataUri).mockResolvedValue(media.url);+ await act(async () =>+ root.render(createElement(Probe, { messages: [source], resolve })),+ );+ await startShare();+ expect((await ready)[0]?.images?.size).toBe(size === 5 ? 1 : 0);+ expect(downloadRemoteMediaAsDataUri).toHaveBeenCalledTimes(+ size === 5 ? 1 : 0,+ );+ },+ );++ it.each([+ "cindy-oss-attach://upload/paste",+ "xdt-oss-attach://upload/paste",+ "cindy-media://blobs/paste",+ "xdt-image://paste",+ ])(+ "reads the latest %s thumbnail on each share without background preparation",+ async (uri) => {+ const resolve = vi.fn<ResolveRemoteMediaFn>(async () => {+ throw new Error("desktop offline");+ });+ const messages: ConversationShareMessage[] = [+ {+ ...source,+ attachments: [+ { kind: "image", name: "paste", uri },+ {+ kind: "image",+ name: "untrusted",+ uri: "file:///private/image.png",+ },+ ],+ },+ ];+ const render = () => createElement(Probe, { messages, resolve });+ await act(async () => root.render(render()));+ expect(resolve).not.toHaveBeenCalled();+ await startShare();+ const oldReady = ready;+ expect((await oldReady)[0]?.images?.size).toBe(0);+ expect(thumbs.reads).not.toHaveBeenCalled();+ resolve.mockClear();+ thumbs.entries.set(uri, "file:///app/sent-attachment-thumbs/paste.png");+ await act(async () => root.render(render()));+ await startShare();+ expect(ready).not.toBe(oldReady);+ const result = await ready;+ expect(result[0]?.images?.get(uri)?.uri).toBe(media.url);+ expect(result[0]?.images?.size).toBe(1);+ expect(result[0]?.attachments?.[0]?.uri).toBe(uri);+ expect(thumbs.reads).toHaveBeenCalledTimes(1);+ expect(resolve).not.toHaveBeenCalled();+ },+ );++ it("falls back to the controlled resolver if a registered thumbnail cannot be read", async () => {+ thumbs.entries.set(+ "cindy-media://paste",+ "file:///app/sent-attachment-thumbs/paste.png",+ );+ thumbs.reads.mockRejectedValueOnce(new Error("file removed"));+ const resolve = vi.fn<ResolveRemoteMediaFn>(async () => media);+ await act(async () =>+ root.render(createElement(Probe, { messages: [source], resolve })),+ );+ await startShare();+ expect((await ready)[0]?.images?.get("cindy-media://paste")?.uri).toBe(+ media.url,+ );+ expect(resolve).toHaveBeenCalledTimes(1);+ });++ it.each([false, true])(+ "keeps later local images across messages when a remote source stalls (reverse=%s)",+ async (reverse) => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ thumbs.entries.set(+ "cindy-media://remaining",+ "file:///app/remaining.png",+ );+ thumbs.entries.set("cindy-media://next", "file:///app/next.png");+ let finish!: (value: typeof media) => void;+ const resolve = vi.fn<ResolveRemoteMediaFn>(async ({ url }) => {+ if (url === "cindy-media://paste") return media;+ return new Promise((done) => {+ finish = done;+ });+ });+ await act(async () =>+ root.render(+ createElement(Probe, {+ messages: [+ {+ ...source,+ body: "keep this text",+ attachments: (reverse+ ? [+ {+ kind: "image",+ name: "slow image",+ uri: "cindy-media://slow",+ },+ {+ kind: "image",+ name: "remaining image",+ uri: "cindy-media://remaining",+ },+ ...source.attachments!,+ ]+ : [+ ...source.attachments!,+ {+ kind: "image" as const,+ name: "slow image",+ uri: "cindy-media://slow",+ },+ {+ kind: "image" as const,+ name: "remaining image",+ uri: "cindy-media://remaining",+ },+ ]) as ConversationShareMessage["attachments"],+ },+ {+ clientId: "next",+ kind: "assistant",+ body: "keep the next message",+ attachments: [+ { kind: "image", name: "next", uri: "cindy-media://next" },+ ],+ },+ ],+ resolve,+ }),+ ),+ );+ await startShare();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(20_000);+ });+ const result = await ready;+ expect(result.map((message) => message.body)).toEqual([+ "keep this text",+ "keep the next message",+ ]);+ expect(result[0]?.images?.size).toBe(2);+ expect(result[1]?.images?.size).toBe(1);+ expect(result[0]?.images?.get("cindy-media://paste")?.uri).toBe(+ media.url,+ );+ expect(+ result[0]?.attachments?.find(+ (attachment) => attachment.uri === "cindy-media://slow",+ )?.name,+ ).toBe("slow image");+ expect(resolve).toHaveBeenCalledTimes(2);+ await act(async () =>+ finish({ ...media, url: "https://example.com/late.png" }),+ );+ expect(current.messages).toBe(result);+ expect(result[0]?.images?.size).toBe(2);+ expect(downloadRemoteMediaAsDataUri).not.toHaveBeenCalled();+ },+ );++ it("survives StrictMode and unrelated rerenders while a remote image loads", async () => {+ let finish!: (value: typeof media) => void;+ const pending = new Promise<typeof media>((done) => {+ finish = done;+ });+ const resolve = vi.fn(() => pending);+ const render = () =>+ createElement(+ StrictMode,+ null,+ createElement(Probe, {+ messages: [+ {+ ...source,+ attachments: source.attachments?.map((a) => ({ ...a })),+ },+ ],+ resolve,+ }),+ );+ await act(async () => root.render(render()));+ await startShare();+ await act(async () => root.render(render()));+ await act(async () => finish(media));+ expect((await ready)[0]?.images?.get("cindy-media://paste")?.uri).toBe(+ media.url,+ );+ expect(current.messages).toHaveLength(1);+ });++ it("cancels the previous selection and ignores its late image result", async () => {+ let finish!: (value: typeof media) => void;+ const resolve = vi.fn(+ () =>+ new Promise<typeof media>((done) => {+ finish = done;+ }),+ );+ await act(async () =>+ root.render(createElement(Probe, { messages: [source], resolve })),+ );+ await startShare();+ const oldReady = ready;+ await act(async () =>+ root.render(+ createElement(Probe, {+ messages: [{ clientId: "next", kind: "assistant", body: "next" }],+ resolve,+ }),+ ),+ );+ expect(await oldReady).toEqual([]);+ await act(async () =>+ finish({ ...media, url: "https://example.com/cancelled.png" }),+ );+ expect(downloadRemoteMediaAsDataUri).not.toHaveBeenCalled();+ await startShare();+ expect((await ready).map((message) => message.clientId)).toEqual(["next"]);+ expect(current.messages[0]?.images?.size).toBe(0);+ });++ it("retains the clicked snapshot through streaming and thumbnail updates", async () => {+ let finish!: (value: typeof media) => void;+ const resolve = vi.fn<ResolveRemoteMediaFn>(+ () =>+ new Promise((done) => {+ finish = done;+ }),+ );+ await act(async () =>+ root.render(+ createElement(Probe, {+ messages: [{ ...source, body: "clicked text" }],+ resolve,+ }),+ ),+ );+ await startShare();+ const clickedReady = ready;+ thumbs.entries.set(+ "cindy-media://paste",+ "file:///app/sent-attachment-thumbs/new.png",+ );+ await act(async () =>+ root.render(+ createElement(Probe, {+ messages: [{ ...source, body: "later streamed text" }],+ resolve,+ }),+ ),+ );+ await act(async () => finish(media));+ const snapshot = await clickedReady;+ expect(snapshot[0]?.body).toBe("clicked text");+ expect(snapshot[0]?.images?.get("cindy-media://paste")?.uri).toBe(+ media.url,+ );+ expect(current.messages).toBe(snapshot);+ expect(resolve).toHaveBeenCalledTimes(1);+ expect(thumbs.reads).not.toHaveBeenCalled();+ await startShare();+ expect((await ready)[0]?.body).toBe("later streamed text");+ expect(thumbs.reads).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/mobile/src/session/ConversationShareSvg.tsx b/apps/mobile/src/session/ConversationShareSvg.tsxindex aaabf02291..28da65f214 100644--- a/apps/mobile/src/session/ConversationShareSvg.tsx+++ b/apps/mobile/src/session/ConversationShareSvg.tsx@@ -1,5 +1,12 @@-import { forwardRef, useImperativeHandle, useMemo, useRef } from "react";-import { Image as NativeImage, StyleSheet, View } from "react-native";+import {+ forwardRef,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from "react";+import { Image as NativeImage, Platform, StyleSheet, View } from "react-native";import Svg, {ClipPath,Defs,@@ -13,7 +20,7 @@ import type {ConversationShareMessage,ConversationShareWebViewColors,} from "@/session/conversationShareWebViewHtml";-import { createConversationShareFooterAssetGate } from "@/session/conversationShareAssetGate";+import { createConversationShareAssetGate } from "@/session/conversationShareAssetGate";import {buildConversationShareSvgLayout,conversationShareSvgRenderSize,@@ -35,6 +42,8 @@ const SHARE_CHARACTER_SIZE = 22;const SHARE_LOGO_HEIGHT = 18;const SHARE_LOCKUP_GAP = 6;const SHARE_EXPORT_TIMEOUT_MS = 20_000;+// Leave time within the existing export deadline for fallback layout + capture.+const SHARE_DECODE_TIMEOUT_MS = 15_000;// Export-card geometry: this is a 1px bubble border in the SVG coordinate// system, not a Lucide icon stroke (whose thinnest token is intentionally 1.75).const SHARE_BUBBLE_STROKE_WIDTH = 1;@@ -52,25 +61,78 @@ export const ConversationShareSvg = forwardRef<ref,) {const svgRef = useRef<Svg | null>(null);+ const [imageKeysByUri] = useState(() => {+ const original = buildConversationShareSvgLayout({+ allShareableIds,+ colors,+ messages,+ width,+ });+ const keys = new Map<string, string[]>();+ original.images.forEach((image, index) => {+ const occurrences = keys.get(image.uri) ?? [];+ occurrences.push(`image-${index}`);+ keys.set(image.uri, occurrences);+ });+ return keys;+ });+ const [assetGate] = useState(() =>+ createConversationShareAssetGate([+ "character",+ "logo",+ ...Array.from(imageKeysByUri.values()).flat(),+ ]),+ );+ const [readyAssets, setReadyAssets] = useState<ReadonlySet<string> | null>(+ null,+ );+ const captureMessages = useMemo(+ () =>+ readyAssets+ ? messages.map((message) => ({+ ...message,+ images: new Map(+ Array.from(message.images ?? []).filter(([, image]) =>+ imageKeysByUri+ .get(image.uri)+ ?.every((key) => readyAssets.has(key)),+ ),+ ),+ }))+ : messages,+ [imageKeysByUri, messages, readyAssets],+ );const layout = useMemo(() =>buildConversationShareSvgLayout({allShareableIds,colors,- messages,+ messages: captureMessages,width,}),- [allShareableIds, colors, messages, width],+ [allShareableIds, colors, captureMessages, width],);+ // Removing a failed URI must not remount already decoded SVG occurrences.+ const keyedImages = useMemo(() => {+ const occurrences = new Map<string, number>();+ return layout.images.map((image) => {+ const occurrence = occurrences.get(image.uri) ?? 0;+ occurrences.set(image.uri, occurrence + 1);+ return { ...image, key: imageKeysByUri.get(image.uri)![occurrence]! };+ });+ }, [imageKeysByUri, layout.images]);const renderSize = useMemo(() => conversationShareSvgRenderSize(layout),[layout],);const logoAsset = colors.dark ? shareLogoDarkAsset : shareLogoLightAsset;- const footerAssetGate = useMemo(- () => createConversationShareFooterAssetGate(),- [logoAsset],- );+ // The screen keys this component by prepared snapshot + theme.+ const exportJob = useRef<{+ promise: Promise<string>;+ cancel(): void;+ capture(sourceTooLarge: boolean): void;+ } | null>(null);+ useEffect(() => () => exportJob.current?.cancel(), []);const logoSource = NativeImage.resolveAssetSource(logoAsset);const logoWidth = (SHARE_LOGO_HEIGHT * logoSource.width) / logoSource.height;const lockupWidth = SHARE_CHARACTER_SIZE + SHARE_LOCKUP_GAP + logoWidth;@@ -80,48 +142,80 @@ export const ConversationShareSvg = forwardRef<ref,() => ({exportPng() {+ if (exportJob.current) return exportJob.current.promise;if (renderSize.sourceTooLarge) {return Promise.reject(new Error("conversation share content is too large"),);}- return new Promise<string>((resolve, reject) => {- let settled = false;- const fail = (error: Error) => {- if (settled) return;- settled = true;+ let capture = (_sourceTooLarge: boolean) => {};+ let cancel = () => {};+ const promise = new Promise<string>((resolve, reject) => {+ let phase: "decoding" | "layout" | "capturing" | "settled" =+ "decoding";+ const finish = (error?: Error, base64?: string) => {+ if (phase === "settled") return;+ phase = "settled";clearTimeout(timer);- reject(error);+ clearTimeout(decodeTimer);+ assetGate.finish();+ if (error) reject(error);+ else resolve(base64!);};const timer = setTimeout(() => {- fail(new Error("conversation share svg export timed out"));+ finish(new Error("conversation share svg export timed out"));}, SHARE_EXPORT_TIMEOUT_MS);- void footerAssetGate.waitUntilReady().then(() => {- if (settled) return;+ const prepareCapture = () => {+ if (phase !== "decoding") return;+ phase = "layout";+ clearTimeout(decodeTimer);+ const ready = assetGate.finish();+ if (!ready.has("character") || !ready.has("logo")) {+ finish(new Error("conversation share footer is unavailable"));+ return;+ }+ setReadyAssets(ready);+ };+ const decodeTimer = setTimeout(+ prepareCapture,+ SHARE_DECODE_TIMEOUT_MS,+ );+ void assetGate.waitUntilSettled().then(prepareCapture);+ cancel = () =>+ finish(new Error("conversation share svg export cancelled"));+ capture = (sourceTooLarge) => {+ if (phase !== "layout") return;+ phase = "capturing";+ if (sourceTooLarge) {+ finish(new Error("conversation share content is too large"));+ return;+ }const svg = svgRef.current;if (!svg) {- fail(new Error("conversation share svg renderer is unavailable"));+ finish(+ new Error("conversation share svg renderer is unavailable"),+ );return;}try {svg.toDataURL((base64) => {- if (settled) return;+ if (phase === "settled") return;if (!base64) {- fail(new Error("conversation share svg export was empty"));+ finish(new Error("conversation share svg export was empty"));return;}- settled = true;- clearTimeout(timer);- resolve(base64);+ finish(undefined, base64);});} catch (error) {- fail(error instanceof Error ? error : new Error(String(error)));+ finish(error instanceof Error ? error : new Error(String(error)));}- });+ };});+ exportJob.current = { promise, cancel, capture };+ return promise;},}),- [footerAssetGate, renderSize.sourceTooLarge],+ [assetGate, renderSize.sourceTooLarge],);return (@@ -134,6 +228,52 @@ export const ConversationShareSvg = forwardRef<{ height: renderSize.height, width: renderSize.width },]}>+ {Platform.OS === "android" && !renderSize.sourceTooLarge+ ? [+ { source: shareCharacterAsset, keys: ["character"] },+ { source: logoAsset, keys: ["logo"] },+ ...Array.from(imageKeysByUri, ([uri, keys]) => ({+ source: { uri },+ keys,+ })),+ ].map(({ source, keys }) => (+ <NativeImage+ key={keys[0]}+ source={source}+ resizeMethod="none"+ fadeDuration={0}+ style={styles.decodeProbe}+ onLoad={() => {+ // Bundled footer bitmaps are held by this mounted view.+ // Release Android may resolve them to resource names, which the+ // URI-only queryCache API cannot look up as native res:/ IDs.+ if (keys[0] === "character" || keys[0] === "logo") {+ keys.forEach(assetGate.markReady);+ return;+ }+ // Android SVG cache hits do not emit onLoad. This mounted Image+ // holds the same unresized Fresco bitmap; encoded/disk cache alone+ // is insufficient, including when Fresco refuses a large bitmap.+ const uri = NativeImage.resolveAssetSource(source).uri;+ const cached = NativeImage.queryCache?.([uri]);+ if (!cached) {+ keys.forEach(assetGate.markFailed);+ return;+ }+ void cached.then(+ (cache) => {+ const mark = cache[uri]?.includes("memory")+ ? assetGate.markReady+ : assetGate.markFailed;+ keys.forEach(mark);+ },+ () => keys.forEach(assetGate.markFailed),+ );+ }}+ onError={() => keys.forEach(assetGate.markFailed)}+ />+ ))+ : null}<Svgheight={renderSize.height}ref={svgRef}@@ -150,6 +290,20 @@ export const ConversationShareSvg = forwardRef<{layout.bubbles.map((bubble, bubbleIndex) => (<SvgBubbleView bubble={bubble} key={`bubble-${bubbleIndex}`} />))}+ {keyedImages.map((image) => (+ <SvgImage+ key={image.key}+ href={{ uri: image.uri }}+ x={image.x}+ y={image.y}+ width={image.width}+ height={image.height}+ preserveAspectRatio="xMidYMid meet"+ onLoad={() => {+ if (Platform.OS !== "android") assetGate.markReady(image.key);+ }}+ />+ ))}{layout.gaps.map((gap, gapIndex) => (<SvgTextfill={gap.color}@@ -180,7 +334,9 @@ export const ConversationShareSvg = forwardRef<height={SHARE_CHARACTER_SIZE}href={shareCharacterAsset}key={`conversation-share-character-${colors.dark ? "dark" : "light"}`}- onLoad={() => footerAssetGate.markReady("character")}+ onLoad={() => {+ if (Platform.OS !== "android") assetGate.markReady("character");+ }}preserveAspectRatio="xMidYMid slice"width={SHARE_CHARACTER_SIZE}x={lockupX}@@ -190,7 +346,9 @@ export const ConversationShareSvg = forwardRef<height={SHARE_LOGO_HEIGHT}href={logoAsset}key={`conversation-share-logo-${colors.dark ? "dark" : "light"}`}- onLoad={() => footerAssetGate.markReady("logo")}+ onLoad={() => {+ if (Platform.OS !== "android") assetGate.markReady("logo");+ }}preserveAspectRatio="xMinYMid meet"width={logoWidth}x={lockupX + SHARE_CHARACTER_SIZE + SHARE_LOCKUP_GAP}@@ -201,6 +359,15 @@ export const ConversationShareSvg = forwardRef<</>) : null}</Svg>+ {readyAssets ? (+ // A newly mounted native layout event is the commit barrier: capture+ // must see the fallback SVG, even when its outer size did not change.+ <View+ collapsable={false}+ onLayout={() => exportJob.current?.capture(renderSize.sourceTooLarge)}+ style={styles.decodeProbe}+ />+ ) : null}</View>);});@@ -245,6 +412,7 @@ function SvgBubbleView({ bubble }: { bubble: ConversationShareSvgBubble }) {}const styles = StyleSheet.create({+ decodeProbe: { position: "absolute", width: 1, height: 1 },hidden: {left: 0,opacity: 0,diff --git a/apps/mobile/src/session/conversationShareAssetGate.ts b/apps/mobile/src/session/conversationShareAssetGate.tsindex e872651681..b3d822aff2 100644--- a/apps/mobile/src/session/conversationShareAssetGate.ts+++ b/apps/mobile/src/session/conversationShareAssetGate.ts@@ -1,28 +1,39 @@-export type ConversationShareFooterAsset = "character" | "logo";--export interface ConversationShareFooterAssetGate {- markReady(asset: ConversationShareFooterAsset): void;- waitUntilReady(): Promise<void>;+export interface ConversationShareAssetGate {+ markReady(asset: string): void;+ markFailed(asset: string): void;+ waitUntilSettled(): Promise<void>;+ finish(): ReadonlySet<string>;}/**- * The SVG footer contains two independently decoded bundled images. Keep the- * readiness latch separate from React so export can wait for both assets and- * the ordering/duplicate-load behavior stays unit-testable.+ * One prepared export owns this latch. The first result for each asset wins;+ * finish freezes the successful subset, including when the decode deadline+ * expires. Late native callbacks cannot change the capture layout.*/-export function createConversationShareFooterAssetGate(): ConversationShareFooterAssetGate {- const pending = new Set<ConversationShareFooterAsset>(["character", "logo"]);- let resolveReady = () => {};- const ready = new Promise<void>((resolve) => {- resolveReady = resolve;+export function createConversationShareAssetGate(+ keys: readonly string[],+): ConversationShareAssetGate {+ const pending = new Set(keys);+ const ready = new Set<string>();+ let finished = false;+ let resolveSettled = () => {};+ const settled = new Promise<void>((resolve) => {+ resolveSettled = resolve;});+ const mark = (asset: string, success: boolean) => {+ if (finished || !pending.delete(asset)) return;+ if (success) ready.add(asset);+ if (pending.size === 0) resolveSettled();+ };+ if (pending.size === 0) resolveSettled();return {- markReady(asset) {- pending.delete(asset);- if (pending.size === 0) resolveReady();- },- waitUntilReady() {+ markReady: (asset) => mark(asset, true),+ markFailed: (asset) => mark(asset, false),+ waitUntilSettled: () => settled,+ finish() {+ finished = true;+ resolveSettled();return ready;},};diff --git a/apps/mobile/src/session/conversationShareImages.ts b/apps/mobile/src/session/conversationShareImages.tsnew file mode 100644index 0000000000..795bacea6e--- /dev/null+++ b/apps/mobile/src/session/conversationShareImages.ts@@ -0,0 +1,130 @@+import {+ collectMobileMarkdownImages,+ mobileMarkdownImageUrlForWorkdir,+} from "@/session/messageMarkdown";+import type {+ ConversationShareImage,+ ConversationShareMessage,+} from "@/session/conversationShareWebViewHtml";++export interface ConversationShareImageContext {+ workdir?: string;+ remoteHostId?: string;+ sessionId?: string;+}++// Compressed bytes do not bound native bitmap memory. Charge every rendered+// occurrence before either HTML or SVG can mount it (RGBA: 16 / 32 MB).+const MAX_IMAGE_PIXELS = 4_000_000;+const MAX_EXPORT_IMAGE_PIXELS = 8_000_000;+const IMAGE_PREPARATION_CONCURRENCY = 3;++/** Prepare selected, visible content only; source URLs never enter the export document. */+export async function prepareConversationShareImages(+ messages: readonly ConversationShareMessage[],+ load: (url: string) => Promise<ConversationShareImage | null>,+ context: ConversationShareImageContext = {},+ isActive: () => boolean = () => true,+): Promise<ConversationShareMessage[]> {+ const result: ConversationShareMessage[] = [];+ // Group references before starting IO so a stalled source cannot prevent+ // independent sources in later messages from reaching a free worker.+ const requests = new Map<+ string,+ Array<{+ source: string;+ occurrences: number;+ images: Map<string, ConversationShareImage>;+ }>+ >();+ let remainingCharacters = 32 * 1024 * 1024;+ let remainingPixels = MAX_EXPORT_IMAGE_PIXELS;+ for (const message of messages) {+ if (!isActive()) return [];+ const sources = new Map<string, { url: string; occurrences: number }>();+ const addSource = (source: string, url: string) => {+ sources.set(source, {+ url,+ occurrences: (sources.get(source)?.occurrences ?? 0) + 1,+ });+ };+ for (const attachment of message.attachments ?? []) {+ if (attachment.kind === "image" && attachment.uri) {+ addSource(attachment.uri, attachment.uri);+ }+ }+ const texts = message.bodyParts+ ? message.bodyParts.flatMap((part) =>+ part.kind === "text" ? [part.text] : [],+ )+ : [message.body];+ if (message.secondaryBody) texts.push(message.secondaryBody);+ for (const text of texts) {+ for (const image of collectMobileMarkdownImages(text)) {+ const url = mobileMarkdownImageUrlForWorkdir(+ image.url,+ context.workdir,+ message.clientId,+ context.remoteHostId,+ context.sessionId,+ );+ if (url) addSource(image.url, url);+ }+ }+ const images = new Map<string, ConversationShareImage>();+ for (const [source, { url, occurrences }] of sources) {+ const references = requests.get(url) ?? [];+ references.push({ source, occurrences, images });+ requests.set(url, references);+ }+ result.push({ ...message, images });+ }+ const pending = requests.entries();+ const worker = async () => {+ while (isActive() && remainingCharacters > 0 && remainingPixels > 0) {+ const next = pending.next();+ if (next.done) return;+ const [url, references] = next.value;+ let image: ConversationShareImage | null;+ try {+ image = await load(url);+ } catch {+ continue;+ }+ if (!isActive()) return;+ const pixels = image+ ? Math.ceil(image.width) * Math.ceil(image.height)+ : 0;+ if (+ image &&+ image.uri.startsWith("data:image/") &&+ Number.isFinite(image.width) &&+ Number.isFinite(image.height) &&+ image.width > 0 &&+ image.height > 0 &&+ pixels <= MAX_IMAGE_PIXELS+ ) {+ // Admission is synchronous: completed sources share one budget owner.+ // No unbounded completed-image buffer; rejected candidates are released.+ // Readiness decides admission, while render order stays in the messages.+ for (const { source, occurrences, images } of references) {+ if (+ pixels * occurrences <= remainingPixels &&+ image.uri.length * occurrences <= remainingCharacters+ ) {+ images.set(source, image);+ remainingCharacters -= image.uri.length * occurrences;+ remainingPixels -= pixels * occurrences;+ }+ }+ }+ }+ };+ await Promise.all(+ Array.from(+ { length: Math.min(IMAGE_PREPARATION_CONCURRENCY, requests.size) },+ worker,+ ),+ );+ return isActive() ? result : [];+}diff --git a/apps/mobile/src/session/conversationShareProjection.ts b/apps/mobile/src/session/conversationShareProjection.tsindex 165274f4fd..6c92851a3a 100644--- a/apps/mobile/src/session/conversationShareProjection.ts+++ b/apps/mobile/src/session/conversationShareProjection.ts@@ -141,8 +141,9 @@ function projectAttachments(): ConversationShareAttachment[] {const { imageAttachments, fileAttachments } =partitionMessageAttachments(attachments);- return [...imageAttachments, ...fileAttachments].map(({ kind, name }) => ({+ return [...imageAttachments, ...fileAttachments].map(({ kind, name, uri }) => ({kind,name,+ ...(kind === 'image' && uri ? { uri } : {}),}));}diff --git a/apps/mobile/src/session/conversationShareSvgLayout.ts b/apps/mobile/src/session/conversationShareSvgLayout.tsindex 85a93f5601..693693f831 100644--- a/apps/mobile/src/session/conversationShareSvgLayout.ts+++ b/apps/mobile/src/session/conversationShareSvgLayout.ts@@ -8,6 +8,7 @@ import {} from "@/session/messageMarkdown";import type {ConversationShareMessage,+ ConversationShareImage,ConversationShareWebViewColors,} from "@/session/conversationShareWebViewHtml";@@ -40,6 +41,13 @@ export interface ConversationShareSvgBubble {}export interface ConversationShareSvgLayout {+ images: Array<{+ uri: string;+ x: number;+ y: number;+ width: number;+ height: number;+ }>;bubbles: ConversationShareSvgBubble[];footerY: number;gaps: Array<{ color: string; y: number }>;@@ -80,6 +88,7 @@ export function buildConversationShareSvgLayout({const canvasWidth = Math.max(280, Math.round(width));const contentWidth = canvasWidth - PADDING * 2;const bubbles: ConversationShareSvgBubble[] = [];+ const images: ConversationShareSvgLayout["images"] = [];const gaps: Array<{ color: string; y: number }> = [];const messageIndex = new Map(allShareableIds.map((id, index) => [id, index]));let previousIndex: number | null = null;@@ -100,42 +109,105 @@ export function buildConversationShareSvgLayout({const bubbleX = user ? canvasWidth - PADDING - bubbleWidth : PADDING;const horizontalPadding = user ? 12 : 0;const textWidth = bubbleWidth - horizontalPadding * 2;- const blocks: Array<{- color: string;- fontSize: number;- lineHeight: number;- text: string;- }> = [];-- if (message.automationOriginLabel) {- blocks.push({- color: colors.textTertiary,- fontSize: META_FONT_SIZE,- lineHeight: META_LINE_HEIGHT,- text: redactSensitiveText(message.automationOriginLabel).trim(),+ const appendMetadata = (text: string, color: string, gap: number) => {+ const lines = wrapSvgText(+ redactSensitiveText(text).trim(),+ bubbleWidth,+ META_FONT_SIZE,+ );+ const height = lines.length * META_LINE_HEIGHT;+ bubbles.push({+ height,+ width: bubbleWidth,+ x: bubbleX,+ y: cursorY,+ textBlocks: [+ {+ color,+ fontSize: META_FONT_SIZE,+ lineHeight: META_LINE_HEIGHT,+ lines,+ x: bubbleX,+ y: cursorY + META_FONT_SIZE,+ },+ ],});+ cursorY += height + gap;+ };+ // One ordered traversal owns attribution, attachments, then body. Failed+ // images replace their own occurrence rather than moving into the bubble.+ if (message.automationOriginLabel) {+ appendMetadata(message.automationOriginLabel, colors.textTertiary, 4);}- for (const attachment of message.attachments ?? []) {- blocks.push({- color: colors.textSecondary,- fontSize: META_FONT_SIZE,- lineHeight: META_LINE_HEIGHT,- text: `${attachment.kind === "image" ? "▧" : "▤"} ${redactSensitiveText(attachment.name).trim()}`,+ const appendImage = (image: ConversationShareImage) => {+ const scale = Math.min(1, bubbleWidth / image.width, 320 / image.height);+ const imageWidth = image.width * scale;+ const imageHeight = image.height * scale;+ images.push({+ uri: image.uri,+ width: imageWidth,+ height: imageHeight,+ x: user ? canvasWidth - PADDING - imageWidth : PADDING,+ y: cursorY,});+ cursorY += imageHeight + MESSAGE_GAP;+ };+ for (const attachment of message.attachments ?? []) {+ const image =+ attachment.kind === "image" && attachment.uri+ ? message.images?.get(attachment.uri)+ : undefined;+ if (image && attachment.uri) {+ appendImage(image);+ } else {+ appendMetadata(+ `${attachment.kind === "image" ? "▧" : "▤"} ${attachment.name}`,+ colors.textSecondary,+ MESSAGE_GAP,+ );+ }}- const body = plainConversationShareText(message);- if (body) {- blocks.push({- color: colors.textPrimary,- fontSize: TEXT_FONT_SIZE,- lineHeight: TEXT_LINE_HEIGHT,- text: body,- });+ const blocks: Array<+ | { image: ConversationShareImage }+ | {+ color: string;+ fontSize: number;+ lineHeight: number;+ text: string;+ }+ > = [];++ for (const part of conversationShareBodyParts(message)) {+ if ("image" in part) blocks.push(part);+ else+ blocks.push({+ color: colors.textPrimary,+ fontSize: TEXT_FONT_SIZE,+ lineHeight: TEXT_LINE_HEIGHT,+ text: part.text,+ });}const textBlocks: ConversationShareSvgTextBlock[] = [];let innerY = user ? 12 : 4;for (const block of blocks) {+ if ("image" in block) {+ const scale = Math.min(+ 1,+ textWidth / block.image.width,+ 320 / block.image.height,+ );+ const height = block.image.height * scale;+ images.push({+ uri: block.image.uri,+ width: block.image.width * scale,+ height,+ x: bubbleX + horizontalPadding,+ y: cursorY + innerY,+ });+ innerY += height + 5;+ continue;+ }const lines = wrapSvgText(block.text, textWidth, block.fontSize);textBlocks.push({color: block.color,@@ -149,22 +221,24 @@ export function buildConversationShareSvgLayout({}if (blocks.length > 0) innerY -= 5;const bubbleHeight = Math.max(user ? 44 : 30, innerY + (user ? 12 : 4));- bubbles.push({- fill: user ? colors.surfaceElevated : undefined,- height: bubbleHeight,- stroke: user ? colors.textSecondary : undefined,- textBlocks,- width: bubbleWidth,- x: bubbleX,- y: cursorY,- });- cursorY += bubbleHeight + MESSAGE_GAP;+ if (blocks.length > 0)+ bubbles.push({+ fill: user ? colors.surfaceElevated : undefined,+ height: bubbleHeight,+ stroke: user ? colors.textSecondary : undefined,+ textBlocks,+ width: bubbleWidth,+ x: bubbleX,+ y: cursorY,+ });+ if (blocks.length > 0) cursorY += bubbleHeight + MESSAGE_GAP;previousIndex = currentIndex;}const footerY = cursorY + 36;return {bubbles,+ images,footerY,gaps,height: footerY + 22 + PADDING,@@ -172,36 +246,87 @@ export function buildConversationShareSvgLayout({};}-function plainConversationShareText(message: ConversationShareMessage): string {- const parts = message.bodyParts- ? message.bodyParts- .map((part) => (part.kind === "text" ? part.text : part.label))- .join("\n")- : message.body;- const combined = [parts, message.secondaryBody].filter(Boolean).join("\n");- return redactSensitiveText(plainMarkdownText(combined));-}+type ShareBodyPart = { text: string } | { image: ConversationShareImage };-function plainMarkdownText(markdown: string): string {- const blocks = parseMobileMarkdown(markdown);- return blocks- .map(plainMarkdownBlockText)- .filter(Boolean)- .join("\n")- .replace(/\n{3,}/g, "\n\n")- .trim();+/** Traverse occurrences, using the source map only to look up decoded bytes. */+function conversationShareBodyParts(+ message: ConversationShareMessage,+): ShareBodyPart[] {+ const parts: ShareBodyPart[] = [];+ const append = (part: ShareBodyPart) => {+ const last = parts[parts.length - 1];+ if ("text" in part && last && "text" in last) last.text += part.text;+ else parts.push(part);+ };+ const markdown = (text: string) => {+ for (const block of parseMobileMarkdown(text)) {+ for (const part of markdownBlockParts(block, message.images))+ append(part);+ append({ text: "\n" });+ }+ };+ if (message.bodyParts) {+ for (const part of message.bodyParts) {+ if (part.kind === "text") markdown(part.text);+ else append({ text: `${part.label}\n` });+ }+ } else markdown(message.body);+ if (message.secondaryBody) markdown(message.secondaryBody);+ const fullText = parts+ .map((part) => ("text" in part ? part.text : ""))+ .join("");+ const redacted = redactSensitiveText(fullText);+ let safeParts = parts;+ if (redacted !== fullText) {+ safeParts = [];+ let sourceOffset = 0;+ let safeOffset = 0;+ for (const part of parts) {+ if ("text" in part) {+ sourceOffset += part.text.length;+ continue;+ }+ // A secret can span an image. Position images against redacted prefixes,+ // but take ALL output text from the fully redacted message, never a prefix.+ const prefix = redactSensitiveText(fullText.slice(0, sourceOffset));+ let boundary = 0;+ while (+ boundary < prefix.length &&+ prefix[boundary] === redacted[boundary]+ )+ boundary++;+ boundary = Math.max(safeOffset, boundary);+ safeParts.push({ text: redacted.slice(safeOffset, boundary) }, part);+ safeOffset = boundary;+ }+ safeParts.push({ text: redacted.slice(safeOffset) });+ }+ return safeParts.flatMap<ShareBodyPart>((part) => {+ if ("image" in part) return [part];+ const text = part.text.replace(/\n{3,}/g, "\n\n").trim();+ return text ? [{ text }] : [];+ });}-function plainMarkdownBlockText(block: MobileMarkdownBlock): string {+function markdownBlockParts(+ block: MobileMarkdownBlock,+ images: ConversationShareMessage["images"],+): ShareBodyPart[] {switch (block.type) {case "paragraph":case "heading":- return plainMarkdownInlineText(block.inlines);+ return markdownInlineParts(block.inlines, images);case "blockquote":- return plainMarkdownInlineText(block.inlines)- .split("\n")- .map((line) => `> ${line}`)- .join("\n");+ return markdownInlineParts(block.inlines, images).map((part) =>+ "text" in part+ ? {+ text: part.text+ .split("\n")+ .map((line) => `> ${line}`)+ .join("\n"),+ }+ : part,+ );case "list_item": {const taskMarker =typeof block.checked === "boolean"@@ -214,26 +339,40 @@ function plainMarkdownBlockText(block: MobileMarkdownBlock): string {? `${block.marker} ${taskMarker}`: taskMarker: block.marker;- return `${marker} ${plainMarkdownInlineText(block.inlines)}`;+ return [+ { text: `${marker} ` },+ ...markdownInlineParts(block.inlines, images),+ ];}case "table": {const rows = [block.header, ...block.rows.map((row) => row.cells)];- return rows- .map((cells) => cells.map(plainMarkdownInlineText).join(" | "))- .join("\n");+ return rows.flatMap((cells, rowIndex) => [+ ...(rowIndex ? [{ text: "\n" }] : []),+ ...cells.flatMap((inlines, cellIndex) => [+ ...(cellIndex ? [{ text: " | " }] : []),+ ...markdownInlineParts(inlines, images),+ ]),+ ]);}case "code":case "math":case "mermaid":- return block.text;+ return [{ text: block.text }];}}-function plainMarkdownInlineText(+function markdownInlineParts(inlines: readonly MobileMarkdownInline[],-): string {- return inlines- .map((inline) => {+ images: ConversationShareMessage["images"],+): ShareBodyPart[] {+ const parts: ShareBodyPart[] = [];+ for (const inline of inlines) {+ const image = inline.type === "image" ? images?.get(inline.url) : undefined;+ if (image) {+ parts.push({ image });+ continue;+ }+ const text = (() => {if (inline.type === "image") {return (inline.alt.trim() || i18n.t("message.renderer.imageFallbackTitle")@@ -243,8 +382,12 @@ function plainMarkdownInlineText(return `~~${inline.text}~~`;}return inline.text;- })- .join("");+ })();+ const last = parts[parts.length - 1];+ if (last && "text" in last) last.text += text;+ else parts.push({ text });+ }+ return parts;}export function wrapSvgText(diff --git a/apps/mobile/src/session/conversationShareWebViewHtml.ts b/apps/mobile/src/session/conversationShareWebViewHtml.tsindex 445158b198..5172b3b7bf 100644--- a/apps/mobile/src/session/conversationShareWebViewHtml.ts+++ b/apps/mobile/src/session/conversationShareWebViewHtml.ts@@ -7,6 +7,7 @@ import {type SelectableMarkdownHtmlOptions,} from "@/session/selectableMarkdownHtml";import { buildMessageContentLayout } from "@/session/messageContentLayout";+import { collectMobileMarkdownImages } from "@/session/messageMarkdown";import { lineHeight, typeScale } from "@/theme/tokens";export interface ConversationShareMessage {@@ -17,11 +18,20 @@ export interface ConversationShareMessage {body: string;bodyParts?: readonly ConversationShareBodyPart[];secondaryBody?: string;+ /** Export-only decoded images, keyed by attachment/Markdown source. */+ images?: ReadonlyMap<string, ConversationShareImage>;+}++export interface ConversationShareImage {+ uri: string;+ width: number;+ height: number;}export interface ConversationShareAttachment {kind: "image" | "file";name: string;+ uri?: string;}export type ConversationShareBodyPart =@@ -124,6 +134,20 @@ function buildMessageHtml(message: ConversationShareMessage,markdownOptions: SelectableMarkdownHtmlOptions,): string {+ markdownOptions = { ...markdownOptions, imageSources: message.images ?? new Map() };+ const texts = message.bodyParts+ ? 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+ // 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)+ ) {+ throw new Error('conversation-share-image-requires-svg');+ }const body = redactSensitiveText(message.body).trim();const secondaryBody = message.secondaryBody? redactSensitiveText(message.secondaryBody).trim()@@ -136,7 +160,7 @@ function buildMessageHtml(const secondaryHtml = secondaryBody? buildSelectableMarkdownFragmentHtml(secondaryBody, markdownOptions): "";- const attachmentsHtml = buildAttachmentsHtml(message.attachments ?? []);+ const attachmentsHtml = buildAttachmentsHtml(message.attachments ?? [], message.images);const bubbleHtml = bodyHtml || secondaryHtml? [`<div class="share-bubble share-bubble-${message.kind}">`,@@ -182,10 +206,16 @@ function buildBodyPartsHtml(function buildAttachmentsHtml(attachments: readonly ConversationShareAttachment[],+ 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/')) {+ 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>`;});return `<div class="share-attachments">${items.join("")}</div>`;@@ -275,6 +305,13 @@ function buildConversationShareCss({}.share-message-user .share-attachments { align-items: flex-end; }.share-message-assistant .share-attachments { align-items: flex-start; }+ .share-attachment-image {+ display: block;+ max-width: 100%;+ max-height: 320px;+ object-fit: contain;+ border-radius: 12px;+ }.share-attachment-chip {box-sizing: border-box;display: flex;diff --git a/apps/mobile/src/session/selectableMarkdownHtml.ts b/apps/mobile/src/session/selectableMarkdownHtml.tsindex b6dd77eecc..f31a9da1a9 100644--- a/apps/mobile/src/session/selectableMarkdownHtml.ts+++ b/apps/mobile/src/session/selectableMarkdownHtml.ts@@ -19,6 +19,8 @@ import { i18n } from '@/i18n';* 只保留「markdown → 完整 HTML 文档」这一条能力。*/export interface SelectableMarkdownHtmlOptions {+ /** When supplied, export only these embedded images; never expose source URLs. */+ imageSources?: ReadonlyMap<string, { uri: string }>;bodyGap?: number;borderColor?: string;chipColor?: string;@@ -54,6 +56,7 @@ export interface SelectableMarkdownHtmlOptions {/** renderBlocks/renderInline 的渲染上下文(目前只有会话 chip 标题 map)。 */interface RenderContext {+ imageSources?: SelectableMarkdownHtmlOptions['imageSources'];sessionLinkTitles?: Readonly<Record<string, string>>;}@@ -82,7 +85,7 @@ export function buildSelectableMarkdownHtml('</head>','<body>',`<main id="xdt-content" role="article" aria-label="${escapeAttribute(i18n.t('message.renderer.markdownDocAriaLabel'))}">`,- renderBlocks(blocks, { sessionLinkTitles: options.sessionLinkTitles }),+ renderBlocks(blocks, { sessionLinkTitles: options.sessionLinkTitles, imageSources: options.imageSources }),'</main>',hasMath ? buildMathRuntimeScript() : '',buildTargetLineScript(options.targetLine),@@ -96,6 +99,7 @@ export function buildSelectableMarkdownFragmentHtml(options: SelectableMarkdownHtmlOptions = {},): string {return renderBlocks(parseMobileMarkdown(markdown), {+ imageSources: options.imageSources,sessionLinkTitles: options.sessionLinkTitles,});}@@ -512,6 +516,13 @@ function renderInline(inline: MobileMarkdownInline, ctx: RenderContext = {}): st// 关闭),加载失败保持斜体源码。return `<span class="xdt-math-inline" data-latex="${escapeAttribute(inline.text)}"><em>${escapeHtml(inline.text)}</em></span>`;case 'image': {+ if (ctx.imageSources) {+ const image = ctx.imageSources.get(inline.url);+ const alt = inline.alt || i18n.t('message.renderer.imageFallbackTitle');+ return image?.uri.startsWith('data:image/')+ ? `<img src="${escapeAttribute(image.uri)}" alt="${escapeAttribute(alt)}">`+ : `<span class="xdt-image-chip">${escapeHtml(alt)}</span>`;+ }// xdt 系非直连图:WebView 无法解析 xdt-image:// 等内部 scheme,渲染占位 chip,// 点击经 data-xdt-src 上报后由 ImageLightbox 走 remote-media resolver 取图。if (!isMobileMarkdownImageDirectUrl(inline.url)) {diff --git a/apps/mobile/src/session/useConversationShareImages.ts b/apps/mobile/src/session/useConversationShareImages.tsnew file mode 100644index 0000000000..014a829ed7--- /dev/null+++ b/apps/mobile/src/session/useConversationShareImages.ts@@ -0,0 +1,203 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { Image } from "react-native";+import { File } from "expo-file-system";+import {+ prepareConversationShareImages,+ type ConversationShareImageContext,+} from "@/session/conversationShareImages";+import type {+ ConversationShareImage,+ ConversationShareMessage,+} from "@/session/conversationShareWebViewHtml";+import {+ isDesktopLocalMediaUrl,+ type ResolveRemoteMediaFn,+} from "@/session/remoteMedia";+import { downloadRemoteMediaAsDataUri } from "@/session/remoteMediaDiskCacheExpo";+import { imageMimeFromUrl } from "@/session/remoteMediaDiskCache";+import {+ getSentAttachmentThumbUri,+ ensureSentAttachmentThumbsHydrated,+} from "@/session/sentAttachmentThumbStore";++const MAX_IMAGE_BYTES = 8 * 1024 * 1024;++async function readShareImageFile(+ uri: string,+ mimeType: string,+): Promise<string | null> {+ const file = new File(uri);+ if (!file.exists || file.size <= 0 || file.size > MAX_IMAGE_BYTES)+ return null;+ return `data:${mimeType};base64,${await file.base64()}`;+}++async function loadShareImage(+ url: string,+ resolve: ResolveRemoteMediaFn,+ canRead: () => boolean,+ signal: AbortSignal,+): Promise<ConversationShareImage | null> {+ // The existing store owns both OSS and desktop-media upload thumbnails.+ await ensureSentAttachmentThumbsHydrated();+ if (!canRead()) return null;+ const localThumb = getSentAttachmentThumbUri(url);+ let uri = localThumb+ ? ((await readShareImageFile(+ localThumb,+ imageMimeFromUrl(localThumb) ?? "image/jpeg",+ ).catch(() => null)) ?? url)+ : url;+ if (!canRead()) return null;+ let mimeType = imageMimeFromUrl(uri) ?? "image/jpeg";+ if (uri === url && isDesktopLocalMediaUrl(url)) {+ const media = await resolve(+ {+ kind: "image",+ url,+ previewable: true,+ thumbnail: true,+ },+ { signal },+ );+ if (+ !canRead() ||+ !media.mimeType.startsWith("image/") ||+ !Number.isFinite(media.size) ||+ media.size <= 0 ||+ media.size > MAX_IMAGE_BYTES+ )+ return null;+ uri = media.url;+ mimeType = media.mimeType;+ // 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)) {+ uri =+ (await downloadRemoteMediaAsDataUri(uri, mimeType, MAX_IMAGE_BYTES)) ??+ "";+ }+ }+ if (uri.startsWith("file://") && isDesktopLocalMediaUrl(url)) {+ // Other local files must come from the controlled media resolver.+ uri = (await readShareImageFile(uri, mimeType)) ?? "";+ }+ if (+ !canRead() ||+ !uri.startsWith("data:image/") ||+ uri.length > (MAX_IMAGE_BYTES * 4) / 3 + 128+ )+ return null;+ const size = await Image.getSize(uri);+ return { uri, width: size.width, height: size.height };+}++interface ShareImageJob {+ sourceMessages: readonly ConversationShareMessage[];+ resolve: ResolveRemoteMediaFn;+ context: ConversationShareImageContext;+ finish: (messages: readonly ConversationShareMessage[]) => void;+}++/** Prepare one click-time snapshot; live message updates cannot replace it. */+export function useConversationShareImages(+ messages: readonly ConversationShareMessage[],+ resolve: ResolveRemoteMediaFn,+ { workdir, remoteHostId, sessionId }: ConversationShareImageContext,+) {+ const [job, setJob] = useState<ShareImageJob | null>(null);+ const prepare = useCallback(() => {+ return new Promise<readonly ConversationShareMessage[]>((finish) => {+ setJob({+ sourceMessages: messages,+ resolve,+ context: { workdir, remoteHostId, sessionId },+ finish,+ });+ });+ }, [messages, resolve, workdir, remoteHostId, sessionId]);+ const cancel = useCallback(() => setJob(null), []);+ const selectionKey = JSON.stringify(+ messages.map((message) => message.clientId),+ );+ useEffect(cancel, [cancel, selectionKey, sessionId]);+ const revision = useRef(0);+ const activeJob = useRef<typeof job | null>(null);+ const [prepared, setPrepared] = useState<{+ job: typeof job;+ messages: readonly ConversationShareMessage[];+ revision: number;+ } | null>(null);+ useEffect(() => {+ if (!job) return;+ const { sourceMessages, resolve, context } = job;+ // The existing media queue removes this export's still-queued waiter.+ // Effect-local ownership also gives StrictMode replays a fresh signal.+ const controller = new AbortController();+ let active = true;+ activeJob.current = job;+ let timedOut = false;+ let finishImageWait!: (image: null) => void;+ const imageDeadline = new Promise<null>((done) => {+ finishImageWait = done;+ });+ const timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ finishImageWait(null);+ }, 20_000);+ void prepareConversationShareImages(+ sourceMessages,+ // Keep completed images and all message text when the shared deadline+ // expires. Remaining images become placeholders without starting more IO.+ (url) =>+ timedOut+ ? Promise.resolve(null)+ : Promise.race([+ loadShareImage(+ url,+ resolve,+ () => active && !timedOut,+ controller.signal,+ ),+ imageDeadline,+ ]),+ context,+ () => active,+ )+ .then((result) => {+ clearTimeout(timer);+ if (active)+ setPrepared({ job, messages: result, revision: ++revision.current });+ })+ .catch(() => {+ clearTimeout(timer);+ if (active)+ setPrepared({+ job,+ messages: sourceMessages,+ revision: ++revision.current,+ });+ });+ return () => {+ active = false;+ controller.abort();+ clearTimeout(timer);+ finishImageWait(null);+ activeJob.current = null;+ // StrictMode immediately replays this effect with the same job.+ queueMicrotask(() => {+ if (activeJob.current !== job) job.finish([]);+ });+ };+ }, [job]);+ useEffect(() => {+ if (job && prepared?.job === job) job.finish(prepared.messages);+ }, [job, prepared]);+ return {+ prepare,+ cancel,+ messages: prepared?.job === job ? prepared.messages : [],+ revision: prepared?.job === job ? prepared.revision : 0,+ };+}