Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 支持预览待发送队列中的图片 (#6129)

DavidShenXD405ce16825ac
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 55c5c0bc6b..594a59f099 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -398,6 +398,7 @@ import {
import {
mergePendingSendItems,
buildPendingSendItems,
+ pendingSendItemKey,
type MobilePendingSendActions,
} from '@/session/pendingSendItems';
import { isSourceDeviceRemoved } from '@/session/messageSourceLabels';
@@ -455,6 +456,8 @@ import { buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttach
import { useMobileLocalAttachments } from '@/session/useMobileLocalAttachments';
import {
getSentMessageImagePreview,
+ pruneSentMessageImagePreviews,
+ rememberOutboxImagePreviews,
rememberSentMessageImagePreviews,
type SentMessageImagePreviews,
} from '@/session/sentMessageImagePreviews';
@@ -1581,15 +1584,18 @@ function SessionScreenContent() {
* 排队气泡里的图不能等 sentAttachmentThumbStore 那条链(上传落定 → 拷进自有目录 →
* AsyncStorage hydrate)——期间查询一律返回 null,气泡只能画空占位格。发送时手边就有
* 预览,记下来直接用;store 仍是重开会话 / 预览失效后的后备。
- * 最多保留 64 条消息的预览;正式内容还会核对图片指纹,防止同名替换误用旧图。
+ * 活跃发送条目全部保留,另保留最近 64 条历史记录;正式内容还会核对图片指纹。
*/
const sentImagePreviewsRef = useRef<SentMessageImagePreviews>(new Map());
+ const liveImagePreviewClientIdsRef = useRef<ReadonlySet<string>>(new Set());
const rememberSentAttachmentPreviews = useCallback((
clientId: string,
attachments: readonly RemoteSerializedAttachment[],
previewOf: (attachment: RemoteSerializedAttachment) => string | null | undefined,
+ galleryKeyOf?: (attachment: RemoteSerializedAttachment) => string | undefined,
) => {
- rememberSentMessageImagePreviews(sentImagePreviewsRef.current, sessionId, clientId, attachments, previewOf);
+ rememberSentMessageImagePreviews(sentImagePreviewsRef.current, sessionId, clientId, attachments,
+ previewOf, galleryKeyOf, liveImagePreviewClientIdsRef.current);
}, [sessionId]);
const getSentImagePreview = useCallback((clientId: string, imageIndex: number, name: string, attachmentId?: string, sha256?: string, sourceRef?: string) => (
getSentMessageImagePreview(sentImagePreviewsRef.current, sessionId, clientId, imageIndex, name, attachmentId, sha256, sourceRef)
@@ -1720,11 +1726,8 @@ function SessionScreenContent() {
outboxRef.current = outboxItems;
useEffect(() => observeDurableOutboxSending(mobileDurableOutbox, deviceId, sessionId, (record) => {
markQueueItemSending(record.prepared!);
- rememberSentAttachmentPreviews(record.item.clientId, outboxItemAttachments(record.item), (attachment) => {
- const slot = record.item.attachmentSlots.findIndex((item) => item?.id === attachment.id);
- const upload = record.uploads.find((item) => item.slot === slot);
- return upload ? durableOutboxUploadUri(record, upload) : record.item.slotMeta[slot]?.previewUri;
- });
+ rememberOutboxImagePreviews(sentImagePreviewsRef.current, sessionId, durableOutboxDisplayItem(record),
+ liveImagePreviewClientIdsRef.current);
}, (clientId) => {
setSendingQueueClientIds((current) => {
if (!current.has(clientId)) return current;
@@ -1732,7 +1735,7 @@ function SessionScreenContent() {
next.delete(clientId);
return next;
});
- }, outboxOwner.accountKey), [outboxOwner, deviceId, sessionId, markQueueItemSending, rememberSentAttachmentPreviews]);
+ }, outboxOwner.accountKey), [outboxOwner, deviceId, sessionId, markQueueItemSending]);
const pageMessageWorkLeaseRef = useRef<ReturnType<
typeof remoteSessionStore.acquireSessionMessageWork
> | null>(null);
@@ -6030,8 +6033,27 @@ function SessionScreenContent() {
// 「气泡在中间 → 消失 → 在底部重新出现」。进 data 后与正式消息同容器、同 key,回流即
// 原地变实(见 pendingSendItems.ts)。只喂给消息列表,不进 renderItems——搜索 / 相册 /
// diff 计数只认已落库的消息。
+ const livePendingSendClientIds = useMemo(() => new Set([
+ ...settlingItemsForRender, ...inputProjection.pendingQueue, ...outboxDisplayItems,
+ ].map((item) => item.clientId)), [settlingItemsForRender, inputProjection.pendingQueue, outboxDisplayItems]);
+ const pendingSendGroupKeys = useMemo(() => new Set([...livePendingSendClientIds].map(pendingSendItemKey)),
+ [livePendingSendClientIds]);
const pendingSendItems = useMemo(
() => {
+ // Also prune when the last live message leaves and the capture loop below is empty.
+ pruneSentMessageImagePreviews(sentImagePreviewsRef.current, sessionId, livePendingSendClientIds, liveImagePreviewClientIdsRef.current);
+ liveImagePreviewClientIdsRef.current = livePendingSendClientIds;
+ // Reopened failed/in-flight rows do not trigger the dispatch observer. Seed their
+ // slot identities before rendering, then let the authoritative queue override edits.
+ for (const item of outboxItems) {
+ rememberOutboxImagePreviews(sentImagePreviewsRef.current, sessionId, item, livePendingSendClientIds);
+ }
+ // Remote/reopened queues have no local send snapshot. Remember identities without
+ // fetching pixels so formal history can inherit their open viewer pages too.
+ // The authoritative queue wins over a stale settling copy of the same message.
+ for (const item of [...settlingItemsForRender, ...inputProjection.pendingQueue]) {
+ rememberSentAttachmentPreviews(item.clientId, item.files ?? [], () => null);
+ }
const presentationByClientId = new Map<
string,
{ actions: MobilePendingSendActions; hint: string | null }
@@ -6065,7 +6087,11 @@ function SessionScreenContent() {
[
i18nInstance.language,
getSentImagePreview,
+ rememberSentAttachmentPreviews,
+ sessionId,
inputProjection,
+ livePendingSendClientIds,
+ outboxItems,
outboxDisplayItems,
queueBusy,
queueEditing?.clientId,
@@ -6625,6 +6651,9 @@ function SessionScreenContent() {
const slot = readyAttachments.findIndex((a) => a.id === attachment.id);
const upload = record?.uploads.find((u) => u.slot === slot);
return record && upload ? durableOutboxUploadUri(record, upload) : readyPreviews[slot] ?? null;
+ }, (attachment) => {
+ const slot = item.attachmentSlots.findIndex((entry) => entry?.id === attachment.id);
+ return slot >= 0 ? `${item.clientId}-slot-${slot}` : undefined;
});
releaseUploadedSources(readyAttachments.map((a) => a.id));
// 本批映射清理(与原发送成功路径同口径):附件已随消息离开 composer 域。
@@ -10161,6 +10190,7 @@ function SessionScreenContent() {
items={messageListItems}
itemsStructureKey={messageListStructureKey}
pendingSend={pendingSendActions}
+ pendingSendGroupKeys={pendingSendGroupKeys}
getSentImagePreview={getSentImagePreview}
loadingEarlier={historyView.snapshot.ready ? historyView.view.isLoadingOlder() : loadingEarlier}
loadEarlierProgressKey={oldestLoadedMessageCursor}
diff --git a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
index be03a6d02f..af905a089b 100644
--- a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
+++ b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
@@ -6,10 +6,12 @@ import type { GestureResponderEvent } from 'react-native';
import { PendingSendBubble, type PendingSendBubbleActions } from '@/session/PendingSendBubble';
import { MessageBodyText } from '@/session/ShareMessageCheckbox';
import type { MobilePendingSendItem } from '@/session/pendingSendItems';
+import { collectMobileMessageGalleryImages, lightboxImagesForPayload } from '@/session/messageGallery';
-const { handlers, frames } = vi.hoisted(() => ({
+const { handlers, frames, durableThumbs } = vi.hoisted(() => ({
handlers: new Map<string, Record<string, unknown>>(),
frames: new Map<number, FrameRequestCallback>(),
+ durableThumbs: new Map<string, string>(),
}));
vi.mock('react-native', async () => {
const { createElement } = await import('react');
@@ -26,7 +28,7 @@ vi.mock('lucide-react-native', () => ({ Check: () => null, AlertCircle: () => nu
Bot: () => null, Ghost: () => null, Send: () => null, Timer: () => null,
Monitor: () => null, Smartphone: () => null }));
vi.mock('@/session/SentInlineAtomBody', () => ({ SentInlineAtomBody: () => null }));
-vi.mock('@/session/sentAttachmentThumbStore', () => ({ getSentAttachmentThumbUri: () => null,
+vi.mock('@/session/sentAttachmentThumbStore', () => ({ getSentAttachmentThumbUri: (ref: string) => durableThumbs.get(ref) ?? null,
useSentAttachmentThumbsVersion: () => 0 }));
vi.mock('react-i18next', () => ({ initReactI18next: { type: '3rdParty', init: () => undefined },
useTranslation: () => ({ t: (key: string) => key }) }));
@@ -41,6 +43,7 @@ let host: HTMLDivElement;
let frameId = 0;
const select = vi.fn();
const openLink = vi.fn();
+const openImage = vi.fn();
const removeOutbox = vi.fn();
const item: MobilePendingSendItem = {
type: 'pending_send', key: 'message-a', clientId: 'a', phase: 'queued', text: 'hello',
@@ -54,6 +57,7 @@ beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
handlers.clear(); frames.clear();
+ durableThumbs.clear();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { frames.set(++frameId, cb); return frameId; });
vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));
@@ -69,6 +73,7 @@ function show(
const actions: PendingSendBubbleActions = { selectedClientId, onSelect: select, onRemove: vi.fn(),
onBeginEdit: vi.fn(), onSteer: vi.fn(), onRetryOutbox: vi.fn(), onRemoveOutbox: removeOutbox };
act(() => root.render(<PendingSendBubble item={{ ...item, ...overrides }} actions={actions} viewerDeviceId={viewerDeviceId}
+ onOpenImage={openImage}
renderImage={() => null} renderFile={() => null}
renderText={() => <MessageBodyText testID="link" onPress={openLink}>link</MessageBodyText>} />));
}
@@ -113,6 +118,67 @@ it('lets a real body link consume the pending tap before the frame commits', ()
act(() => host.querySelector<HTMLElement>('[data-testid="link"]')!.click());
flush(); expect(openLink).toHaveBeenCalledOnce(); expect(select).not.toHaveBeenCalled();
});
+it.each(['queued', 'uploading', 'sending', 'settling', 'editing', 'failed'] as const)(
+ 'previews a %s image without changing queue selection or cancelling the send', (phase) => {
+ show({ phase, thumbs: [{ key: 'a-slot-0', uri: 'file:///photo.jpg', ossRef: null,
+ uploading: phase === 'uploading' }], attachmentCount: 1 });
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-0"]')!.click());
+ flush();
+ expect(openImage).toHaveBeenCalledOnce();
+ expect(openImage.mock.calls[0][0]).toMatchObject({ kind: 'media', media: {
+ kind: 'image', url: 'file:///photo.jpg', previewable: true,
+ } });
+ expect(select).not.toHaveBeenCalled();
+ expect(removeOutbox).not.toHaveBeenCalled();
+ },
+);
+it('opens the host original rather than its local thumbnail and preserves expanded queue actions', () => {
+ show({ thumbs: [{ key: 'a-slot-0', uri: 'file:///photo.jpg', ossRef: 'cindy-media://blobs/photo.jpg',
+ uploading: false }], attachmentCount: 1 }, 'a');
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-0"]')!.click());
+ expect(openImage.mock.calls[0][0].media).toMatchObject({
+ url: 'cindy-media://blobs/photo.jpg', previewable: false,
+ });
+ expect(select).not.toHaveBeenCalled();
+ expect(host.querySelector('[data-testid="pendingSend.actions.a"]')).not.toBeNull();
+});
+it('keeps an unavailable upload reference disabled until a local image becomes available', () => {
+ const thumb = { key: 'a-slot-0', uri: null, ossRef: 'cindy-oss-attach://photo', uploading: false };
+ show({ thumbs: [thumb] });
+ expect(handlers.get('pendingSend.image.a-slot-0')?.disabled).toBe(true);
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-0"]')!.click());
+ expect(openImage).not.toHaveBeenCalled();
+ show({ thumbs: [{ ...thumb, uri: 'file:///photo.jpg' }] });
+ expect(handlers.get('pendingSend.image.a-slot-0')?.disabled).toBe(false);
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-0"]')!.click());
+ expect(openImage).toHaveBeenCalledOnce();
+});
+it('opens the full gallery when a durable copy arrives after the thumbnail locks its temporary URI', () => {
+ const thumbs = [0, 1].map((index) => ({ key: `a-slot-${index}`, uri: `file:///temporary-${index}.jpg`,
+ ossRef: `cindy-oss-attach://photo-${index}`, uploading: false }));
+ show({ thumbs, attachmentCount: 2 });
+ durableThumbs.set(thumbs[1].ossRef, 'file:///durable-1.jpg');
+ show({ thumbs, attachmentCount: 2 });
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-1"]')!.click());
+ const payload = openImage.mock.calls[0][0];
+ const gallery = collectMobileMessageGalleryImages([{ ...item, thumbs, attachmentCount: 2 }]);
+ expect(lightboxImagesForPayload(gallery, payload, item.key)).toHaveLength(2);
+ expect(payload.galleryImageSlot).toBe(1);
+ expect(payload.media.url).toBe('file:///temporary-1.jpg');
+ expect(gallery[1].url).toBe('file:///durable-1.jpg');
+ expect(select).not.toHaveBeenCalled();
+});
+it('captures the clicked slot without skipping an earlier unreadable thumbnail', () => {
+ const thumbs = [
+ { key: 'a-slot-0', uri: null, ossRef: null, uploading: true },
+ { key: 'a-slot-1', uri: 'file:///clicked.jpg', ossRef: null, uploading: false },
+ ];
+ show({ thumbs, attachmentCount: 2 });
+ expect(handlers.get('pendingSend.image.a-slot-0')?.disabled).toBe(true);
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.image.a-slot-1"]')!.click());
+ expect(openImage.mock.calls[0][0]).toMatchObject({ galleryImageKey: 'a-slot-1', galleryImageSlot: 1 });
+ expect(select).not.toHaveBeenCalled();
+});
it('shows the source label above the bubble and announces it with the queued message', () => {
show({ source: { kind: 'automation', label: '由自动化「巡检」发送' } });
const label = host.querySelector('[data-testid="pendingSend.source.a"]');
diff --git a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
index f4a344b677..1b20152036 100644
--- a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
+++ b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
@@ -4,8 +4,15 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildAttachmentPayload } from '@/session/messagePayload';
import { svgAttachmentForDisplay } from '@/session/messageAttachments';
-import { collectMobileMessageGalleryImages, lightboxImagesForPayload } from '@/session/messageGallery';
-import type { MobileMessageRenderItem } from '@/session/messageRenderModel';
+import { collectMobileMessageGalleryImages, galleryImageIndexForPayload, lightboxImagesForPayload } from '@/session/messageGallery';
+import { buildMobileMessageRenderItems, type MobileMessageRenderItem } from '@/session/messageRenderModel';
+import { buildOutboxItem, outboxDisplayItem, outboxItemAttachments, outboxItemWithUpload,
+ type MobileOutboxThumb } from '@/session/sessionOutbox';
+import { buildPendingSendItems, pendingSendItemKey } from '@/session/pendingSendItems';
+import { computeVanishedQueueItems } from '@/session/queueSettling';
+import { getSentMessageImagePreview, rememberOutboxImagePreviews, rememberSentMessageImagePreviews, type GetSentMessageImagePreview, type SentMessageImagePreviews } from '@/session/sentMessageImagePreviews';
+import { createDurableOutbox, observeDurableOutboxSending, type DurableOutboxRecord } from '@/session/durableOutbox';
+import type { QueuedRemoteMessage, RemoteSerializedAttachment } from '@/session/types';
import {
ImageLightbox,
type ImageLightboxProps,
@@ -32,6 +39,7 @@ const runtime = vi.hoisted(() => ({
insets: { top: 40, bottom: 20, left: 0, right: 0 },
gesture: null as GestureNode | null,
alerts: [] as Array<[string, string, Array<{ text: string; style?: string; onPress?: () => void }>]>,
+ scrollToOffset: vi.fn(),
}));
vi.mock("expo-router", () => ({
@@ -79,10 +87,10 @@ vi.mock("react-native", async () => {
runtime.nodes.set("FlatList", props);
useImperativeHandle(
props.ref,
- () => ({ scrollToOffset: () => undefined }),
+ () => ({ scrollToOffset: runtime.scrollToOffset }),
[],
);
- return props.renderItem({ item: props.data[0], index: 0 });
+ return props.data.length ? props.renderItem({ item: props.data[0], index: 0 }) : null;
},
};
});
@@ -215,6 +223,7 @@ beforeEach(() => {
runtime.dimensions = { width: 400, height: 800 };
runtime.insets = { top: 40, bottom: 20, left: 0, right: 0 };
runtime.alerts = [];
+ runtime.scrollToOffset.mockClear();
root = createRoot(document.createElement("div"));
});
afterEach(() => act(() => root.unmount()));
@@ -245,6 +254,811 @@ function mount(overrides: Partial<ImageLightboxProps> = {}) {
return { props, render };
}
+describe('pending image gallery updates', () => {
+ const collect = (thumbs: MobileOutboxThumb[]) => collectMobileMessageGalleryImages([{
+ type: 'pending_send', key: 'pending', clientId: 'pending', phase: 'queued', text: '',
+ thumbs, attachmentCount: thumbs.length, uploadedCount: 0, fileCount: 0, queueIndex: 1,
+ sentInlineTokens: [], errorText: null, actions: null, hint: null,
+ }]);
+ const thumbs = [0, 1].map((index) => ({ key: `pending-slot-${index}`, uri: `file:///temporary-${index}.jpg`,
+ ossRef: null, uploading: true }));
+
+ it.each([false, true])('closes and cannot submit an old image after its source row loses all images (annotating: %s)', async (annotating) => {
+ const initial = collect(thumbs);
+ const onClose = vi.fn();
+ const onShareImage = vi.fn();
+ const onSubmit = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onClose, onShareImage,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ if (annotating) {
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw, 'onStart', { x: 100, y: 200 });
+ fire(draw, 'onFinalize', {}, true);
+ }
+ props.images = lightboxImagesForPayload(collect([]), initial[0].payload, 'pending', props.images, true);
+ render();
+ expect(props.images).toEqual([]);
+ expect(onClose).toHaveBeenCalledOnce();
+ if (annotating) press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(onShareImage).not.toHaveBeenCalled();
+ });
+
+ it.each(['remote middle removal', 'local cancellation', 'settling expiry', 'outbox cancellation']
+ .flatMap((reason) => [false, true].map((annotating) => ({ reason, annotating }))))(
+ 'closes the removed pending image after $reason (annotating: $annotating)', async ({ reason, annotating }) => {
+ const file: RemoteSerializedAttachment = { id: 'photo', name: 'photo.jpg', category: 'image',
+ path: 'https://example.invalid/photo.jpg', mimeType: 'image/jpeg', ext: 'jpg', size: 100 };
+ const target = { clientId: 'target', text: '', chatMessage: {}, files: [file] } as unknown as QueuedRemoteMessage;
+ const head = { ...target, clientId: 'head', files: [] };
+ const before = reason === 'remote middle removal' ? [head, target] : [target];
+ const after = reason === 'remote middle removal' ? [head] : [];
+ const input = { outbox: [], hiddenClientIds: new Set<string>(), sendingClientIds: new Set<string>(),
+ editingClientId: null, steeringClientIds: new Set<string>(), presentationByClientId: new Map() };
+ const sourceKey = pendingSendItemKey(target.clientId);
+ const initial = reason === 'outbox cancellation'
+ ? collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: [], settling: [],
+ outbox: [outboxDisplayItem(buildOutboxItem({ sessionId: 's', clientId: target.clientId, text: '',
+ permissionModeAtSend: 'ask', readyAttachments: [file], readyPreviews: ['file:///preview.jpg'], claimedUploads: [] }))] }))
+ : collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: before, settling: [] }));
+ const clicked = initial[0].payload;
+ const onClose = vi.fn();
+ const onShareImage = vi.fn();
+ const onSubmit = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onClose, onShareImage,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ if (annotating) {
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw, 'onStart', { x: 100, y: 200 });
+ fire(draw, 'onFinalize', {}, true);
+ } else {
+ expect(runtime.nodes.has('message.imageLightboxShareButton')).toBe(true);
+ }
+ const settling = reason === 'outbox cancellation' ? [] : computeVanishedQueueItems({ previous: before, current: after,
+ previousSteeringClientIds: new Set(), currentSteeringClientIds: new Set(), hiddenClientIds: new Set(),
+ locallyRemovedClientIds: new Set(reason === 'local cancellation' ? [target.clientId] : []) });
+ expect(settling.map((item) => item.clientId)).toEqual(reason === 'settling expiry' ? [target.clientId] : []);
+ if (reason === 'settling expiry') {
+ // Head departure is ambiguous: preserve the open viewer while the existing settling window is live.
+ props.images = lightboxImagesForPayload([], clicked, sourceKey, props.images, false, true);
+ render();
+ expect(onClose).not.toHaveBeenCalled();
+ }
+ const current = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: after, settling: [] }));
+ props.images = lightboxImagesForPayload(current, clicked, sourceKey, props.images, false, false);
+ // The fixture's node registry also contains unmounted controls unless cleared before rendering.
+ runtime.nodes.clear();
+ render();
+ expect(props.images).toEqual([]);
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(runtime.nodes.has('message.imageLightboxShareButton')).toBe(false);
+ if (runtime.nodes.has('message.imageLightboxAnnotationSubmit')) press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onShareImage).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['ready', 'uploading', 'remote-only'])('preserves annotations through the real %s outbox-to-queue handoff', (phase) => {
+ const file: RemoteSerializedAttachment = { id: 'photo', name: 'same.jpg', category: 'image',
+ path: 'cindy-oss-attach://photo', url: phase === 'remote-only' ? 'https://example.invalid/original.jpg' : 'cindy-oss-attach://photo',
+ mimeType: 'image/jpeg', ext: 'jpg', size: 100 };
+ const pdf = { ...file, id: 'pdf', category: 'pdf' as const, name: 'doc.pdf' };
+ let item = buildOutboxItem({ sessionId: 's', clientId: 'pending', text: '', permissionModeAtSend: 'ask',
+ readyAttachments: phase === 'uploading' ? [pdf] : [pdf, file],
+ readyPreviews: [null, phase === 'remote-only' ? null : 'file:///temporary.jpg'],
+ claimedUploads: phase !== 'uploading' ? [] : [
+ { localId: 'upload', failed: false, kind: 'image', previewUri: 'file:///temporary.jpg' },
+ ] });
+ const previews: SentMessageImagePreviews = new Map();
+ const input = { settling: [], hiddenClientIds: new Set<string>(), sendingClientIds: new Set<string>(),
+ editingClientId: null, steeringClientIds: new Set<string>(), presentationByClientId: new Map() };
+ const initial = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input,
+ queue: [], outbox: [outboxDisplayItem(item)] }));
+ const clicked = initial[0].payload;
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ if (phase === 'uploading') item = outboxItemWithUpload(item, 'upload', file);
+ props.images = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input,
+ queue: [], outbox: [outboxDisplayItem(item)] }));
+ render();
+ // Production's synchronous dispatch observer captures the slot identity before queue materialization.
+ rememberSentMessageImagePreviews(previews, 's', item.clientId, outboxItemAttachments(item),
+ () => phase === 'remote-only' ? null : 'file:///durable.jpg', (attachment) => {
+ const slot = item.attachmentSlots.findIndex((entry) => entry?.id === attachment.id);
+ return `${item.clientId}-slot-${slot}`;
+ });
+ const collectQueued = (attachment: RemoteSerializedAttachment) => collectMobileMessageGalleryImages(buildPendingSendItems({
+ ...input, outbox: [], queue: [{ clientId: 'pending', text: '', chatMessage: {}, files: [pdf, attachment] } as unknown as QueuedRemoteMessage],
+ getImagePreview: (clientId, index, name, id) => getSentMessageImagePreview(previews, 's', clientId, index, name, id),
+ }));
+ const queued = collectQueued({ ...file, url: 'https://example.invalid/materialized.jpg' });
+ props.images = lightboxImagesForPayload(queued, clicked, 'message-pending', props.images, true);
+ render();
+ const page = () => runtime.nodes.get('FlatList').renderItem({ item: props.images[0], index: 0 }).props;
+ expect(queued[0].key).toBe(initial[0].key);
+ expect(queued[0].previewUri).toBe(phase === 'remote-only' ? undefined : 'file:///durable.jpg');
+ expect(page().annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page().annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page().naturalSize).toEqual({ width: 400, height: 800 });
+ // Keeping a slot/URL while changing the actual attachment must still discard the old image's state.
+ const replaced = collectQueued({ ...file, id: 'replacement', url: queued[0].url });
+ props.images = lightboxImagesForPayload(replaced, clicked, 'message-pending', props.images, true);
+ render();
+ expect(replaced[0].key).not.toBe(initial[0].key);
+ expect(page().annotationStrokes).toEqual([]);
+ expect(page().annotationDraftStroke).toBeNull();
+ expect(page().naturalSize).toBeNull();
+ });
+
+ it.each([
+ ['failed', true], ['failed', false], ['sending', true], ['sending', false],
+ ] as const)('keeps a rehydrated %s outbox image and its strokes through queue/formal handoff (local preview: %s)', async (state, localPreview) => {
+ const files: RemoteSerializedAttachment[] = [0, 1].map((index) => ({ id: `photo-${index}`, name: `photo-${index}.jpg`,
+ category: 'image', path: `cindy-oss-attach://photo-${index}`, mimeType: 'image/jpeg', ext: 'jpg', size: 100,
+ sha256: String(index).repeat(64), ...(index === 1 ? { url: 'https://example.invalid/restored-1.jpg' } : {}) }));
+ const pdf = { ...files[0], id: 'pdf', name: 'document.pdf', category: 'pdf' as const };
+ const item = buildOutboxItem({ sessionId: 's', clientId: 'pending', text: '', permissionModeAtSend: 'ask',
+ readyAttachments: [files[0], pdf, files[1]], claimedUploads: [],
+ readyPreviews: [null, null, localPreview ? 'file:///durable-1.jpg' : null] });
+ const disk = new Map<string, string>();
+ const storage = { getAllKeys: async () => [...disk.keys()], getItem: async (key: string) => disk.get(key) ?? null,
+ setItem: async (key: string, value: string) => { disk.set(key, value); }, removeItem: async (key: string) => { disk.delete(key); } };
+ const initialStore = createDurableOutbox(storage);
+ await initialStore.activate('account');
+ await initialStore.add({ version: 1, accountId: 'account', deviceId: 'desktop', item, state,
+ sendAtMs: 1, createdAt: 1, uploads: [] } satisfies DurableOutboxRecord);
+ const restored = createDurableOutbox(storage);
+ await restored.activate('account');
+ const row = restored.getSnapshot()[0];
+ const onSending = vi.fn();
+ const unsubscribe = observeDurableOutboxSending(restored, 'desktop', 's', onSending, vi.fn());
+ try {
+ const previews: SentMessageImagePreviews = new Map();
+ // Capture on first render; the dispatch observer does not replay restored sends.
+ rememberOutboxImagePreviews(previews, 's', row.item, new Set([item.clientId]));
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ const input = { settling: [], hiddenClientIds: new Set<string>(), sendingClientIds: new Set<string>(),
+ editingClientId: null, steeringClientIds: new Set<string>(), presentationByClientId: new Map(), getImagePreview: getPreview };
+ const initial = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: [], outbox: [outboxDisplayItem(row.item)] }));
+ expect(initial).toHaveLength(1);
+ expect(initial[0].key).toBe('pending-slot-2');
+ const clicked = initial[0].payload;
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, initialImageKey: initial[0].key,
+ annotation: { submitLabel: 'Send', onSubmit: vi.fn() } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ // Even a retry cannot be used to bootstrap identity: the observer already saw this clientId.
+ const queuedFiles = [files[0], pdf, files[1]].map((file, index) => ({ ...file, url: `https://example.invalid/queued-${index}.jpg` }));
+ const queued = { clientId: item.clientId, text: '', chatMessage: {}, files: queuedFiles } as unknown as QueuedRemoteMessage;
+ await restored.update(row, { state: 'queued' });
+ await restored.update(restored.getSnapshot()[0], { state: 'sending', prepared: queued });
+ expect(onSending).not.toHaveBeenCalled();
+ rememberSentMessageImagePreviews(previews, 's', item.clientId, queuedFiles, () => null);
+ const queueGallery = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: [queued], outbox: [] }));
+ const formal = collectMobileMessageGalleryImages(buildMobileMessageRenderItems([{
+ id: 'server', clientId: item.clientId, sessionId: 's', role: 'user', toolUseId: null, agentMeta: null,
+ createdAt: '2026-10-16T00:00:00.000Z', content: { images: files.map((file, index) => ({
+ name: file.name, sha256: file.sha256, url: `https://example.invalid/formal-${index}.jpg`,
+ })) },
+ }]), undefined, undefined, 's', getPreview);
+ for (const gallery of [queueGallery, formal]) {
+ props.images = lightboxImagesForPayload(gallery, clicked, 'message-pending', props.images, true);
+ render();
+ expect(props.images).toHaveLength(2);
+ expect(props.images[1].key).toBe(initial[0].key);
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page.annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page.naturalSize).toEqual({ width: 400, height: 800 });
+ }
+ } finally {
+ unsubscribe();
+ }
+ });
+
+ it('keeps the current page, paging and sharing after URLs settle and the pending row leaves', async () => {
+ const initial = collect(thumbs);
+ const clicked = initial[1].payload;
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: clicked.media.url, onShareImage });
+ expect(runtime.nodes.get('FlatList').initialScrollIndex).toBe(1);
+ const updated = collect(thumbs.map((thumb, index) => ({
+ ...thumb, uploading: false, ossRef: `https://example.invalid/settled-${index}.jpg`,
+ })));
+ props.images = lightboxImagesForPayload(updated, clicked, 'pending', props.images);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(updated[1].url);
+ // Paging away from the originally clicked page must also survive a row handoff.
+ act(() => runtime.nodes.get('FlatList').onMomentumScrollEnd({ nativeEvent: { contentOffset: { x: 0 } } }));
+ props.images = lightboxImagesForPayload([], clicked, 'pending', props.images, false, true);
+ render();
+ expect(runtime.nodes.get('FlatList').data).toHaveLength(2);
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('1 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(updated[0].url);
+ });
+
+ it.each([
+ ['hash', false], ['hash', true], ['materialized queue', false], ['materialized queue', true],
+ ] as const)('keeps the second image and its strokes through formal history (%s, gap: %s)', async (proof, gap) => {
+ const files: RemoteSerializedAttachment[] = [0, 1].map((index) => ({ id: `photo-${index}`, name: `photo-${index}.jpg`,
+ category: 'image', path: `cindy-oss-attach://photo-${index}`, mimeType: 'image/jpeg', ext: 'jpg', size: 100,
+ ...(proof === 'hash' ? { sha256: String(index).repeat(64) } : {}) }));
+ let item = buildOutboxItem({ sessionId: 's', clientId: 'pending', text: '', permissionModeAtSend: 'ask',
+ readyAttachments: [], claimedUploads: files.map((file, index) => ({ localId: file.id, failed: false,
+ kind: 'image', ...(index === 1 ? { previewUri: 'file:///temporary-1.jpg' } : {}) })) });
+ const input = { settling: [], hiddenClientIds: new Set<string>(), sendingClientIds: new Set<string>(),
+ editingClientId: null, steeringClientIds: new Set<string>(), presentationByClientId: new Map() };
+ const initial = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, queue: [], outbox: [outboxDisplayItem(item)] }));
+ expect(initial).toHaveLength(1);
+ const clicked = initial[0].payload;
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, initialImageKey: initial[0].key,
+ annotation: { submitLabel: 'Send', onSubmit },
+ onResolveRemoteMedia: async (media) => ({ url: `file:///${media.url.split('/').at(-1)}`, ossKey: '',
+ mimeType: 'image/jpeg', size: 100, expiresAt: '9999-01-01', previewable: true }) });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ for (const file of files) item = outboxItemWithUpload(item, file.id, file);
+ const previews: SentMessageImagePreviews = new Map();
+ rememberSentMessageImagePreviews(previews, 's', item.clientId, outboxItemAttachments(item),
+ (file) => file.id === files[1].id ? 'file:///durable-1.jpg' : null,
+ (file) => `${item.clientId}-slot-${item.attachmentSlots.findIndex((entry) => entry?.id === file.id)}`);
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ if (proof === 'materialized queue') {
+ const queuedFiles = files.map((file, index) => ({ ...file, url: `cindy-media://blobs/formal-${index}.jpg` }));
+ // The session observes Desktop's new URL under the same attachment ID, without new local pixels.
+ rememberSentMessageImagePreviews(previews, 's', item.clientId, queuedFiles, () => null);
+ const queued = collectMobileMessageGalleryImages(buildPendingSendItems({ ...input, outbox: [],
+ queue: [{ clientId: item.clientId, text: '', chatMessage: {}, files: queuedFiles } as unknown as QueuedRemoteMessage],
+ getImagePreview: getPreview }));
+ props.images = lightboxImagesForPayload(queued, clicked, 'message-pending', props.images, true);
+ await act(async () => { render(); });
+ expect(props.images[1].key).toBe(initial[0].key);
+ }
+ if (gap) {
+ props.images = lightboxImagesForPayload([], clicked, 'message-pending', props.images, false, true);
+ render();
+ }
+ const formal = collectMobileMessageGalleryImages(buildMobileMessageRenderItems([{
+ id: 'server-id', clientId: item.clientId, sessionId: 's', role: 'user', toolUseId: null,
+ agentMeta: null, createdAt: '2026-01-01T00:00:00.000Z', content: { images: files.map((file, index) => ({
+ name: file.name, sha256: file.sha256, url: `cindy-media://blobs/formal-${index}.jpg`,
+ })) },
+ }]), undefined, undefined, 's', getPreview);
+ props.images = lightboxImagesForPayload(formal, clicked, 'message-pending', props.images, true);
+ await act(async () => { render(); });
+ expect(props.images[1].key).toBe(initial[0].key);
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page.annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page.naturalSize).toEqual({ width: 400, height: 800 });
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([props.images[1], 'file:///formal-1.jpg',
+ [{ points: [{ x: 0.25, y: 0.25 }] }, { points: [{ x: 0.5, y: 0.5 }] }],
+ { mimeType: 'image/jpeg', naturalWidth: 400, naturalHeight: 800 }]);
+ });
+
+ it.each([
+ ['hash', false, 1], ['hash', true, 1], ['url', false, 1], ['url', true, 1],
+ ['hash', false, 65], ['hash', true, 65],
+ ] as const)('keeps a remote queued image through formal history without a local preview (%s, gap: %s, live messages: %s)', async (proof, gap, liveCount) => {
+ const files: RemoteSerializedAttachment[] = [0, 1].map((index) => ({ id: `photo-${index}`, name: `photo-${index}.jpg`,
+ category: 'image', path: index === 0 ? 'cindy-oss-attach://unreadable' : 'cindy-media://blobs/queued-1.jpg',
+ mimeType: 'image/jpeg', ext: 'jpg', size: 100, ...(proof === 'hash' ? { sha256: String(index).repeat(64) } : {}) }));
+ const previews: SentMessageImagePreviews = new Map();
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ // The session observes a remote/reopened queue, with no local outbox or preview URI.
+ const liveClientIds = new Set(['pending', ...Array.from({ length: liveCount - 1 }, (_, index) => `other-${index}`)]);
+ for (const clientId of liveClientIds) {
+ rememberSentMessageImagePreviews(previews, 's', clientId, files, () => null, undefined, liveClientIds);
+ }
+ const initial = collectMobileMessageGalleryImages(buildPendingSendItems({
+ queue: [{ clientId: 'pending', text: '', chatMessage: {}, files } as unknown as QueuedRemoteMessage],
+ settling: [], outbox: [], hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,
+ steeringClientIds: new Set(), presentationByClientId: new Map(), getImagePreview: getPreview,
+ }));
+ expect(initial).toHaveLength(1);
+ expect(initial[0].previewUri).toBeUndefined();
+ const clicked = initial[0].payload;
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, initialImageKey: initial[0].key,
+ annotation: { submitLabel: 'Send', onSubmit },
+ onResolveRemoteMedia: async (media) => ({ url: `file:///${media.url.split('/').at(-1)}`, ossKey: '',
+ mimeType: 'image/jpeg', size: 100, expiresAt: '9999-01-01', previewable: true }) });
+ await act(async () => { await Promise.resolve(); });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ if (gap) {
+ props.images = lightboxImagesForPayload([], clicked, 'message-pending', props.images, false, true);
+ render();
+ }
+ const formalUrls = ['cindy-media://blobs/formal-0.jpg', proof === 'hash'
+ ? 'cindy-media://blobs/formal-1.jpg' : files[1].path];
+ const formal = collectMobileMessageGalleryImages(buildMobileMessageRenderItems([{
+ id: 'server-id', clientId: 'pending', sessionId: 's', role: 'user', toolUseId: null,
+ agentMeta: null, createdAt: '2026-01-01T00:00:00.000Z', content: { images: files.map((file, index) => ({
+ name: file.name, sha256: file.sha256, url: formalUrls[index],
+ })) },
+ }]), undefined, undefined, 's', getPreview);
+ props.images = lightboxImagesForPayload(formal, clicked, 'message-pending', props.images, true);
+ await act(async () => { render(); });
+ expect(props.images[1].key).toBe(initial[0].key);
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page.annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page.naturalSize).toEqual({ width: 400, height: 800 });
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([props.images[1], `file:///${formalUrls[1].split('/').at(-1)}`,
+ [{ points: [{ x: 0.25, y: 0.25 }] }, { points: [{ x: 0.5, y: 0.5 }] }],
+ { mimeType: 'image/jpeg', naturalWidth: 400, naturalHeight: 800 }]);
+ });
+
+ it.each(['ph://photo', 'content://media/1', 'assets-library://photo'])('previews %s but waits for a materialized file before enabling actions', async (uri) => {
+ const thumb = { key: 'pending-slot-0', uri, ossRef: null, uploading: true };
+ const initial = collect([thumb]);
+ const onShareImage = vi.fn();
+ const onSubmit = vi.fn<NonNullable<ImageLightboxProps['annotation']>['onSubmit']>(() => new Promise<void>(() => undefined));
+ const onResolveRemoteMedia = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: uri,
+ onShareImage, onResolveRemoteMedia, annotation: { submitLabel: 'Send', allowDirectSubmit: true, onSubmit } });
+ const preview = runtime.nodes.get('message.imageLightboxPreviewLayer') ?? runtime.nodes.get('Image');
+ act(() => preview.onLoad({ source: { width: 400, height: 800 } }));
+ expect(preview.source.uri).toBe(uri);
+ doubleTapAtCorner();
+ finishAnimations();
+ expect(runtime.nodes.get('Image').style[1].current.transform[4].scale).toBe(2.5);
+ doubleTapAtCorner();
+ finishAnimations();
+ expect(runtime.nodes.get('message.imageLightboxAnnotateButton').disabled).toBe(true);
+ expect(runtime.nodes.has('message.imageLightboxShareButton')).toBe(false);
+ expect(runtime.nodes.get('message.imageLightboxSendToChatButton').disabled).toBe(true);
+ press('message.imageLightboxAnnotateButton');
+ press('message.imageLightboxSendToChatButton');
+ await act(async () => { await Promise.resolve(); });
+ expect(onShareImage).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(onResolveRemoteMedia).not.toHaveBeenCalled();
+ props.images = collect([{ ...thumb, uri: 'file:///materialized.jpg', uploading: false }]);
+ render();
+ expect(props.images[0].key).toBe(initial[0].key);
+ expect(runtime.nodes.get('message.imageLightboxAnnotateButton').disabled).toBe(false);
+ expect(runtime.nodes.get('message.imageLightboxShareButton').disabled).toBe(false);
+ await act(async () => { press('message.imageLightboxShareButton'); });
+ expect(onShareImage.mock.calls[0]?.[1]).toBe('file:///materialized.jpg');
+ press('message.imageLightboxAnnotateButton');
+ const draw = gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw, 'onStart', { x: 100, y: 200 });
+ fire(draw, 'onFinalize', {}, true);
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]?.[1]).toBe('file:///materialized.jpg');
+ expect(onSubmit.mock.calls[0]?.[2]).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ });
+
+ it.each([
+ ['image', false], ['image', true], ['pdf', false], ['pdf', true],
+ ] as const)('keeps an unchanged image when an earlier %s is removed (local preview: %s)', (category, local) => {
+ const first: RemoteSerializedAttachment = { id: 'first', name: 'first', category,
+ path: 'cindy-oss-attach://first', size: 100, ext: 'jpg', mimeType: 'image/jpeg' };
+ const target: RemoteSerializedAttachment = { ...first, id: 'target', name: 'target.jpg', category: 'image',
+ path: 'https://example.invalid/target.jpg' };
+ const previews: SentMessageImagePreviews = new Map();
+ if (local) rememberSentMessageImagePreviews(previews, 's', 'pending', [first, target],
+ (file) => file.id === target.id ? 'file:///target.jpg' : null,
+ (file) => `pending-slot-${file.id === target.id ? 1 : 0}`);
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ const queued = (files: RemoteSerializedAttachment[]) => collectMobileMessageGalleryImages(buildPendingSendItems({
+ queue: [{ clientId: 'pending', text: '', chatMessage: {}, files } as unknown as QueuedRemoteMessage],
+ settling: [], outbox: [], hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,
+ steeringClientIds: new Set(), presentationByClientId: new Map(), getImagePreview: local ? getPreview : undefined,
+ }));
+ const initial = queued([first, target]);
+ expect(initial).toHaveLength(1);
+ const clicked = initial[0].payload;
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url,
+ annotation: { submitLabel: 'Send', onSubmit: vi.fn() } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ const current = queued([{ ...target, path: 'https://example.invalid/settled.jpg' }]);
+ props.images = lightboxImagesForPayload(current, clicked, 'message-pending', props.images, true);
+ render();
+ expect(current[0].key).toBe(initial[0].key);
+ const page = () => runtime.nodes.get('FlatList').renderItem({ item: props.images[0], index: 0 }).props;
+ expect(page().annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page().annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page().naturalSize).toEqual({ width: 400, height: 800 });
+ props.images = lightboxImagesForPayload(queued([{ ...target, id: 'replacement' }]), clicked, 'message-pending', props.images, true);
+ render();
+ expect(page().annotationStrokes).toEqual([]);
+ expect(page().annotationDraftStroke).toBeNull();
+ expect(page().naturalSize).toBeNull();
+ });
+
+ it('anchors the current image when an earlier pending placeholder becomes readable', () => {
+ const initial = collect([{ ...thumbs[0], uri: null }, thumbs[1]]);
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url });
+ props.images = collect(thumbs);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ expect(runtime.scrollToOffset).toHaveBeenLastCalledWith({ animated: false, offset: 400 });
+ });
+
+ it.each([false, true])('keeps the selected queue image after a readable earlier image is removed and the rest reorder (local: %s)', async (local) => {
+ const files: RemoteSerializedAttachment[] = ['first', 'target', 'tail'].map((id) => ({
+ id, name: `${id}.jpg`, category: 'image', path: `https://example.invalid/${id}.jpg`,
+ size: 100, mimeType: 'image/jpeg', ext: 'jpg',
+ }));
+ const previews: SentMessageImagePreviews = new Map();
+ if (local) rememberSentMessageImagePreviews(previews, 's', 'pending', files, (file) => `file:///${file.id}.jpg`,
+ (file) => `pending-slot-${files.indexOf(file)}`);
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ const queued = (attachments: RemoteSerializedAttachment[]) => collectMobileMessageGalleryImages(buildPendingSendItems({
+ queue: [{ clientId: 'pending', text: '', chatMessage: {}, files: attachments } as unknown as QueuedRemoteMessage],
+ settling: [], outbox: [], hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,
+ steeringClientIds: new Set(), presentationByClientId: new Map(), getImagePreview: local ? getPreview : undefined,
+ }));
+ const initial = queued(files);
+ const clicked = initial[1].payload;
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[1].url, initialImageKey: initial[1].key, onShareImage });
+ for (const attachments of [files.slice(1), [files[2], files[1]]]) {
+ props.images = lightboxImagesForPayload(queued(attachments), clicked, 'message-pending', props.images, true);
+ render();
+ const index = props.images.findIndex((image) => image.key === initial[1].key);
+ expect(index).toBe(attachments.indexOf(files[1]));
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe(`${index + 1} / 2`);
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(files[1].path);
+ }
+ });
+
+ it.each([0, 1])('follows the replacement of pending slot %i instead of a neighbor with the same old URL', async (index) => {
+ const original = thumbs.map((thumb) => ({ ...thumb, uri: 'https://example.invalid/duplicate.jpg' }));
+ const initial = collect(original);
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onShareImage });
+ act(() => runtime.nodes.get('FlatList').onMomentumScrollEnd({ nativeEvent: { contentOffset: { x: index * 400 } } }));
+ const replacement = { ...original[index], key: `${original[index].key}:replaced`, uri: 'https://example.invalid/replacement.jpg' };
+ props.images = collect(original.map((thumb, slot) => slot === index ? replacement : thumb));
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe(`${index + 1} / 2`);
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(replacement.uri);
+ });
+
+ it.each([0, 1])('opens the clicked pending slot %i when multiple attachments have the same URL', (index) => {
+ const images = collect(thumbs.map((thumb) => ({ ...thumb, uri: 'https://example.invalid/duplicate.jpg' })));
+ mount({ images, initialUrl: images[index].url, initialImageKey: images[index].key });
+ const list = runtime.nodes.get('FlatList');
+ expect(list.initialScrollIndex).toBe(index);
+ expect(list.renderItem({ item: images[index], index }).props.active).toBe(true);
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe(`${index + 1} / 2`);
+ });
+
+ it('keeps the replacement and its annotation when an earlier image becomes readable', async () => {
+ const initial = collect([thumbs[1]]);
+ const replacement = { ...thumbs[1], key: `${thumbs[1].key}:replacement`, uri: 'file:///replacement.jpg' };
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ props.images = collect([replacement]);
+ render();
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ props.images = collect([thumbs[0], replacement]);
+ render();
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page.annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([
+ props.images[1], replacement.uri,
+ [{ points: [{ x: 0.25, y: 0.25 }] }, { points: [{ x: 0.5, y: 0.5 }] }],
+ { mimeType: undefined, naturalWidth: 400, naturalHeight: 800 },
+ ]);
+ });
+
+ it.each([false, true])('follows the pending slot when replacement and an earlier upload settle together (paged: %s)', async (paged) => {
+ const waiting = [{ ...thumbs[0], uri: null }, thumbs[1]];
+ const initial = collect(paged ? thumbs : waiting);
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onShareImage });
+ if (paged) {
+ act(() => runtime.nodes.get('FlatList').onMomentumScrollEnd({ nativeEvent: { contentOffset: { x: 400 } } }));
+ props.images = collect(waiting);
+ render();
+ }
+ const replacement = { ...thumbs[1], key: 'replacement', uri: thumbs[0].uri };
+ // One update inserts an earlier readable page and replaces the active identity.
+ props.images = collect([thumbs[0], replacement]);
+ render();
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ expect(runtime.scrollToOffset).toHaveBeenLastCalledWith({ animated: false, offset: 400 });
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0]).toBe(props.images[1].payload.media);
+ });
+
+ it('clears old strokes and dimensions on a replacement that arrives with an earlier readable page', async () => {
+ const initial = collect([{ ...thumbs[0], uri: null }, thumbs[1]]);
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ const replacement = { ...thumbs[1], key: 'replacement', uri: 'file:///replacement.jpg' };
+ props.images = collect([thumbs[0], replacement]);
+ render();
+ const page = runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotating).toBe(true);
+ expect(page.annotationStrokes).toEqual([]);
+ expect(page.annotationDraftStroke).toBeNull();
+ expect(page.naturalSize).toBeNull();
+ // The FlatList mock mounts page zero only; deliver the active page's decoder/draw callbacks.
+ const activePage = () => runtime.nodes.get('FlatList').renderItem({ item: props.images[1], index: 1 }).props;
+ act(() => activePage().onNaturalSize(props.images[1].key, { width: 800, height: 400 }));
+ act(() => activePage().onDrawPoint('start', 200, 400, 0, 0, 1));
+ act(() => activePage().onDrawPoint('end', 200, 400, 0, 0, 1));
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([
+ props.images[1], replacement.uri, [{ points: [{ x: 0.5, y: 0.5 }] }],
+ { mimeType: undefined, naturalWidth: 800, naturalHeight: 400 },
+ ]);
+ });
+
+ it('refreshes the pending slot when removing an unreadable thumbnail leaves the readable page unchanged', async () => {
+ const waiting = [{ ...thumbs[0], uri: null },
+ { ...thumbs[0], key: 'another-waiting', uri: null }, thumbs[1]];
+ const initial = collect(waiting);
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onShareImage });
+ // Same key, URL and readable index, but the active thumbnail's slot changes from 2 to 1.
+ props.images = collect(waiting.slice(1));
+ render();
+ const replacement = { ...thumbs[1], key: 'replacement', uri: 'file:///replacement.jpg' };
+ props.images = collect([{ ...waiting[1], uri: 'file:///earlier.jpg' }, replacement]);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0]).toBe(props.images[1].payload.media);
+ });
+
+ it('keeps sharing the replacement when the original page later reappears', async () => {
+ const initial = collect(thumbs);
+ const replacement = { ...thumbs[0], key: `${thumbs[0].key}:replacement`, uri: 'file:///replacement.jpg' };
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, onShareImage });
+ props.images = collect([replacement, thumbs[1]]);
+ render();
+ props.images = collect([replacement, thumbs[1], thumbs[0]]);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('1 / 3');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(replacement.uri);
+ });
+
+ it('uses the latest page position when an already shifted active attachment is replaced', async () => {
+ const last = { ...thumbs[1], key: 'last', uri: 'file:///last.jpg' };
+ const replacement = { ...last, key: 'last:replacement', uri: 'file:///replacement.jpg' };
+ const initial = collect([...thumbs, last]);
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: last.uri, onShareImage });
+ props.images = collect([thumbs[1], last]);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ props.images = collect([thumbs[1], replacement, thumbs[0]]);
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 3');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(replacement.uri);
+ });
+
+ it('preserves completed and in-progress annotation strokes when the same pending image shifts pages', async () => {
+ const initial = collect([{ ...thumbs[0], uri: null }, thumbs[1]]);
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ fire(draw(), 'onUpdate', { x: 240, y: 440 });
+ const completed = [{ points: [{ x: 0.25, y: 0.25 }] }];
+ const draft = { points: [{ x: 0.5, y: 0.5 }, { x: 0.6, y: 0.55 }] };
+ // Inserting/removing an earlier page changes only this image's index, not its identity.
+ for (const images of [collect(thumbs), initial]) {
+ props.images = images;
+ render();
+ const list = runtime.nodes.get('FlatList');
+ const index = images.findIndex((image) => image.key === initial[0].key);
+ const page = list.renderItem({ item: images[index], index }).props;
+ expect(page.active).toBe(true);
+ expect(page.annotating).toBe(true);
+ expect(page.annotationStrokes).toEqual(completed);
+ expect(page.annotationDraftStroke).toEqual(draft);
+ }
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([
+ initial[0], initial[0].url, [...completed, draft],
+ { mimeType: undefined, naturalWidth: 400, naturalHeight: 800 },
+ ]);
+ });
+
+ it('loads the replacement image strokes when the active image changes without changing index', () => {
+ const initial = collect([thumbs[1]]);
+ const replacement = collect([thumbs[0]]);
+ const existing = [{ points: [{ x: 0.1, y: 0.2 }] }];
+ const { props, render } = mount({ images: initial, initialUrl: initial[0].url, autoAnnotate: true,
+ annotation: { submitLabel: 'Save', onSubmit: vi.fn(),
+ initialStrokesFor: (image) => image.key === replacement[0].key ? existing : [] } });
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ props.images = replacement;
+ render();
+ const page = runtime.nodes.get('FlatList').renderItem({ item: replacement[0], index: 0 }).props;
+ expect(page.annotationStrokes).toEqual(existing);
+ expect(page.annotationDraftStroke).toBeNull();
+ });
+
+ it('opens the clicked second slot even if its preview URL changed before the viewer mounted', () => {
+ const clicked = collect(thumbs)[1].payload;
+ const updated = collect(thumbs.map((thumb) => ({ ...thumb, uri: thumb.uri.replace('temporary', 'durable') })));
+ const images = lightboxImagesForPayload(updated, clicked, 'pending');
+ mount({ images, initialUrl: images[galleryImageIndexForPayload(images, clicked)]?.url ?? clicked.media.url });
+ expect(runtime.nodes.get('FlatList').initialScrollIndex).toBe(1);
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ });
+
+ it.each([false, true])('opens the clicked second slot after replacement before mounting (duplicate URL: %s)', async (duplicate) => {
+ const original = thumbs.map((thumb) => ({ ...thumb, uri: 'https://example.invalid/old.jpg' }));
+ const clicked = collect(original)[1].payload;
+ const updated = collect([original[0], { ...original[1], key: 'replacement',
+ uri: duplicate ? original[0].uri : 'https://example.invalid/replacement.jpg' }]);
+ const images = lightboxImagesForPayload(updated, clicked, 'pending');
+ const initialImage = images[galleryImageIndexForPayload(images, clicked)];
+ const onShareImage = vi.fn();
+ // Mirror the renderer's selected-image props; identity must disambiguate equal URLs.
+ const { props, render } = mount({ images,
+ initialImageKey: initialImage?.key ?? clicked.galleryImageKey,
+ initialUrl: initialImage?.url ?? clicked.media.url, onShareImage });
+ expect(runtime.nodes.get('FlatList').initialScrollIndex).toBe(1);
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0]).toBe(images[1].payload.media);
+
+ // Adopt the replacement on the very first render, so later shifts still follow its identity.
+ props.images = [{ ...images[0], key: 'inserted',
+ payload: { ...images[0].payload, galleryImageKey: 'inserted' } }, ...images];
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('3 / 3');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0]).toBe(images[1].payload.media);
+ });
+
+ it.each(['neighbor', 'replaced image'])('resets annotation and dimensions when a queued edit replaces the active attachment (opened from %s)', async (openedFrom) => {
+ const collectQueued = (id: string, url: string) => collectMobileMessageGalleryImages(buildPendingSendItems({
+ queue: [{ clientId: 'pending', text: '', chatMessage: {}, files: [
+ { id, name: 'same.jpg', category: 'image', path: url, url },
+ { id: 'neighbor', name: 'neighbor.jpg', category: 'image', path: 'https://example.invalid/neighbor.jpg' },
+ ] } as unknown as QueuedRemoteMessage],
+ settling: [], outbox: [], hiddenClientIds: new Set(), sendingClientIds: new Set(),
+ editingClientId: null, steeringClientIds: new Set(), presentationByClientId: new Map(),
+ }));
+ const initial = collectQueued('original', 'https://example.invalid/original.jpg');
+ // Cover both the original click and paging from an unchanged neighbor before a remote edit.
+ const clicked = initial[openedFrom === 'neighbor' ? 1 : 0].payload;
+ const onSubmit = vi.fn(() => new Promise<void>(() => undefined));
+ const { props, render } = mount({ images: initial, initialUrl: clicked.media.url,
+ annotation: { submitLabel: 'Send', onSubmit } });
+ act(() => runtime.nodes.get('FlatList').onMomentumScrollEnd({ nativeEvent: { contentOffset: { x: 0 } } }));
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
+ press('message.imageLightboxAnnotateButton');
+ const draw = () => gestures().find((gesture) => gesture.kind === 'Pan' && gesture.options.minDistance === 0)!;
+ fire(draw(), 'onStart', { x: 100, y: 200 });
+ fire(draw(), 'onFinalize', {}, true);
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ const page = () => runtime.nodes.get('FlatList').renderItem({ item: props.images[0], index: 0 }).props;
+
+ // A new URL for the same attachment must retain both strokes and known dimensions.
+ const settled = collectQueued('original', 'https://example.invalid/settled.jpg');
+ props.images = lightboxImagesForPayload(settled, clicked, 'message-pending', props.images);
+ render();
+ expect(page().annotationStrokes).toEqual([{ points: [{ x: 0.25, y: 0.25 }] }]);
+ expect(page().annotationDraftStroke).toEqual({ points: [{ x: 0.5, y: 0.5 }] });
+ expect(page().naturalSize).toEqual({ width: 400, height: 800 });
+
+ const replaced = collectQueued('replacement', 'https://example.invalid/replacement.jpg');
+ props.images = lightboxImagesForPayload(replaced, clicked, 'message-pending', props.images);
+ render();
+ expect(page().annotationStrokes).toEqual([]);
+ expect(page().annotationDraftStroke).toBeNull();
+ expect(page().naturalSize).toBeNull();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('1 / 2');
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 800, height: 400 } }));
+ fire(draw(), 'onStart', { x: 200, y: 400 });
+ fire(draw(), 'onFinalize', {}, true);
+ press('message.imageLightboxAnnotationSubmit');
+ await act(async () => { await Promise.resolve(); });
+ expect(onSubmit.mock.calls[0]).toEqual([
+ replaced[0], replaced[0].url, [{ points: [{ x: 0.5, y: 0.5 }] }],
+ { mimeType: undefined, naturalWidth: 800, naturalHeight: 400 },
+ ]);
+ });
+
+ it('keeps ordinary message pages selected when a completed work group rebuilds its keys', async () => {
+ // Ordinary message pages have no stable pending attachment identity.
+ const initial = collect(thumbs).map((image) => ({ ...image, payload: { ...image.payload, galleryImageKey: undefined } }));
+ const onShareImage = vi.fn();
+ const { props, render } = mount({ images: initial, initialUrl: initial[1].url, onShareImage });
+ props.images = initial.map((image) => ({ ...image, key: `completed:${image.key}` }));
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('2 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe(initial[1].url);
+ // After rebuilding the keys, moving this page must follow its adopted key.
+ const updated = collect([{ ...thumbs[1], uri: 'https://example.invalid/current.jpg' }])[0];
+ props.images = [{ ...updated, key: props.images[1].key }, props.images[0]];
+ render();
+ expect(runtime.nodes.get('message.imageLightboxPageLabel').children).toBe('1 / 2');
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage.mock.lastCall?.[0].url).toBe('https://example.invalid/current.jpg');
+ });
+});
+
describe('Markdown gallery prefetch boundaries', () => {
it('does not fetch a titled outside-workdir image when a neighboring image is opened', async () => {
const items = [{
diff --git a/apps/mobile/src/__tests__/messageGallery.test.ts b/apps/mobile/src/__tests__/messageGallery.test.ts
index b12e211152..746d3d3c22 100644
--- a/apps/mobile/src/__tests__/messageGallery.test.ts
+++ b/apps/mobile/src/__tests__/messageGallery.test.ts
@@ -9,6 +9,10 @@ import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';
import type { RemoteMessage } from '@/session/types';
import { mobileMarkdownImageUrlForWorkdir, mobileMarkdownManagedImagePreviewUrl } from '@/session/messageMarkdown';
import { buildMediaPayload } from '@/session/messagePayload';
+import { buildOutboxItem, outboxDisplayItem, type MobileOutboxThumb } from '@/session/sessionOutbox';
+import { buildPendingSendItems } from '@/session/pendingSendItems';
+import { getSentMessageImagePreview, rememberSentMessageImagePreviews, type GetSentMessageImagePreview,
+ type SentMessageImagePreviews } from '@/session/sentMessageImagePreviews';
const durableThumbs = vi.hoisted(() => new Map<string, string>());
vi.mock('@/session/sentAttachmentThumbStore', async (importOriginal) => ({
@@ -34,7 +38,236 @@ function messageItem(key: string, message: Partial<MobileMessageRenderItem & { m
} as MobileMessageRenderItem;
}
+function pendingItem(key: string, thumbs: MobileOutboxThumb[]): Extract<MobileMessageRenderItem, { type: 'pending_send' }> {
+ return {
+ type: 'pending_send', key, clientId: key, text: '', sentInlineTokens: [], phase: 'queued',
+ queueIndex: 1, thumbs, fileCount: 0, attachmentCount: thumbs.length, uploadedCount: thumbs.length,
+ errorText: null, actions: null, hint: null,
+ };
+}
+
describe('message gallery', () => {
+ it.each([
+ ['file:///photo.jpg', null, 'file:///photo.jpg', true],
+ ['ph://photo', null, 'ph://photo', true],
+ ['content://photo', null, 'content://photo', true],
+ ['assets-library://photo', null, 'assets-library://photo', true],
+ ['file:///photo.jpg', 'cindy-oss-attach://photo', 'file:///photo.jpg', true],
+ ['file:///photo.jpg', 'cindy-media://blobs/photo.jpg', 'cindy-media://blobs/photo.jpg', false],
+ [null, 'cindy-media://blobs/photo.jpg', 'cindy-media://blobs/photo.jpg', false],
+ ['file:///photo.jpg', 'https://example.com/photo.jpg', 'https://example.com/photo.jpg', true],
+ ] as const)('includes pending image %s / %s using a renderable source', (uri, ossRef, url, previewable) => {
+ const gallery = collectMobileMessageGalleryImages([pendingItem('pending', [
+ { key: 'photo', uri, ossRef, uploading: !ossRef },
+ ])]);
+ expect(gallery).toHaveLength(1);
+ expect(gallery[0]).toMatchObject({ url, groupKey: 'pending', payload: { media: { url, previewable } } });
+ });
+
+ it('uses the durable upload preview and keeps paging within the selected pending message', () => {
+ durableThumbs.set('cindy-oss-attach://pending', 'file:///durable.jpg');
+ try {
+ const gallery = collectMobileMessageGalleryImages([
+ pendingItem('pending-a', [
+ { key: 'a0', uri: 'file:///temporary.jpg', ossRef: 'cindy-media://blobs/a.jpg',
+ previewRef: 'cindy-oss-attach://pending', uploading: false },
+ { key: 'a1', uri: 'file:///b.jpg', ossRef: null, uploading: true },
+ ]),
+ pendingItem('pending-b', [{ key: 'b0', uri: 'file:///c.jpg', ossRef: null, uploading: false }]),
+ ]);
+ expect(gallery[0].previewUri).toBe('file:///durable.jpg');
+ expect(lightboxImagesForPayload(gallery, gallery[0].payload, 'pending-a').map((image) => image.key))
+ .toEqual(['a0', 'a1']);
+ } finally { durableThumbs.clear(); }
+ });
+
+ it('excludes pending placeholders that have no readable image yet', () => {
+ const gallery = collectMobileMessageGalleryImages([pendingItem('pending', [
+ { key: 'upload', uri: null, ossRef: 'cindy-oss-attach://missing', uploading: false },
+ { key: 'empty', uri: null, ossRef: null, uploading: true },
+ ])]);
+ expect(gallery).toEqual([]);
+ });
+
+ it('keeps the second pending image in its gallery as uploads settle to new URLs', () => {
+ const thumbs = [0, 1].map((index) => ({ key: `pending-slot-${index}`, uri: `file:///temporary-${index}.jpg`,
+ ossRef: `cindy-oss-attach://pending-${index}`, uploading: true }));
+ const initial = collectMobileMessageGalleryImages([pendingItem('pending', thumbs)]);
+ const opened = initial[1].payload;
+ try {
+ durableThumbs.set(thumbs[1].ossRef, 'file:///durable-1.jpg');
+ const durable = collectMobileMessageGalleryImages([pendingItem('pending', thumbs)]);
+ const durablePages = lightboxImagesForPayload(durable, opened, 'pending');
+ expect(durablePages.map((image) => image.key)).toEqual(thumbs.map((thumb) => thumb.key));
+ expect(galleryImageIndexForPayload(durablePages, opened)).toBe(1);
+ const settled = collectMobileMessageGalleryImages([pendingItem('pending', thumbs.map((thumb, index) => ({
+ ...thumb, uploading: false, ossRef: `cindy-media://blobs/settled-${index}.jpg`,
+ })))]);
+ const settledPages = lightboxImagesForPayload(settled, opened, 'pending');
+ expect(settledPages).toHaveLength(2);
+ expect(galleryImageIndexForPayload(settledPages, opened)).toBe(1);
+ expect(settledPages[1].url).toBe('cindy-media://blobs/settled-1.jpg');
+ } finally { durableThumbs.clear(); }
+ });
+
+ it('keeps distinct pending attachment slots even when they settle to the same content URL', () => {
+ const gallery = collectMobileMessageGalleryImages([pendingItem('pending', [0, 1].map((index) => ({
+ key: `pending-slot-${index}`, uri: null, ossRef: 'cindy-media://blobs/same.jpg', uploading: false,
+ })))]);
+ expect(gallery).toHaveLength(2);
+ expect(galleryImageIndexForPayload(gallery, gallery[1].payload)).toBe(1);
+ });
+
+ it('locates the replacement of a clicked slot when an earlier placeholder becomes readable before opening', () => {
+ const thumbs = [
+ { key: 'earlier', uri: null, ossRef: null, uploading: true },
+ { key: 'clicked', uri: 'file:///clicked.jpg', ossRef: null, uploading: false },
+ ];
+ const clicked = collectMobileMessageGalleryImages([pendingItem('pending', thumbs)])[0].payload;
+ const current = collectMobileMessageGalleryImages([pendingItem('pending', [
+ { ...thumbs[0], uri: 'file:///earlier.jpg' },
+ { ...thumbs[1], key: 'replacement', uri: 'file:///replacement.jpg' },
+ ])]);
+ const images = lightboxImagesForPayload(current, clicked, 'pending');
+ expect(galleryImageIndexForPayload(images, clicked)).toBe(1);
+ });
+
+ it('prefers an unchanged attachment identity to its old position when a queued edit reorders images', () => {
+ const thumbs = [0, 1].map((index) => ({ key: `slot-${index}`, uri: 'file:///duplicate.jpg',
+ ossRef: null, uploading: false }));
+ const clicked = collectMobileMessageGalleryImages([pendingItem('pending', thumbs)])[1].payload;
+ const reordered = collectMobileMessageGalleryImages([pendingItem('pending', [...thumbs].reverse())]);
+ expect(galleryImageIndexForPayload(reordered, clicked)).toBe(0);
+ });
+
+ it('retains the open pending gallery through row handoff without using another message with the same URL', () => {
+ const previous = collectMobileMessageGalleryImages([pendingItem('pending', [0, 1].map((index) => ({
+ key: `pending-slot-${index}`, uri: `file:///local-${index}.jpg`, ossRef: null, uploading: false,
+ })))]);
+ const opened = previous[1].payload;
+ const unrelated = collectMobileMessageGalleryImages([messageItem('other', {
+ attachments: [{ kind: 'image', name: 'same.jpg', uri: opened.media.url, previewable: true }],
+ })]);
+ expect(lightboxImagesForPayload(unrelated, opened, 'pending', previous, false, true)).toEqual(previous);
+ expect(lightboxImagesForPayload([], opened, 'pending', previous, false, true)).toEqual(previous);
+ // A different click must not inherit a previous viewer's pending gallery.
+ expect(lightboxImagesForPayload(unrelated, unrelated[0].payload, 'other', previous)).toEqual(unrelated);
+ });
+
+ it.each([false, true])('hands an outbox snapshot to the formal message with a different server ID (history gap: %s)', (gap) => {
+ const files = [0, 1].map((index) => ({ id: `upload-${index}`, name: `photo-${index}.jpg`,
+ category: 'image' as const, path: `cindy-oss-attach://upload-${index}`, size: 100, ext: 'jpg', mimeType: 'image/jpeg' }));
+ const item = buildOutboxItem({ clientId: 'mobile-client-id', sessionId: 's', text: '',
+ readyAttachments: files, readyPreviews: ['file:///outbox-0.jpg', 'file:///outbox-1.jpg'],
+ claimedUploads: [], permissionModeAtSend: 'ask' });
+ const [row] = buildPendingSendItems({ queue: [], settling: [], outbox: [outboxDisplayItem(item)],
+ hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,
+ steeringClientIds: new Set(), presentationByClientId: new Map() });
+ let previous = collectMobileMessageGalleryImages([row]);
+ const opened = previous[1].payload;
+ if (gap) previous = lightboxImagesForPayload([], opened, row.key, previous, false, true);
+ const message: RemoteMessage = { id: 'server-history-id', clientId: item.clientId, sessionId: 's',
+ role: 'user', content: { images: files.map((file, index) => ({
+ name: file.name, url: `cindy-media://blobs/formal-${index}.jpg`,
+ })) }, toolUseId: null, agentMeta: null, createdAt: '2026-01-01T00:00:00.000Z' };
+ // A separate message has identical image URLs, and the server's ID differs from clientId.
+ const rows = buildMobileMessageRenderItems([{ ...message, id: 'other-server-id', clientId: 'other' }, message]);
+ expect(rows.some((entry) => entry.key === row.key)).toBe(true);
+ const gallery = collectMobileMessageGalleryImages(rows);
+ const current = lightboxImagesForPayload(gallery, opened, row.key, previous, true);
+ expect(current).toHaveLength(2);
+ expect(current.map((image) => image.groupKey)).toEqual([row.key, row.key]);
+ expect(current.map((image) => image.url)).toEqual([
+ 'cindy-media://blobs/formal-0.jpg', 'cindy-media://blobs/formal-1.jpg',
+ ]);
+ expect(current.every((image) => image.payload.media.previewable === false)).toBe(true);
+ expect(current).not.toEqual(previous);
+ });
+
+ it.each(['text only', 'non-image files', 'unreadable replacement'])('does not retain deleted pending images when the source row remains (%s)', (edit) => {
+ const previous = collectMobileMessageGalleryImages([pendingItem('pending', [
+ { key: 'pending-slot-0:old', uri: 'file:///removed.jpg', ossRef: null, uploading: false },
+ ])]);
+ const row = pendingItem('pending', edit === 'unreadable replacement' ? [
+ { key: 'pending-slot-0:new', uri: null, ossRef: null, uploading: true },
+ ] : []);
+ row.text = 'edited on another device';
+ row.fileCount = edit === 'non-image files' ? 1 : 0;
+ const current = collectMobileMessageGalleryImages([row]);
+ expect(lightboxImagesForPayload(current, previous[0].payload, row.key, previous, true)).toEqual([]);
+ // Actual row departure still preserves the open snapshot during handoff.
+ expect(lightboxImagesForPayload([], previous[0].payload, row.key, previous, false, true)).toEqual(previous);
+ });
+
+ it.each([false, true])('discards a removed pending message instead of retaining its snapshot (same URL in another message: %s)', (duplicate) => {
+ const previous = collectMobileMessageGalleryImages([pendingItem('pending', [
+ { key: 'pending-slot-0', uri: 'file:///removed.jpg', ossRef: null, uploading: false },
+ ])]);
+ const opened = previous[0].payload;
+ const current = duplicate ? collectMobileMessageGalleryImages([messageItem('other', {
+ attachments: [{ kind: 'image', name: 'same.jpg', uri: opened.media.url, previewable: true }],
+ })]) : [];
+ expect(lightboxImagesForPayload(current, opened, 'pending', previous, false, false)).toEqual([]);
+ // Even with no retained snapshot, the canceled payload must not revive itself as a single image.
+ expect(lightboxImagesForPayload(current, opened, 'pending', null, false, false)).toEqual([]);
+ });
+
+ it('keeps proven attachment identities in formal history while deduplicating their Markdown reference', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const files = ['a', 'b'].map((id) => ({ id, name: `${id}.jpg`, category: 'image' as const,
+ path: `cindy-oss-attach://${id}`, sha256: 'c'.repeat(64), size: 100, mimeType: 'image/jpeg', ext: 'jpg' }));
+ rememberSentMessageImagePreviews(previews, 's', 'm', files, () => null, (file) => `m-slot-${file.id}`);
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ const url = 'https://example.invalid/same.jpg';
+ const rows = buildMobileMessageRenderItems([{ id: 'server', clientId: 'm', sessionId: 's', role: 'user',
+ toolUseId: null, agentMeta: null, createdAt: '2026-01-01T00:00:00.000Z', content: {
+ text: `![body copy](${url})`, images: files.map((file) => ({ name: file.name, sha256: file.sha256, url })),
+ } }]);
+ const gallery = collectMobileMessageGalleryImages(rows, undefined, undefined, 's', getPreview);
+ expect(gallery.map((image) => image.key)).toEqual(['m-slot-a', 'm-slot-b']);
+ expect(gallery.every((image) => image.payload.galleryImageKey === image.key)).toBe(true);
+ });
+
+ it('does not copy a pending identity to a same-name formal replacement with different pixels', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const file = { id: 'old', name: 'same.jpg', category: 'image' as const, path: 'cindy-oss-attach://old',
+ sha256: 'a'.repeat(64), size: 100, mimeType: 'image/jpeg', ext: 'jpg' };
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => 'file:///old.jpg', () => 'm-slot-old');
+ const getPreview: GetSentMessageImagePreview = (...args) => getSentMessageImagePreview(previews, 's', ...args);
+ const rows = buildMobileMessageRenderItems([{ id: 'server', clientId: 'm', sessionId: 's', role: 'user',
+ toolUseId: null, agentMeta: null, createdAt: '2026-01-01T00:00:00.000Z', content: {
+ images: [{ name: file.name, sha256: 'b'.repeat(64), url: 'cindy-media://blobs/new.jpg' }],
+ } }]);
+ const [replacement] = collectMobileMessageGalleryImages(rows, undefined, undefined, 's', getPreview);
+ expect(replacement.key).not.toBe('m-slot-old');
+ expect(replacement.previewUri).toBeUndefined();
+ expect(replacement.payload.galleryImageKey).toBeUndefined();
+ });
+
+ it.each([1, 2])('uses the current pending message when the clicked attachment is replaced (%i images)', (count) => {
+ const initialThumbs = Array.from({ length: count }, (_, index) => ({
+ key: `pending-slot-${index}:original`, uri: `file:///original-${index}.jpg`, ossRef: null, uploading: false,
+ }));
+ const initial = collectMobileMessageGalleryImages([pendingItem('pending', initialThumbs)]);
+ const clickedIndex = count - 1;
+ const clicked = initial[clickedIndex].payload;
+ let previous = initial;
+ // The original clicked identity remains absent across later queue updates.
+ for (const version of ['replacement', 'edited-again']) {
+ const current = collectMobileMessageGalleryImages([pendingItem('pending', initialThumbs.map((thumb, index) => (
+ index === clickedIndex ? { ...thumb, key: `pending-slot-${index}:${version}`, uri: `file:///${version}.jpg` } : thumb
+ )))]);
+ previous = lightboxImagesForPayload(current, clicked, 'pending', previous);
+ expect(previous).toEqual(current);
+ }
+ // Once the row leaves, keep the latest gallery rather than resurrecting the originally clicked image.
+ const unrelated = collectMobileMessageGalleryImages([pendingItem('other', initialThumbs.map((thumb) => (
+ { ...thumb, key: `other:${thumb.key}` }
+ )))]);
+ expect(lightboxImagesForPayload(unrelated, clicked, 'pending', previous, false, true)).toEqual(previous);
+ expect(lightboxImagesForPayload([], clicked, 'pending', previous, false, true)).toEqual(previous);
+ });
+
it.each(['', ' "title"', " 'title'"])(
'excludes out-of-workdir Markdown images from neighbor prefetch with title suffix %s', (title) => {
const outside = 'xdt-file://open?path=%2Fprivate%2Fphoto.png&baseDir=%2F';
diff --git a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
index 2d02828d57..7f096f7dff 100644
--- a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
+++ b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
@@ -15,6 +15,36 @@ describe('mobile message media thumbnail wiring', () => {
const rendererSource = readTextLf(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
const screenSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+ it('seeds restored outbox identities before visible rows and authoritative queue captures', () => {
+ const pendingItems = screenSource.slice(
+ screenSource.indexOf('const pendingSendItems = useMemo('),
+ screenSource.indexOf('const messageListItems = useMemo('),
+ );
+ const seed = pendingItems.indexOf('rememberOutboxImagePreviews(');
+ expect(seed).toBeGreaterThan(-1);
+ expect(pendingItems).toContain('for (const item of outboxItems)');
+ expect(seed).toBeLessThan(pendingItems.indexOf('rememberSentAttachmentPreviews(item.clientId'));
+ expect(seed).toBeLessThan(pendingItems.indexOf('return buildPendingSendItems('));
+ });
+
+ it('captures remote and settling queue identities before building their visible rows, without requesting pixels', () => {
+ const pendingItems = screenSource.slice(
+ screenSource.indexOf('const livePendingSendClientIds = useMemo('),
+ screenSource.indexOf('const messageListItems = useMemo('),
+ );
+ expect(pendingItems).toContain('for (const item of [...settlingItemsForRender, ...inputProjection.pendingQueue])');
+ const capture = pendingItems.indexOf('rememberSentAttachmentPreviews(item.clientId, item.files ?? [], () => null)');
+ expect(capture).toBeGreaterThan(-1);
+ expect(capture).toBeLessThan(pendingItems.indexOf('return buildPendingSendItems('));
+ expect(pendingItems).toContain('...settlingItemsForRender, ...inputProjection.pendingQueue, ...outboxDisplayItems,');
+ const pruning = pendingItems.indexOf('pruneSentMessageImagePreviews(sentImagePreviewsRef.current, sessionId, livePendingSendClientIds, liveImagePreviewClientIdsRef.current)');
+ expect(pruning).toBeGreaterThan(-1);
+ expect(pruning).toBeLessThan(capture);
+ expect(screenSource).toContain('previewOf, galleryKeyOf, liveImagePreviewClientIdsRef.current)');
+ expect(pendingItems).toContain('new Set([...livePendingSendClientIds].map(pendingSendItemKey))');
+ expect(screenSource).toContain('pendingSendGroupKeys={pendingSendGroupKeys}');
+ });
+
it('threads onResolveRemoteMedia from actions through both media blocks into MediaPreview', () => {
expect(rendererSource).toContain('onResolveRemoteMedia={actions.onResolveRemoteMedia}');
const attachmentStrip = rendererSource.slice(
@@ -132,7 +162,12 @@ describe('mobile message media thumbnail wiring', () => {
it('routes image and video payloads to the fullscreen ImageLightbox instead of the generic modal', () => {
expect(rendererSource).toContain('<ImageLightbox');
- expect(rendererSource).toContain('lightboxImagesForPayload(galleryImages, payload, payloadSourceGroupKey)');
+ expect(rendererSource).toContain('lightboxImages[galleryImageIndexForPayload(lightboxImages, payload)]');
+ expect(rendererSource).toContain('initialImageKey={initialLightboxImage?.key ?? payload.galleryImageKey}');
+ expect(rendererSource).toContain('initialUrl={initialLightboxImage?.url ?? payload.media.url}');
+ expect(rendererSource).toContain('const sourceGroupPresent = listData.some((item) => item.key === payloadSourceGroupKey);');
+ expect(rendererSource).toContain('pendingSendGroupKeys?.has(payloadSourceGroupKey) === true');
+ expect(rendererSource).toContain('lightboxImagesForPayload(galleryImages, payload, payloadSourceGroupKey, prev, sourceGroupPresent, retainPendingSnapshot)');
expect(rendererSource).toContain("const imageLightboxOpen = historyActive && payload?.kind === 'media' && isLightboxMediaKind(payload.media.kind);");
expect(rendererSource).toContain('payload={historyActive ? payload : null}');
expect(rendererSource).toContain('() => (imageLightboxOpen');
@@ -199,6 +234,8 @@ describe('mobile message media thumbnail wiring', () => {
expect(lightboxSource).toContain('onPress={onToggleChrome}');
// lightbox images 引用稳定,父层流式重渲染不空转取件 effect / FlatList
expect(rendererSource).toContain('const lightboxImages = useMemo');
+ // Removing an unreadable thumbnail changes the slot even if visible keys/URLs do not change.
+ expect(rendererSource.includes('p.payload.galleryImageSlot === n.payload.galleryImageSlot')).toBe(true);
// 语义未变时复用上一份数组;关闭回调稳定化,流式期间不重建手势图
expect(rendererSource).toContain('lightboxImagesRef');
expect(rendererSource).toContain('onClose={closePayload}');
diff --git a/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts b/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts
index 57f819316f..439182c349 100644
--- a/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts
+++ b/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from 'vitest';
import {
- getSentMessageImagePreview, rememberSentMessageImagePreviews, type SentMessageImagePreviews,
+ getSentMessageImagePreview, pruneSentMessageImagePreviews, rememberOutboxImagePreviews,
+ rememberSentMessageImagePreviews, type SentMessageImagePreviews,
} from '@/session/sentMessageImagePreviews';
import { buildPendingSendItems } from '@/session/pendingSendItems';
+import { buildOutboxItem, outboxItemWithUpload } from '@/session/sessionOutbox';
import type { QueuedRemoteMessage, RemoteSerializedAttachment } from '@/session/types';
const image = (id: string, name = `${id}.jpg`): RemoteSerializedAttachment => ({
@@ -11,6 +13,42 @@ const image = (id: string, name = `${id}.jpg`): RemoteSerializedAttachment => ({
});
describe('sent image preview handoff', () => {
+ it('seeds restored mixed/partial outbox slots and extends the bridge as uploads finish', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const second = image('b');
+ let item = buildOutboxItem({ sessionId: 's', clientId: 'm', text: '', permissionModeAtSend: 'ask',
+ readyAttachments: [{ ...image('pdf'), category: 'pdf' }, second], readyPreviews: [null, 'file:///durable-b.jpg'],
+ claimedUploads: [{ localId: 'upload', kind: 'image', failed: true, previewUri: 'file:///durable-a.jpg' }] });
+ rememberOutboxImagePreviews(previews, 's', item);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, second.name, second.id))
+ .toMatchObject({ galleryImageKey: 'm-slot-1', uri: 'file:///durable-b.jpg' });
+ item = outboxItemWithUpload(item, 'upload', image('a'));
+ rememberOutboxImagePreviews(previews, 's', item);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 1, 'a.jpg', 'a'))
+ .toMatchObject({ galleryImageKey: 'm-slot-2', uri: 'file:///durable-a.jpg' });
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, second.name, second.id)?.galleryImageKey).toBe('m-slot-1');
+ expect(getSentMessageImagePreview(previews, 'other-session', 'm', 0, second.name, second.id)).toBeUndefined();
+ // A stale local row is captured first; the authoritative queue still replaces its images.
+ rememberSentMessageImagePreviews(previews, 's', 'm', [image('replacement', second.name)], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, second.name, second.id)).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, second.name, 'replacement')?.galleryImageKey).toBeUndefined();
+ });
+
+ it('retains every restored live outbox identity without local image pixels', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const live = new Set(Array.from({ length: 65 }, (_, index) => `restored-${index}`));
+ for (const clientId of live) {
+ const item = buildOutboxItem({ sessionId: 's', clientId, text: '', permissionModeAtSend: 'ask',
+ readyAttachments: [image('a')], claimedUploads: [] });
+ rememberOutboxImagePreviews(previews, 's', item, live);
+ }
+ expect(previews.size).toBe(65);
+ for (const clientId of live) {
+ expect(getSentMessageImagePreview(previews, 's', clientId, 0, 'a.jpg', 'a'))
+ .toMatchObject({ galleryImageKey: `${clientId}-slot-0`, uri: null });
+ }
+ });
+
it('keeps image order through mixed files and host URL materialization, including the formal message', () => {
const previews: SentMessageImagePreviews = new Map();
const files = [image('a'), { ...image('pdf'), category: 'pdf' as const }, image('b')];
@@ -26,7 +64,7 @@ describe('sent image preview handoff', () => {
hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,
steeringClientIds: new Set(), presentationByClientId: new Map(), getImagePreview: getPreview });
expect(pending.thumbs.map((thumb) => [thumb.key, thumb.uri])).toEqual([
- ['message-slot-0', 'file:///a.jpg'], ['message-slot-2', 'file:///b.jpg'],
+ ['message-attachment:a', 'file:///a.jpg'], ['message-attachment:b', 'file:///b.jpg'],
]);
expect(pending.thumbs[0].previewRef).toBe(files[0].url);
// Formal messages have no file ID; the accepted message and image position remain stable.
@@ -53,6 +91,123 @@ describe('sent image preview handoff', () => {
expect(getSentMessageImagePreview(previews, 's', '0', 0, 'a.jpg')).toBeUndefined();
});
+ it('retains all live messages in addition to 64 historical records, then releases departed identities', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const live = new Set(Array.from({ length: 65 }, (_, index) => `live-${index}`));
+ for (const clientId of live) rememberSentMessageImagePreviews(previews, 's', clientId, [image('a')],
+ () => 'file:///local.jpg', () => `${clientId}-slot-0`, live);
+ for (let index = 0; index < 65; index++) rememberSentMessageImagePreviews(previews, 's', `past-${index}`,
+ [image('a')], () => null, undefined, live);
+ expect(previews.size).toBe(129);
+ for (const clientId of live) {
+ expect(getSentMessageImagePreview(previews, 's', clientId, 0, 'a.jpg', 'a'))
+ .toMatchObject({ uri: 'file:///local.jpg', galleryImageKey: `${clientId}-slot-0` });
+ }
+ expect(getSentMessageImagePreview(previews, 's', 'past-0', 0, 'a.jpg', 'a')).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'past-1', 0, 'a.jpg', 'a')).toBeDefined();
+ // A completed/cancelled message stops being protected even if no new image is recorded.
+ const previousLive = new Set(live);
+ live.delete('live-0');
+ pruneSentMessageImagePreviews(previews, 's', live, previousLive);
+ expect(previews.size).toBe(128);
+ // Just completed is recent history: do not lose its identity at the exact formal handoff.
+ expect(getSentMessageImagePreview(previews, 's', 'live-0', 0, 'a.jpg', 'a')?.galleryImageKey).toBe('live-0-slot-0');
+ expect(getSentMessageImagePreview(previews, 's', 'past-1', 0, 'a.jpg', 'a')).toBeUndefined();
+ pruneSentMessageImagePreviews(previews, 's', new Set(), live);
+ expect(previews.size).toBe(64);
+ });
+
+ it('scopes live-message retention to the current session', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ rememberSentMessageImagePreviews(previews, 'other', 'live', [image('a')], () => null);
+ const live = new Set(['live']);
+ rememberSentMessageImagePreviews(previews, 's', 'live', [image('a')], () => null, undefined, live);
+ for (let index = 0; index < 64; index++) rememberSentMessageImagePreviews(previews, 's', `past-${index}`,
+ [image('a')], () => null, undefined, live);
+ expect(getSentMessageImagePreview(previews, 'other', 'live', 0, 'a.jpg', 'a')).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'live', 0, 'a.jpg', 'a')).toBeDefined();
+ expect(previews.size).toBe(65);
+ });
+
+ it('remembers observed queue identity without local pixels and replaces it on remote edits', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const file = image('a');
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, file.id)).toMatchObject({
+ attachmentId: file.id, uri: null, sourceRef: file.url, sha256: file.sha256,
+ });
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, file.sha256)?.attachmentId).toBe(file.id);
+ const replacement = { ...image('b'), name: file.name };
+ rememberSentMessageImagePreviews(previews, 's', 'm', [replacement], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, file.id)).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, file.sha256)).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, replacement.sha256)?.attachmentId).toBe(replacement.id);
+ rememberSentMessageImagePreviews(previews, 's', 'm', [], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, replacement.id)).toBeUndefined();
+ // Text-only queue traffic must not evict image identities from this bounded store.
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => null);
+ for (let n = 0; n < 65; n++) rememberSentMessageImagePreviews(previews, 's', String(n), [], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, file.id)?.attachmentId).toBe(file.id);
+ });
+
+ it('finds an unchanged attachment by ID after a remote edit moves its image index', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const files = [image('a'), image('b')];
+ rememberSentMessageImagePreviews(previews, 's', 'm', files, (file) => `file:///${file.id}.jpg`,
+ (file) => `m-slot-${files.indexOf(file)}`);
+ const moved = getSentMessageImagePreview(previews, 's', 'm', 0, 'b.jpg', 'b');
+ expect(moved).toMatchObject({ attachmentId: 'b', uri: 'file:///b.jpg', galleryImageKey: 'm-slot-1' });
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'b.jpg', 'replacement')).toBeUndefined();
+ // Formal history omits IDs. Reconnect a moved image only after checking its pixels.
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'b.jpg', undefined, files[1].sha256)).toEqual(moved);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'b.jpg', undefined, 'changed')).toBeUndefined();
+ });
+
+ it.each([null, 'file:///original.jpg'])('tracks a materialized queue reference without a hash while retaining preview %s', (uri) => {
+ const previews: SentMessageImagePreviews = new Map();
+ const file = { ...image('a'), sha256: undefined };
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => uri, () => 'm-slot-1');
+ const materialized = { ...file, url: 'cindy-media://blobs/a.jpg' };
+ rememberSentMessageImagePreviews(previews, 's', 'm', [materialized], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, undefined, materialized.url))
+ .toMatchObject({ attachmentId: file.id, sourceRef: uri ? file.url : materialized.url, uri, galleryImageKey: 'm-slot-1' });
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, undefined, 'cindy-media://blobs/replaced.jpg'))
+ .toBeUndefined();
+ // A new attachment ID must not inherit the previous URL bridge or its local pixels.
+ const replacement = { ...file, id: 'replacement', url: 'cindy-media://blobs/replaced.jpg' };
+ rememberSentMessageImagePreviews(previews, 's', 'm', [replacement], () => null);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, undefined, materialized.url)).toBeUndefined();
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, undefined, undefined, replacement.url))
+ .toMatchObject({ attachmentId: replacement.id, uri: null });
+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, file.name, replacement.id)?.galleryImageKey).toBeUndefined();
+ });
+
+ it('does not choose an ambiguous formal image after its position changes', () => {
+ const previews: SentMessageImagePreviews = new Map();
+ const first = image('a', 'same.jpg');
+ rememberSentMessageImagePreviews(previews, 's', 'm', [first, { ...first, id: 'b' }], () => 'file:///same.jpg',
+ (file) => `key-${file.id}`);
+ expect(getSentMessageImagePreview(previews, 's', 'm', 2, 'same.jpg', undefined, first.sha256)).toBeUndefined();
+ });
+
+ it.each([null, 'file:///durable.jpg'])('retains outbox identity with preview %s and rejects a real replacement', (uri) => {
+ const previews: SentMessageImagePreviews = new Map();
+ const file = image('a');
+ const key = 'm-slot-2';
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => uri, () => key);
+ const getPreview = (id: string) => getSentMessageImagePreview(previews, 's', 'm', 0, file.name, id);
+ expect(getPreview(file.id)).toMatchObject({ uri, galleryImageKey: key });
+ // A text-only edit may refresh the URI or lack a new local preview.
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => 'file:///refreshed.jpg');
+ expect(getPreview(file.id)).toMatchObject({ uri: 'file:///refreshed.jpg', galleryImageKey: key });
+ rememberSentMessageImagePreviews(previews, 's', 'm', [file], () => null);
+ expect(getPreview(file.id)?.galleryImageKey).toBe(key);
+ const replacement = { ...file, id: 'replacement' };
+ expect(getPreview(replacement.id)).toBeUndefined();
+ rememberSentMessageImagePreviews(previews, 's', 'm', [replacement], () => 'file:///new.jpg');
+ expect(getPreview(replacement.id)?.galleryImageKey).toBeUndefined();
+ });
+
it('preserves previews on text-only edits and matches the persisted original name', () => {
const previews: SentMessageImagePreviews = new Map();
const attachment = { ...image('a', 'upload.jpg'), originalName: 'photo.jpg' };
diff --git a/apps/mobile/src/session/ImageLightbox.tsx b/apps/mobile/src/session/ImageLightbox.tsx
index f272192b37..e2271d02d9 100644
--- a/apps/mobile/src/session/ImageLightbox.tsx
+++ b/apps/mobile/src/session/ImageLightbox.tsx
@@ -17,7 +17,7 @@
*/
import { useNavigation } from 'expo-router';
import { Image } from 'expo-image';
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
ActivityIndicator,
@@ -174,6 +174,8 @@ export interface ImageLightboxAnnotationConfig {
export interface ImageLightboxProps {
images: readonly MobileMessageGalleryImage[];
initialUrl: string;
+ /** Same-content attachment slots can share a URL; prefer the clicked attachment's identity. */
+ initialImageKey?: string;
onClose(): void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
/** 关闭时逐出本次取过的视频(与通用查看器一致;图片缩略图常驻列表不逐出)。 */
@@ -213,6 +215,7 @@ export interface ImageLightboxProps {
export const ImageLightbox = memo(function ImageLightbox({
images,
initialUrl,
+ initialImageKey,
onClose,
onResolveRemoteMedia,
onReleaseRemoteMedia,
@@ -226,7 +229,41 @@ export const ImageLightbox = memo(function ImageLightbox({
const { width, height } = useWindowDimensions();
const insets = useSafeAreaInsets();
const urls = useMemo(() => images.map((image) => image.url), [images]);
- const [activeIndex, setActiveIndex] = useState(() => lightboxInitialIndex(urls, initialUrl));
+ const initialKeyIndex = initialImageKey ? images.findIndex((image) => image.key === initialImageKey) : -1;
+ const initialIndex = initialKeyIndex >= 0 ? initialKeyIndex : lightboxInitialIndex(urls, initialUrl);
+ const [activePage, setActivePage] = useState(() => {
+ const image = images[initialIndex];
+ return { key: image?.key, url: image?.url, galleryImageKey: image?.payload.galleryImageKey,
+ galleryImageSlot: image?.payload.galleryImageSlot, index: initialIndex };
+ });
+ // 地址升级或相邻附件就绪时,页码跟随图片身份,不跟随旧数组下标。
+ // 普通消息在流式工作组收尾时会换 key,仍按原地址找回;删除当前页才钳制下标。
+ const keyIndex = images.findIndex((image) => image.key === activePage.key);
+ // Replacement and earlier uploads can settle in one render. Preserve the thumbnail slot,
+ // not the old readable-page index, when the active attachment identity disappears.
+ const slotIndex = keyIndex < 0 && activePage.galleryImageKey && activePage.galleryImageSlot !== undefined
+ ? images.findIndex((image) => image.payload.galleryImageSlot === activePage.galleryImageSlot) : -1;
+ // Stable attachment keys distinguish duplicate URLs. A missing key means replacement/removal;
+ // URL fallback is only for ordinary message pages whose render keys can be rebuilt.
+ const urlIndex = keyIndex < 0 && !activePage.galleryImageKey
+ ? images.findIndex((image) => image.url === activePage.url) : -1;
+ const activeIndex = keyIndex >= 0 ? keyIndex : slotIndex >= 0 ? slotIndex : urlIndex >= 0 ? urlIndex
+ : Math.max(0, Math.min(activePage.index, images.length - 1));
+ const activePageKey = images[activeIndex]?.key;
+ const activePageUrl = images[activeIndex]?.url;
+ const activeGalleryImageKey = images[activeIndex]?.payload.galleryImageKey;
+ const activeGalleryImageSlot = images[activeIndex]?.payload.galleryImageSlot;
+ // 记住这次实际显示的身份与位置;换图或钳制后,后续更新继续跟随新图,不能找回旧图。
+ useLayoutEffect(() => {
+ if (activePageKey === undefined || activePageUrl === undefined) return;
+ setActivePage((previous) => previous.key === activePageKey
+ && previous.url === activePageUrl && previous.index === activeIndex
+ && previous.galleryImageKey === activeGalleryImageKey
+ && previous.galleryImageSlot === activeGalleryImageSlot
+ ? previous
+ : { key: activePageKey, url: activePageUrl, galleryImageKey: activeGalleryImageKey,
+ galleryImageSlot: activeGalleryImageSlot, index: activeIndex });
+ }, [activePageKey, activePageUrl, activeGalleryImageKey, activeGalleryImageSlot, activeIndex]);
const [zoomed, setZoomed] = useState(false);
/** 捏合/平移进行中 chrome 不接收触摸,避免底栏抢走双指。 */
const [chromeInteractive, setChromeInteractive] = useState(true);
@@ -259,6 +296,9 @@ export const ImageLightbox = memo(function ImageLightbox({
const [sharing, setSharing] = useState(false);
const onCloseRef = useRef(onClose);
onCloseRef.current = onClose;
+ useEffect(() => {
+ if (images.length === 0) onCloseRef.current();
+ }, [images.length]);
const [strokes, setStrokes] = useState<AnnotationStroke[]>([]);
// 取消 / 返回回调经 ref 读最新笔迹与文案:它们进入手势 deps(onRequestClose),
// 不能因每次作画 / 父层重渲染而让整张手势图重建。
@@ -285,15 +325,15 @@ export const ImageLightbox = memo(function ImageLightbox({
});
}, []);
- // 打开/翻页时装载该页既有笔迹(托盘再编辑);标注模式中禁翻页,不会中途换页。
- // 依赖「活跃图 key」而非 images 数组引用:父层因附件上传落定 / 流式回复等
- // 原因重建图集(语义未变)时,不能把用户正在画的笔迹重置掉(review P1);
+ // 打开/换图时装载该图既有笔迹(托盘再编辑),标注模式中禁用手动翻页。
+ // 只依赖「活跃图 key」,不依赖数组引用或页码:附件就绪可能让同一张图前移/后移,
+ // 不能因此重置已画笔迹或正在画的一笔;
// 真正换图(翻页 / 打开另一张)时 key 变化,照常重载。images 经 ref 读最新。
const activeImageKeyForStrokes = images[activeIndex]?.key ?? null;
const imagesRef = useRef(images);
imagesRef.current = images;
useEffect(() => {
- const image = imagesRef.current[activeIndex];
+ const image = imagesRef.current.find((entry) => entry.key === activeImageKeyForStrokes);
const initial = image ? annotation?.initialStrokesFor?.(image) : undefined;
setStrokes(initial ? [...initial] : []);
draftStrokeRef.current = null;
@@ -302,7 +342,7 @@ export const ImageLightbox = memo(function ImageLightbox({
setDraftStroke(null);
// annotation 语义上只在打开时取一次快照,翻页时按新页(key)重取
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeIndex, activeImageKeyForStrokes]);
+ }, [activeImageKeyForStrokes]);
/**
* 画笔落点(容器坐标 + 当页 transform 状态,LightboxPage 手势经 runOnJS 上抛)。
@@ -433,13 +473,10 @@ export const ImageLightbox = memo(function ImageLightbox({
const imageErrorRetryUsedRef = useRef<Set<string>>(new Set());
const listRef = useRef<FlatList<MobileMessageGalleryImage>>(null);
- // 旋转(宽度变化)时按 activeIndex 重锚:FlatList 保留的是旧宽度下的像素
- // contentOffset,不重锚会让可见页与页码 / 分享目标错位。
+ // 旋转或图集变动导致页码变化时重锚,保持画面、页码和分享目标一致。
useEffect(() => {
listRef.current?.scrollToOffset({ animated: false, offset: activeIndex * width });
- // activeIndex 不进依赖:翻页由手势滚动驱动,这里只响应宽度突变
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [width]);
+ }, [activeIndex, width]);
const resolveImage = useCallback((
image: MobileMessageGalleryImage,
@@ -577,15 +614,18 @@ export const ImageLightbox = memo(function ImageLightbox({
}));
const activeUri = activeImage ? displayUriFor(activeImage) : null;
+ // Expo can display library handles, but sharing/annotation need the file or remote
+ // original supplied later by the existing upload pipeline. Do not enable dead-end actions.
+ const activeActionsReady = !!activeUri && !/^(?:ph|content|assets-library):\/\//.test(activeUri);
const pageLabel = lightboxPageLabel(activeIndex, images.length);
// 工具栏从打开那一刻就在:原图还在取件时先置灰,就绪即可用,不让工具「晚到」。
// 取件结果是 data: 等不可分享地址时才收起分享。
const shareVisible = !!onShareImage && !!activeImage && !activeIsVideo
&& (!activeUri || canShareLightboxImage(activeUri));
- const shareEnabled = shareVisible && !!activeUri;
+ const shareEnabled = shareVisible && activeActionsReady;
const handleShare = useCallback(() => {
- if (!activeImage || !activeUri || !onShareImage || sharingRef.current || submittingRef.current) return;
+ if (!activeImage || !activeUri || !activeActionsReady || !onShareImage || sharingRef.current || submittingRef.current) return;
const state = resolveMap[activeImage.url];
const mimeType = (state?.status === 'ready' ? state.media.mimeType : undefined)
?? activeImage.payload.media.mimeType;
@@ -603,7 +643,7 @@ export const ImageLightbox = memo(function ImageLightbox({
sharingRef.current = false;
setSharing(false);
});
- }, [activeImage, activeUri, onShareImage, resolveMap]);
+ }, [activeImage, activeUri, activeActionsReady, onShareImage, resolveMap]);
// 活跃页 MIME:取件结果优先,保留附件已知类型,最后兜底 URI 后缀。
const activeResolveState = activeImage ? resolveMap[activeImage.url] : undefined;
@@ -623,7 +663,7 @@ export const ImageLightbox = memo(function ImageLightbox({
// 画笔要等图片自然尺寸就位(坐标换算基准),否则进入标注后作画静默无效:
// 此前按钮置灰禁用,与撤销的禁用态同观感。宿主给出暂不可标注的原因时,按钮
// 同样置灰但可点,点按说明原因(否则用户不知道为什么不能画)。
- const annotateReady = annotateVisible && !!activeUri && !!activeNaturalSize;
+ const annotateReady = annotateVisible && activeActionsReady && !!activeNaturalSize;
const annotateBlockedReason = annotateReady && activeImage
? annotation?.annotationBlockedReason?.(activeImage)
: undefined;
@@ -640,10 +680,10 @@ export const ImageLightbox = memo(function ImageLightbox({
}, [annotateReady, activeImage, annotation, t]);
// 独立直发(发送到对话):不要求可标注——gif 等不可画的图同样能转发。
const directSubmitVisible = !!annotation?.allowDirectSubmit && !!activeImage && !activeIsVideo;
- const directSubmitEnabled = directSubmitVisible && !!activeUri;
+ const directSubmitEnabled = directSubmitVisible && activeActionsReady;
const handleSubmitAnnotation = useCallback(() => {
- if (!annotation || !activeImage || !activeUri || submittingRef.current || sharingRef.current) return;
+ if (!annotation || !activeImage || !activeUri || !activeActionsReady || submittingRef.current || sharingRef.current) return;
submittingRef.current = true;
setAnnotationSubmitting(true);
// 点击提交时另一根手指可能还在画,把屏幕上最后一笔也纳入同一快照。
@@ -668,7 +708,7 @@ export const ImageLightbox = memo(function ImageLightbox({
submittingRef.current = false;
setAnnotationSubmitting(false);
});
- }, [annotation, activeImage, activeUri, activeMimeType, activeNaturalSize, strokes]);
+ }, [annotation, activeImage, activeUri, activeActionsReady, activeMimeType, activeNaturalSize, strokes]);
// Android 物理返回键触发 Modal.onRequestClose,不受手势层/按钮层的
// isAnnotating 禁用覆盖(review 发现:会绕开"标注模式中关闭均禁用"保护
@@ -717,11 +757,13 @@ export const ImageLightbox = memo(function ImageLightbox({
decelerationRate="fast"
getItemLayout={(_, index) => ({ length: width, offset: width * index, index })}
horizontal
- initialScrollIndex={lightboxInitialIndex(urls, initialUrl)}
+ initialScrollIndex={initialIndex}
keyExtractor={(image) => image.key}
onMomentumScrollEnd={(event) => {
const index = lightboxPageIndex(event.nativeEvent.contentOffset.x, width, images.length);
- setActiveIndex(index);
+ const image = images[index];
+ setActivePage({ key: image?.key, url: image?.url, galleryImageKey: image?.payload.galleryImageKey,
+ galleryImageSlot: image?.payload.galleryImageSlot, index });
}}
pagingEnabled
ref={listRef}
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 873a55b42c..3086c64561 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -180,6 +180,7 @@ import {
} from '@/session/userMessageCollapse';
import {
collectMobileMessageGalleryImages,
+ galleryImageIndexForPayload,
isLightboxMediaKind,
lightboxImagesForPayload,
type MobileMessageGalleryImage,
@@ -760,6 +761,7 @@ export function MessageRenderer({
shareSelectionBusy,
onQuoteSelection,
pendingSend,
+ pendingSendGroupKeys,
getSentImagePreview,
onReadTextFilePreview,
onReleaseRemoteMedia,
@@ -808,6 +810,8 @@ export function MessageRenderer({
focusedRequestKey?: number | string | null;
followLatestRequestKey?: number | string | null;
items: readonly MobileMessageRenderItem[];
+ /** Live outbox, queued and settling rows; an absent source cannot retain its viewer forever. */
+ pendingSendGroupKeys?: ReadonlySet<string>;
/** Stable while streaming only changes row content; structural list derivations key off this. */
itemsStructureKey?: unknown;
/** Oldest loaded host cursor; synthetic cards must not mask successful history prepends. */
@@ -1708,22 +1712,31 @@ export function MessageRenderer({
// 避免取件 effect / FlatList / LightboxPage memo 每帧全部失效。
const lightboxImagesRef = useRef<readonly MobileMessageGalleryImage[] | null>(null);
const lightboxImages = useMemo(() => {
- if (!(payload?.kind === 'media' && isLightboxMediaKind(payload.media.kind)) || !galleryImages) return null;
- const next = lightboxImagesForPayload(galleryImages, payload, payloadSourceGroupKey);
+ if (!(payload?.kind === 'media' && isLightboxMediaKind(payload.media.kind)) || !galleryImages) {
+ lightboxImagesRef.current = null;
+ return null;
+ }
const prev = lightboxImagesRef.current;
+ const sourceGroupPresent = listData.some((item) => item.key === payloadSourceGroupKey);
+ const retainPendingSnapshot = !!payloadSourceGroupKey && pendingSendGroupKeys?.has(payloadSourceGroupKey) === true;
+ const next = lightboxImagesForPayload(galleryImages, payload, payloadSourceGroupKey, prev, sourceGroupPresent, retainPendingSnapshot);
if (prev && prev.length === next.length && prev.every((p, i) => {
const n = next[i];
return p.key === n.key
&& p.url === n.url
&& p.payload.media.url === n.payload.media.url
&& p.payload.media.previewable === n.payload.media.previewable
+ && p.payload.galleryImageSlot === n.payload.galleryImageSlot
&& p.previewUri === n.previewUri;
})) {
return prev;
}
lightboxImagesRef.current = next;
return next;
- }, [galleryImages, imageLightboxOpen, payload, payloadSourceGroupKey]);
+ }, [galleryImages, imageLightboxOpen, listData, payload, payloadSourceGroupKey, pendingSendGroupKeys]);
+ const initialLightboxImage = lightboxImages
+ ? lightboxImages[galleryImageIndexForPayload(lightboxImages, payload)]
+ : undefined;
const bottomPadding = mobileMessageListBottomPadding(bottomOverlayHeight, contentBottomInset);
const topPadding = mobileMessageListTopPadding(topOverlayHeight);
listBottomPaddingRef.current = bottomPadding;
@@ -2904,7 +2917,8 @@ export function MessageRenderer({
<ImageLightbox
annotation={imageAnnotation}
images={lightboxImages}
- initialUrl={payload.media.url}
+ initialImageKey={initialLightboxImage?.key ?? payload.galleryImageKey}
+ initialUrl={initialLightboxImage?.url ?? payload.media.url}
onClose={closePayload}
onReleaseRemoteMedia={onReleaseRemoteMedia}
onResolveRemoteMedia={onResolveRemoteMedia}
@@ -3035,6 +3049,7 @@ const RenderItemView = memo(function RenderItemView({
<PendingSendBubble
actions={actions.pendingSend}
item={item}
+ onOpenImage={actions.onOpenPayload}
screenWidth={actions.screenWidth}
viewerDeviceId={actions.viewerDeviceId}
renderImage={(uri, sourceUri, onError) => uri ? (
diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsx
index ee951bd9d0..9bbc87ac4c 100644
--- a/apps/mobile/src/session/PendingSendBubble.tsx
+++ b/apps/mobile/src/session/PendingSendBubble.tsx
@@ -56,6 +56,8 @@ import {
type ResolveRemoteMediaFn,
} from '@/session/remoteMedia';
import type { MobileOutboxThumb } from '@/session/sessionOutbox';
+import type { MessagePayload } from '@/session/messagePayload';
+import { pendingSendGalleryImage } from '@/session/pendingSendImages';
import {
fontWeight,
iconSize,
@@ -157,28 +159,45 @@ function useThumbCellUri(
function ThumbCell({
thumb,
+ slot,
resolveRemoteMedia,
renderImage,
+ onOpenImage,
}: {
renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;
thumb: MobileOutboxThumb;
+ slot: number;
resolveRemoteMedia?: ResolveRemoteMediaFn;
+ onOpenImage?: (payload: MessagePayload) => void;
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const [failedUris, setFailedUris] = useState<readonly string[]>([]);
const uri = useThumbCellUri(thumb, resolveRemoteMedia, failedUris);
+ const image = pendingSendGalleryImage(thumb, uri, slot);
+ const canOpen = !!image && !!onOpenImage;
return (
- <View style={styles.thumbCell}>
+ <Pressable
+ accessibilityLabel={image?.title}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: !canOpen }}
+ disabled={!canOpen}
+ onPress={(event) => {
+ event.stopPropagation();
+ if (image) onOpenImage?.(image.payload);
+ }}
+ style={styles.thumbCell}
+ testID={`pendingSend.image.${thumb.key}`}
+ >
{renderImage(uri, thumb.uri, () => {
if (uri) setFailedUris((failed) => failed.includes(uri) ? failed : [...failed, uri]);
})}
{thumb.uploading ? (
- <View style={styles.thumbUploadingOverlay}>
+ <View pointerEvents="none" style={styles.thumbUploadingOverlay}>
<ActivityIndicator color={colors.ctaText} size="small" />
</View>
) : null}
- </View>
+ </Pressable>
);
}
@@ -187,19 +206,22 @@ function AttachmentThumbStrip({
resolveRemoteMedia,
renderImage,
gap,
+ onOpenImage,
}: {
renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;
gap: number;
thumbs: readonly MobileOutboxThumb[];
resolveRemoteMedia?: ResolveRemoteMediaFn;
+ onOpenImage?: (payload: MessagePayload) => void;
}) {
const styles = useThemedStyles(makeStyles);
useSentAttachmentThumbsVersion();
if (thumbs.length === 0) return null;
return (
<View style={[styles.thumbStrip, { gap }]} testID="pendingSend.thumbStrip">
- {thumbs.map((thumb) => (
- <ThumbCell renderImage={renderImage} key={thumb.key} resolveRemoteMedia={resolveRemoteMedia} thumb={thumb} />
+ {thumbs.map((thumb, slot) => (
+ <ThumbCell renderImage={renderImage} key={thumb.key} resolveRemoteMedia={resolveRemoteMedia}
+ thumb={thumb} slot={slot} onOpenImage={onOpenImage} />
))}
</View>
);
@@ -214,6 +236,7 @@ export function PendingSendBubble({
renderFile,
screenWidth,
viewerDeviceId,
+ onOpenImage,
}: {
/** 当前查看设备:排队消息就是本机发的时不显示设备标签(与已发送消息同一规则)。 */
viewerDeviceId?: string | null;
@@ -225,6 +248,7 @@ export function PendingSendBubble({
actions: PendingSendBubbleActions;
/** 远端媒体取件(粘贴时已上传到媒体总仓的图靠它取缩略图)。 */
resolveRemoteMedia?: ResolveRemoteMediaFn;
+ onOpenImage?: (payload: MessagePayload) => void;
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -409,6 +433,7 @@ export function PendingSendBubble({
<View key={`attachments:${item.clientId}`} onLayout={measureBadgeAnchor} style={[styles.attachmentStrip, { gap: layout.attachmentGap }]}>
<AttachmentThumbStrip
gap={layout.attachmentGap}
+ onOpenImage={onOpenImage}
renderImage={renderImage}
resolveRemoteMedia={resolveRemoteMedia}
thumbs={item.thumbs}
diff --git a/apps/mobile/src/session/messageGallery.ts b/apps/mobile/src/session/messageGallery.ts
index 05a3154f6b..13a4786626 100644
--- a/apps/mobile/src/session/messageGallery.ts
+++ b/apps/mobile/src/session/messageGallery.ts
@@ -10,9 +10,10 @@ import { buildAttachmentPayload, buildMediaPayload, payloadMediaKindLabel } from
import type { MobileMessageRenderItem, MobileWorkChildItem } from '@/session/messageRenderModel';
import { logUnhandledRenderItem } from '@/session/assertNever';
import { applySentAttachmentThumbOverlay, getSentAttachmentThumbUri } from '@/session/sentAttachmentThumbStore';
-import type { GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';
+import { sentImageGalleryKey, type GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';
import { i18n } from '@/i18n';
import { svgAttachmentForDisplay } from '@/session/messageAttachments';
+import { pendingSendGalleryImage } from '@/session/pendingSendImages';
/**
* 全屏查看器的一页:图片或视频(同一条消息里的图片与视频可连续横滑;名字沿用
@@ -66,9 +67,12 @@ export function collectMobileMessageGalleryImages(
) => {
const url = payload.media.url.trim();
if (!url || !isLightboxMediaKind(payload.media.kind)) return;
- const dedupeKey = `${currentGroupKey}::${url}`;
+ // 待发送的两个附件可能物化到同一个内容地址,仍须与两个可点击缩略图逐槽对应。
+ const dedupeKey = `${currentGroupKey}::${payload.galleryImageKey ? `slot:${payload.galleryImageKey}` : `url:${url}`}`;
if (seenUrls.has(dedupeKey)) return;
seenUrls.add(dedupeKey);
+ // Distinct attachment identities remain separate pages; body references to their URL still dedupe.
+ seenUrls.add(`${currentGroupKey}::url:${url}`);
images.push({ key, title, url, payload, groupKey: currentGroupKey, ...(previewUri ? { previewUri } : {}) });
};
@@ -104,7 +108,13 @@ export function collectMobileMessageGalleryImages(
const previewUri = attachment.kind === 'image' && displayAttachment.uri
? getSentAttachmentThumbUri(localPreview?.sourceRef ?? displayAttachment.uri) ?? localPreview?.uri
: null;
- push(`${keyPrefix}:attachment:${index}`, attachment.name, payload, previewUri);
+ // The verified send snapshot bridges outbox/queue keys to formal history, even when
+ // an earlier unreadable upload first enters the gallery at this exact handoff.
+ const galleryImageKey = localPreview && clientId
+ ? localPreview.galleryImageKey ?? sentImageGalleryKey(clientId, localPreview.attachmentId)
+ : undefined;
+ push(galleryImageKey ?? `${keyPrefix}:attachment:${index}`, attachment.name,
+ galleryImageKey ? { ...payload, galleryImageKey } : payload, previewUri);
});
message.media?.forEach((media, index) => pushMedia(media, `${keyPrefix}:media:${index}`));
// 正文 Markdown 图片(![](url) / 安全 <img>)也纳入图集,点开后可与附件图片一起横滑翻页。
@@ -187,8 +197,10 @@ export function collectMobileMessageGalleryImages(
// fork 来源标记只含导航 UI,no-op。
break;
case 'pending_send':
- // 待发送气泡:附件还是 `cindy-oss-attach://` 中转引用 / 本地预览,不是可供
- // lightbox 分页的正式媒体;等消息回流后由 message 路径入图集。
+ item.thumbs.forEach((thumb, slot) => {
+ const image = pendingSendGalleryImage(thumb, undefined, slot);
+ if (image) push(image.key, image.title, image.payload, image.previewUri);
+ });
break;
default:
// 穷尽性保证:新增 render-item 变体会被 typecheck 拦下(入参 never)。运行时降级为 log+skip
@@ -210,6 +222,13 @@ export function galleryImageIndexForPayload(
payload: MessagePayload | null,
): number {
if (!payload || payload.kind !== 'media' || !isLightboxMediaKind(payload.media.kind)) return -1;
+ if (payload.galleryImageKey) {
+ const identityIndex = images.findIndex((image) => image.key === payload.galleryImageKey);
+ if (identityIndex >= 0 || payload.galleryImageSlot === undefined) return identityIndex;
+ // The selected message's slot can be replaced between the press and viewer mount.
+ // Count placeholders too; readable-page indices can change while uploads settle.
+ return images.findIndex((image) => image.payload.galleryImageSlot === payload.galleryImageSlot);
+ }
const url = payload.media.url.trim();
if (!url) return -1;
return images.findIndex((image) => image.url === url);
@@ -230,9 +249,21 @@ export function lightboxImagesForPayload(
images: readonly MobileMessageGalleryImage[],
payload: Extract<MessagePayload, { kind: 'media' }>,
sourceGroupKey?: string | null,
+ previousImages?: readonly MobileMessageGalleryImage[] | null,
+ sourceGroupPresent = false,
+ retainPendingSnapshot = false,
): MobileMessageGalleryImage[] {
+ // 待发送消息仍在时跟随该消息的当前图集:编辑可替换最初点开的附件身份。
+ if (payload.galleryImageKey && sourceGroupKey) {
+ const currentGroup = images.filter((image) => image.groupKey === sourceGroupKey);
+ // A present row with no readable images is an edit, not a row handoff. Never revive its old payload.
+ if (currentGroup.length > 0 || sourceGroupPresent) return currentGroup;
+ }
const url = payload.media.url.trim();
- const matches = url ? images.filter((image) => image.url === url) : [];
+ // 待发送附件的临时文件、持久副本、远端原图地址会变化,匹配应跟随附件身份。
+ const matches = images.filter((image) => payload.galleryImageKey
+ ? image.key === payload.galleryImageKey
+ : !!url && image.url === url);
if (matches.length > 0) {
if (sourceGroupKey && matches.some((image) => image.groupKey === sourceGroupKey)) {
return images.filter((image) => image.groupKey === sourceGroupKey);
@@ -244,6 +275,16 @@ export function lightboxImagesForPayload(
return images.filter((image) => image.groupKey === groupKey);
}
}
+ // Only a live outbox/queue/settling item may bridge a temporary gap in formal history.
+ // Canceled rows and expired settling items must not revive their original payload.
+ if (payload.galleryImageKey && !retainPendingSnapshot) return [];
+ // 最初点开的附件可能已被编辑替换,因此有来源时按消息归属保留最新快照。
+ if (payload.galleryImageKey && previousImages) {
+ const previousGroup = previousImages.filter((image) => sourceGroupKey
+ ? image.groupKey === sourceGroupKey
+ : image.key === payload.galleryImageKey);
+ if (previousGroup.length > 0) return sourceGroupKey ? previousGroup : [...previousImages];
+ }
return [{
key: 'lightbox:payload',
title: payload.title,
diff --git a/apps/mobile/src/session/messagePayload.ts b/apps/mobile/src/session/messagePayload.ts
index 6814cdd540..ba55e3d3fd 100644
--- a/apps/mobile/src/session/messagePayload.ts
+++ b/apps/mobile/src/session/messagePayload.ts
@@ -41,7 +41,12 @@ import {
import { i18n } from '@/i18n';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
-export type MessagePayload = SharedMessagePayload<NormalizedToolDiff, NormalizedToolMedia>;
+export type MessagePayload = SharedMessagePayload<NormalizedToolDiff, NormalizedToolMedia> & {
+ /** Mobile 查看器内的附件身份,不参与跨端传输;地址变化时仍能定位同一页。 */
+ galleryImageKey?: string;
+ /** 待发送图片条中的位置(含未就绪格),仅在打开前附件被替换、身份失效时兜底。 */
+ galleryImageSlot?: number;
+};
export {
buildPayloadToolDiff,
diff --git a/apps/mobile/src/session/pendingSendImages.ts b/apps/mobile/src/session/pendingSendImages.ts
new file mode 100644
index 0000000000..8f9223ce05
--- /dev/null
+++ b/apps/mobile/src/session/pendingSendImages.ts
@@ -0,0 +1,40 @@
+import { i18n } from '@/i18n';
+import type { MobileMessageGalleryImage } from '@/session/messageGallery';
+import { buildMediaPayload } from '@/session/messagePayload';
+import { isDesktopLocalMediaUrl, isDirectPreviewableMediaUrl } from '@/session/remoteMedia';
+import { getSentAttachmentThumbUri } from '@/session/sentAttachmentThumbStore';
+import type { MobileOutboxThumb } from '@/session/sessionOutbox';
+
+/** Stable slot identity connects the button and gallery while preview/original URLs settle. */
+export function pendingSendGalleryImage(
+ thumb: MobileOutboxThumb,
+ displayedUri?: string | null,
+ slot?: number,
+): MobileMessageGalleryImage | null {
+ const previewRef = thumb.previewRef ?? thumb.ossRef;
+ const previewUri = displayedUri === undefined
+ ? (previewRef ? getSentAttachmentThumbUri(previewRef) : null) ?? thumb.uri
+ : displayedUri;
+ // A materialized host reference opens the original through the existing resolver.
+ // OSS upload references are lookup keys, never image URLs for the native viewer.
+ const remoteUrl = isDesktopLocalMediaUrl(thumb.ossRef) || isDirectPreviewableMediaUrl(thumb.ossRef)
+ ? thumb.ossRef : null;
+ const localUrl = previewUri && (
+ isDirectPreviewableMediaUrl(previewUri)
+ || /^(?:file|ph|content|assets-library):\/\//.test(previewUri)
+ ) ? previewUri : null;
+ const url = remoteUrl ?? localUrl;
+ if (!url) return null;
+ const title = i18n.t('message.renderer.imageFallbackTitle');
+ return {
+ key: thumb.key,
+ title,
+ url,
+ payload: {
+ ...buildMediaPayload({ kind: 'image', url, previewable: !isDesktopLocalMediaUrl(url) }, title),
+ galleryImageKey: thumb.key,
+ galleryImageSlot: slot,
+ },
+ ...(localUrl ? { previewUri: localUrl } : {}),
+ };
+}
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index 51cb043219..a905cfac40 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -35,7 +35,7 @@ import {
type SentInlineToken,
} from '@/session/sentMessageAtoms';
import type { QueuedRemoteMessage } from '@/session/types';
-import type { GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';
+import { sentImageGalleryKey, type GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';
import type { MobileMessageRenderItem } from '@/session/messageRenderModel';
import {
automationOriginLabel,
@@ -324,7 +324,7 @@ function queuedAttachmentThumbs(
): { thumbs: MobileOutboxThumb[]; fileCount: number } {
const thumbs: MobileOutboxThumb[] = [];
let fileCount = 0;
- (item.files ?? []).forEach((file, index) => {
+ (item.files ?? []).forEach((file) => {
if (file.category !== 'image') {
fileCount += 1;
return;
@@ -332,7 +332,8 @@ function queuedAttachmentThumbs(
const ossRef = file.url ?? file.path;
const preview = getImagePreview?.(item.clientId, thumbs.length, file.name, file.id);
thumbs.push({
- key: `${item.clientId}-slot-${index}`,
+ // URLs may settle for one attachment; editing the slot to another must reset its viewer state.
+ key: preview?.galleryImageKey ?? sentImageGalleryKey(item.clientId, file.id),
// 发送时刻抓下的本地预览优先:sentAttachmentThumbStore 那条兜底链要等「上传落定 →
// 拷进自有目录 → AsyncStorage hydrate」全部完成才查得到,期间 getSentAttachmentThumbUri
// 一律返回 null,排队气泡只能画空占位格(实测:兜底文件已生成,气泡仍是空方块)。
diff --git a/apps/mobile/src/session/sentMessageImagePreviews.ts b/apps/mobile/src/session/sentMessageImagePreviews.ts
index c41c65310a..40f77e3fbe 100644
--- a/apps/mobile/src/session/sentMessageImagePreviews.ts
+++ b/apps/mobile/src/session/sentMessageImagePreviews.ts
@@ -1,11 +1,16 @@
import type { RemoteSerializedAttachment } from '@/session/types';
+import { outboxItemAttachments, type MobileOutboxItem } from '@/session/sessionOutbox';
export interface SentMessageImagePreview {
attachmentId: string;
name: string;
+ /** Reference used to find the retained local thumbnail. */
sourceRef: string;
+ /** Latest reference observed under this attachment ID, including host materialization. */
+ currentSourceRef?: string;
sha256?: string;
- uri: string;
+ uri: string | null;
+ galleryImageKey?: string;
}
export type SentMessageImagePreviews = Map<string, readonly (SentMessageImagePreview | null)[]>;
@@ -15,26 +20,81 @@ export type GetSentMessageImagePreview = (
const messageKey = (sessionId: string, clientId: string) => JSON.stringify([sessionId, clientId]);
-/** Presentation-only snapshot. Host materialization changes URLs, but preserves message/image order. */
+/** Known attachments keep their identity when a queue edit changes their position. */
+export const sentImageGalleryKey = (clientId: string, attachmentId: string): string => `${clientId}-attachment:${attachmentId}`;
+
+/** Live sends retain their identity; only departed messages count toward the history budget. */
+export function pruneSentMessageImagePreviews(
+ previews: SentMessageImagePreviews,
+ sessionId: string,
+ liveClientIds: ReadonlySet<string> = new Set(),
+ previousLiveClientIds: ReadonlySet<string> = liveClientIds,
+): void {
+ // A freshly handed-off message is recent history, even if it waited in the queue
+ // longer than 64 completed sends. Preserve its bridge while formal history mounts.
+ for (const clientId of previousLiveClientIds) {
+ if (liveClientIds.has(clientId)) continue;
+ const key = messageKey(sessionId, clientId);
+ const images = previews.get(key);
+ if (!images) continue;
+ previews.delete(key);
+ previews.set(key, images);
+ }
+ const liveKeys = new Set([...liveClientIds].map((clientId) => messageKey(sessionId, clientId)));
+ let historicalCount = 0;
+ for (const key of previews.keys()) if (!liveKeys.has(key)) historicalCount += 1;
+ for (const key of previews.keys()) {
+ if (historicalCount <= 64) break;
+ if (liveKeys.has(key)) continue;
+ previews.delete(key);
+ historicalCount -= 1;
+ }
+}
+
+/** Presentation-only attachment identities, with optional local pixels for immediate previews. */
export function rememberSentMessageImagePreviews(
previews: SentMessageImagePreviews,
sessionId: string,
clientId: string,
attachments: readonly RemoteSerializedAttachment[],
previewOf: (attachment: RemoteSerializedAttachment) => string | null | undefined,
+ galleryKeyOf?: (attachment: RemoteSerializedAttachment) => string | undefined,
+ liveClientIds?: ReadonlySet<string>,
): void {
const key = messageKey(sessionId, clientId);
const previous = previews.get(key);
const images = attachments.filter((attachment) => attachment.category === 'image').map((attachment) => {
const uri = previewOf(attachment);
- return uri ? { attachmentId: attachment.id, name: attachment.originalName ?? attachment.name,
- sourceRef: attachment.url ?? attachment.path, sha256: attachment.sha256, uri }
- : previous?.find((entry) => entry?.attachmentId === attachment.id) ?? null;
+ const prior = previous?.find((entry) => entry?.attachmentId === attachment.id);
+ // Preserve the outbox identity through URL materialization; a replaced file ID cannot inherit it.
+ const galleryImageKey = galleryKeyOf?.(attachment) ?? prior?.galleryImageKey;
+ const currentSourceRef = attachment.url ?? attachment.path;
+ return { attachmentId: attachment.id, name: attachment.originalName ?? attachment.name,
+ sourceRef: uri || !prior?.uri ? currentSourceRef : prior.sourceRef,
+ currentSourceRef,
+ sha256: attachment.sha256, uri: uri || prior?.uri || null,
+ ...(galleryImageKey ? { galleryImageKey } : {}) };
});
// Replace the complete snapshot on edit, including removed images and missing previews.
previews.delete(key);
+ if (images.length === 0) return;
previews.set(key, images);
- while (previews.size > 64) previews.delete(previews.keys().next().value!);
+ pruneSentMessageImagePreviews(previews, sessionId, liveClientIds);
+}
+
+/** Restored rows need the same slot-to-attachment bridge as newly dispatched sends. */
+export function rememberOutboxImagePreviews(
+ previews: SentMessageImagePreviews,
+ sessionId: string,
+ item: MobileOutboxItem,
+ liveClientIds?: ReadonlySet<string>,
+): void {
+ const slotOf = (attachment: RemoteSerializedAttachment) => (
+ item.attachmentSlots.findIndex((entry) => entry?.id === attachment.id)
+ );
+ rememberSentMessageImagePreviews(previews, sessionId, item.clientId, outboxItemAttachments(item),
+ (attachment) => item.slotMeta[slotOf(attachment)]?.previewUri,
+ (attachment) => `${item.clientId}-slot-${slotOf(attachment)}`, liveClientIds);
}
export function getSentMessageImagePreview(
@@ -47,10 +107,19 @@ export function getSentMessageImagePreview(
sha256?: string,
sourceRef?: string,
): SentMessageImagePreview | undefined {
- const preview = previews.get(messageKey(sessionId, clientId))?.[imageIndex];
- if (!preview || (attachmentId ? preview.attachmentId !== attachmentId : preview.name !== name)) return undefined;
+ const entries = previews.get(messageKey(sessionId, clientId));
+ if (attachmentId) return entries?.find((entry) => entry?.attachmentId === attachmentId) ?? undefined;
// Formal content omits file IDs. Prove the pixels still match before reusing a local image;
// a same-name queue edit on another device must never resurrect the old preview.
- if (!attachmentId && !(sha256 && preview.sha256 === sha256) && preview.sourceRef !== sourceRef) return undefined;
- return preview;
+ const matches = (entry: SentMessageImagePreview | null | undefined): entry is SentMessageImagePreview => (
+ !!entry && entry.name === name && (
+ !!sha256 && entry.sha256 === sha256 || (entry.currentSourceRef ?? entry.sourceRef) === sourceRef
+ )
+ );
+ const indexed = entries?.[imageIndex];
+ if (matches(indexed)) return indexed;
+ // Remote queue edits can move an image without updating this local snapshot. Only a unique,
+ // proven content match may reconnect it; ambiguous same-name images cannot share identity.
+ const candidates = entries?.filter(matches);
+ return candidates?.length === 1 ? candidates[0] : undefined;
}
diff --git a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
index d00ae18bc0..03824e2510 100644
--- a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
+++ b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
@@ -264,12 +264,26 @@ describe('Windows Git PATH PowerShell probes', () => {
expect(coordinator.kill()).toBe(true);
await coordinatorExit;
- terminateWindowsPowerShellDescendants(powershell, coordinatorPid);
+ const cleanupWarnings: unknown[] = [];
+ const cleanupStarted = performance.now();
+ terminateWindowsPowerShellDescendants(powershell, coordinatorPid, {
+ warn: (...args: unknown[]) => {
+ cleanupWarnings.push(args);
+ },
+ });
+ const cleanupMs = Math.round(performance.now() - cleanupStarted);
// EncodedCommand avoids Windows argv splitting of a multi-line -Command.
// Poll until the orphaned child is gone; a live child after cleanup is a real leak.
const livenessCommand = Buffer.from(
- `if (Get-Process -Id ${childPid} -ErrorAction SilentlyContinue) { exit 1 } else { exit 0 }`,
+ [
+ `$child = Get-Process -Id ${childPid} -ErrorAction SilentlyContinue`,
+ 'if ($child) {',
+ ' $child | Select-Object Id, ProcessName, StartTime, HasExited | ConvertTo-Json -Compress',
+ ' exit 1',
+ '}',
+ 'exit 0',
+ ].join('\n'),
'utf16le',
).toString('base64');
await vi.waitFor(
@@ -277,9 +291,20 @@ describe('Windows Git PATH PowerShell probes', () => {
const liveness = spawnSync(
powershell,
['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', livenessCommand],
- { stdio: 'ignore', timeout: 10_000, windowsHide: true },
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000, windowsHide: true },
);
- expect(liveness.status).toBe(0);
+ // Keep the real exit assertion, but report whether cleanup timed out,
+ // failed, or left a process alive instead of only "expected 1 to be 0".
+ expect(liveness.status, JSON.stringify({
+ coordinatorPid,
+ childPid,
+ cleanupMs,
+ cleanupWarnings,
+ livenessError: liveness.error?.message,
+ livenessSignal: liveness.signal,
+ livenessStdout: liveness.stdout,
+ livenessStderr: liveness.stderr,
+ })).toBe(0);
},
{ timeout: 8_000, interval: 50 },
);