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): preserve shared attachment order and verified destinations

Chris8360a86654f3
diff --git a/apps/mobile/app/incoming-share.tsx b/apps/mobile/app/incoming-share.tsx
index 6f8b4c106a..9e93c6d4ec 100644
--- a/apps/mobile/app/incoming-share.tsx
+++ b/apps/mobile/app/incoming-share.tsx
@@ -149,7 +149,7 @@ export default function IncomingShareScreen() {
const conversation = item.item.links.find(link => link.rel === 'conversation')?.target;
return <Pressable accessibilityRole="button" style={styles.row}
disabled={conversation?.kind !== 'session'} onPress={() => {
- if (conversation?.kind === 'session') choose(incomingShareDestination(item.host.deviceId, conversation.sessionId),
+ if (conversation?.kind === 'session') choose(incomingShareDestination(item.host.deviceId, conversation.sessionId, item.item.ref),
() => router.dismissTo(teammateResourceRoute(item, i18n.language)));
}}>
<Text style={styles.title}>{resolveRemoteText(item.item.display.title, i18n.language)}</Text>
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 30bea42e38..168134bbfa 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';
import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';
import { incomingShareDestination } from '@/session/incomingShare';
import { useSessionHistorySearch } from '@/session/useSessionHistorySearch';
@@ -1350,6 +1351,7 @@ function SessionScreenContent() {
waitForPendingUploads,
beginOutboxAttachmentHandoff,
getUploadedSource,
+ insertUploadedAttachment,
getUploadedAttachmentId,
releaseUploadedSources,
waitForPastePlaceholdersSettled,
@@ -1367,7 +1369,7 @@ function SessionScreenContent() {
?.decorateUploadedAttachment(rawAttachment, candidate) ?? rawAttachment;
// send() 在 waitForPendingUploads 落定后同步读 ref,而 setState 到 commit 有
// 微任务延迟——这里派发时同步镜像,保证「上传完成→立即发送」不丢刚落定的附件。
- attachmentsRef.current = [...attachmentsRef.current, attachment];
+ attachmentsRef.current = insertUploadedAttachment(attachmentsRef.current, attachment);
if (candidate.kind === 'image') {
setAttachmentPreviews((current) => ({ ...current, [attachment.id]: candidate.uri }));
}
@@ -1376,7 +1378,7 @@ function SessionScreenContent() {
const sourceId = candidate.sourceId;
setMediaAssetAttachments((current) => ({ ...current, [sourceId]: attachment.id }));
}
- setAttachments((current) => [...current, attachment]);
+ setAttachments((current) => insertUploadedAttachment(current, attachment));
},
onError: (message) => {
setAttachmentError(message);
@@ -3229,8 +3231,11 @@ function SessionScreenContent() {
}, [applyComposerDraft]);
useIncomingShareComposer({
- destination: incomingShareDestination(deviceId, sessionId),
- ready: composerDraftHydrated && canUseComposer && !queueEditingRef.current,
+ destination: [incomingShareDestination(deviceId, sessionId), incomingShareDestination(deviceId, sessionId, {
+ collectionId: readRouteParam(params.resourceCollectionId) ?? '',
+ kind: readRouteParam(params.resourceKind) ?? '', id: readRouteParam(params.resourceId) ?? '',
+ })],
+ ready: composerDraftHydrated && canUseComposer && companionEntry.ready && !queueEditingRef.current,
appendText: text => setComposerDraft(current => [current, text].filter(Boolean).join('\n\n')),
attachmentCount: attachments.length,
enqueueUploads, getPendingUploadCount, onError: setAttachmentError,
@@ -6640,6 +6645,10 @@ function SessionScreenContent() {
sessionRefs: sessionRefsAtSend, agentReferences: agentReferencesAtSend,
pastedTextRanges: pastedTextRangesAtSend, slashCommandRanges: slashCommandRangesAtSend ?? [],
permissionModeAtSend, planModeAtSend, readyAttachments, readyPreviews,
+ attachmentOrder: incomingShareSlotOrder([
+ ...readyAttachments.map(attachment => getUploadedSource(attachment.id)?.incomingShareOrder),
+ ...pendingSources.map(({ source }) => source.incomingShareOrder),
+ ]),
claimedUploads: pendingSources.map(({ localId, source }) => ({ localId, failed: false, kind: source.kind, previewUri: source.uri })),
});
const clearedAt = currentSession.clearedAt ? Date.parse(currentSession.clearedAt) : null;
@@ -6654,7 +6663,7 @@ function SessionScreenContent() {
const source = getUploadedSource(readyAttachments[slot].id);
if (!source && !outboxAttachmentNeedsLocalBytes(readyAttachments[slot])) continue;
if (!source) throw new Error(t('session.screen.attachmentsNotCarriedBack', { count: 1 }));
- record.uploads.push(await retainOutboxFile(record, slot, source));
+ record.uploads.push(await retainOutboxFile(record, item.attachmentSlots.findIndex(attachment => attachment?.id === readyAttachments[slot].id), source));
}
for (const { localId, source } of pendingSources) {
record.uploads.push(await retainOutboxFile(record, item.slotByLocalId[localId]!, source));
@@ -6677,9 +6686,9 @@ function SessionScreenContent() {
applyComposerDocument(documentAfterOptimisticClear);
}
rememberSentAttachmentPreviews(record.item.clientId, readyAttachments, (attachment) => {
- const slot = readyAttachments.findIndex((a) => a.id === attachment.id);
+ const slot = item.attachmentSlots.findIndex((a) => a?.id === attachment.id);
const upload = record?.uploads.find((u) => u.slot === slot);
- return record && upload ? durableOutboxUploadUri(record, upload) : readyPreviews[slot] ?? null;
+ return record && upload ? durableOutboxUploadUri(record, upload) : readyPreviews[readyAttachments.findIndex(a => a.id === attachment.id)] ?? null;
}, (attachment) => {
const slot = item.attachmentSlots.findIndex((entry) => entry?.id === attachment.id);
return slot >= 0 ? `${item.clientId}-slot-${slot}` : undefined;
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 36f414018a..19fe4753ff 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -924,6 +924,7 @@ export default function NewRemoteSessionScreen() {
getPendingUploadCount,
hasAttachmentInput,
getUploadedSource,
+ insertUploadedAttachment,
getUploadedAttachmentId,
releaseUploadedSources,
} = useMobileLocalAttachments({
@@ -935,7 +936,7 @@ export default function NewRemoteSessionScreen() {
?.decorateUploadedAttachment(rawAttachment, candidate) ?? rawAttachment;
// create() 在 waitForPendingUploads 落定后同步读 ref,而 setState 到 commit 有
// 微任务延迟——这里派发时同步镜像,保证「上传完成→立即创建」不丢刚落定的附件。
- attachmentsRef.current = [...attachmentsRef.current, attachment];
+ attachmentsRef.current = insertUploadedAttachment(attachmentsRef.current, attachment);
if (candidate.kind === 'image') {
setAttachmentPreviews((current) => ({ ...current, [attachment.id]: candidate.uri }));
}
@@ -944,7 +945,7 @@ export default function NewRemoteSessionScreen() {
const sourceId = candidate.sourceId;
setMediaAssetAttachments((current) => ({ ...current, [sourceId]: attachment.id }));
}
- setAttachments((current) => [...current, attachment]);
+ setAttachments((current) => insertUploadedAttachment(current, attachment));
},
onError: setAttachmentError,
onPicked: () => setContextSheetOpen(false),
diff --git a/apps/mobile/docs/incoming-sharing.md b/apps/mobile/docs/incoming-sharing.md
index dc397bdbed..5789b982a9 100644
--- a/apps/mobile/docs/incoming-sharing.md
+++ b/apps/mobile/docs/incoming-sharing.md
@@ -49,9 +49,9 @@ new sending privileges: normal conversation hydration and authorization still ap
- `src/session/incomingShare.ts`: account-fenced mailbox, explicit destination identity,
text normalization and attachment conversion selection.
- `src/session/useIncomingShareComposer.ts`: shared handoff into new-task and existing
- task/companion composers. Upload, retries and send stay in the established pipeline.
+ task/companion composers. Share batch positions survive concurrent upload completion and durable outbox handoff; successfully staged non-image copies are released, while failed uploads retain retry inputs. Upload, retries and send stay in the established pipeline.
- `app/incoming-share.tsx`: destination discovery; companion identities come from their
- advertised conversation links, not names or guessed sessions. Hosts without a
+ permanent resource IDs, with live canonical-conversation verification before claiming a share. Hosts without a
conversation link remain visible but unavailable. Tasks use the existing active-list
API (latest 500 per computer plus pinned tasks); archived/worker/bot sessions are not
duplicated in the task section.
diff --git a/apps/mobile/src/__tests__/sessionOutbox.test.ts b/apps/mobile/src/__tests__/sessionOutbox.test.ts
index ce03f26499..1540b0e871 100644
--- a/apps/mobile/src/__tests__/sessionOutbox.test.ts
+++ b/apps/mobile/src/__tests__/sessionOutbox.test.ts
@@ -1,3 +1,4 @@
+import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';
import { beforeAll, describe, expect, it } from 'vitest';
import { DeviceLinkError } from '@cindy/device-link';
import { i18n } from '@/i18n';
@@ -549,3 +550,18 @@ describe('outboxWithUploadResult / outboxOwnsUpload / replaceOutboxItem', () =>
expect(replaced[0]?.text).toBe('changed');
});
});
+
+it('preserves external share order across completed and pending durable slots', () => {
+ const later = attachmentFor('second.pdf');
+ const item = itemWith({
+ readyAttachments: [later], readyPreviews: ['file:///stage/second'],
+ claimedUploads: [{ localId: 'first', failed: false, kind: 'file', name: 'first.pdf', previewUri: 'file:///share/first' }],
+ attachmentOrder: incomingShareSlotOrder([{ batchId: 'batch', index: 1 }, { batchId: 'batch', index: 0 }]),
+ });
+ expect(item.attachmentSlots).toEqual([null, later]);
+ expect(item.slotByLocalId.first).toBe(0);
+ expect(item.slotMeta.map(meta => meta.name)).toEqual(['first.pdf', 'second.pdf']);
+ expect(item.slotMeta.map(meta => meta.previewUri)).toEqual(['file:///share/first', 'file:///stage/second']);
+ const complete = outboxItemWithUpload(item, 'first', attachmentFor('first.pdf'));
+ expect(outboxItemAttachments(complete).map(attachment => attachment.name)).toEqual(['first.pdf', 'second.pdf']);
+});
diff --git a/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx b/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx
index c223d6326b..35d7a193ff 100644
--- a/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx
+++ b/apps/mobile/src/__tests__/useIncomingShareComposer.test.tsx
@@ -6,7 +6,7 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { beforeEach, afterEach, expect, it, vi } from 'vitest';
import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';
-import { __resetIncomingShareForTest, discardIncomingShareBatch, receiveIncomingShare, stageIncomingShareBatch, selectIncomingShareDestination, incomingShareBatchId } from '@/session/incomingShare';
+import { __resetIncomingShareForTest, discardIncomingShareBatch, receiveIncomingShare, stageIncomingShareBatch, selectIncomingShareDestination, incomingShareBatchId, incomingShareDestination } from '@/session/incomingShare';
import { setMobileAuthOwner, __testing as ownerTesting } from '@/auth/authOwnerGeneration';
import type { ResolvedSharePayload } from 'expo-sharing';
const h = vi.hoisted(() => ({ focused: true, auth: { isAuthenticated: true, user: { id: 'a' }, getAccessToken: async () => 'token' } }));
@@ -19,7 +19,7 @@ let root: Root;
const appendText = vi.fn(), enqueueUploads = vi.fn(), onError = vi.fn();
const link: ResolvedSharePayload = { value: 'https://example.com', shareType: 'url', contentUri: 'https://example.com', contentType: 'website', contentMimeType: 'text/uri-list', originalName: 'example.com', contentSize: null };
const file: ResolvedSharePayload = { value: 'file:///share/report.pdf', shareType: 'file', contentUri: 'file:///share/report.pdf', contentType: 'file', contentMimeType: 'application/pdf', originalName: 'report.pdf', contentSize: 20 };
-function Composer({ destination = 'chosen', ready = true, count = 0 }) {
+function Composer({ destination = 'chosen', ready = true, count = 0 }: { destination?: string | readonly string[]; ready?: boolean; count?: number }) {
useIncomingShareComposer({ destination, ready, attachmentCount: count, appendText, enqueueUploads, onError, getPendingUploadCount: () => 0 });
return null;
}
@@ -41,7 +41,7 @@ it('waits for the chosen focused composer to hydrate, then appends text and uplo
expect(ack).not.toHaveBeenCalled();
act(() => root.render(<Composer />));
expect(appendText).toHaveBeenCalledExactlyOnceWith(link.value);
- expect(enqueueUploads).toHaveBeenCalledWith([expect.objectContaining({ name: 'report.pdf', uri: file.value, cleanupLocalUris: expect.any(Function) })], expect.anything());
+ expect(enqueueUploads).toHaveBeenCalledWith([expect.objectContaining({ name: 'report.pdf', uri: file.value, incomingShareOrder: { batchId: expect.any(String), index: 0 }, cleanupLocalUris: expect.any(Function) })], expect.anything());
act(() => root.render(<Composer />));
expect(ack).toHaveBeenCalledOnce();
});
@@ -87,3 +87,24 @@ it('cancels an unclaimed share so sharing the same text again can open a fresh c
act(() => root.render(<Composer />));
expect(nextAck).toHaveBeenCalledOnce(); expect(appendText).toHaveBeenCalledOnce();
});
+
+it('retains a companion share until the live canonical task is ready', () => {
+ const resource = { collectionId: 'companions', kind: 'bot', id: 'alice' };
+ const batch = stageIncomingShareBatch([link, file], vi.fn())!;
+ selectIncomingShareDestination(batch.id, incomingShareDestination('host', 'old-task', resource));
+ act(() => root.render(<Composer destination={incomingShareDestination('host', 'old-task', resource)} ready={false} />));
+ expect(batch.acknowledge).not.toHaveBeenCalled();
+ act(() => root.render(<Composer destination={incomingShareDestination('host', 'new-task', resource)} ready={false} />));
+ expect(appendText).not.toHaveBeenCalled();
+ act(() => root.render(<Composer destination={incomingShareDestination('host', 'new-task', resource)} />));
+ expect(batch.acknowledge).toHaveBeenCalledOnce();
+ expect(appendText).toHaveBeenCalledExactlyOnceWith(link.value);
+ expect(enqueueUploads).toHaveBeenCalledOnce();
+});
+
+it('also accepts a task-row selection when the mounted route retains companion identity', () => {
+ const ack = share();
+ act(() => root.render(<Composer destination={['chosen', 'resource-alias']} />));
+ expect(ack).toHaveBeenCalledOnce();
+ expect(appendText).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
index ea3490a0ca..17405620f0 100644
--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
@@ -2,6 +2,7 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { RemoteSerializedAttachment } from '@/session/types';
import type { MobileLocalAttachmentUploadCandidate } from '@/session/mobileLocalAttachmentUpload';
import { useComposerImageExpansion } from '@/session/useComposerImageExpansion';
import {
@@ -287,3 +288,39 @@ describe('useMobileLocalAttachments abandonment on scope change', () => {
expect(abandoned).toHaveBeenCalledTimes(1);
});
});
+
+it('restores share source order when concurrent uploads complete in reverse order', async () => {
+ const harness = mount('session-a');
+ let attachments: RemoteSerializedAttachment[] = [];
+ vi.mocked(harness.options.onUploaded).mockImplementation(attachment => {
+ attachments = harness.latest().insertUploadedAttachment(attachments, attachment);
+ });
+ act(() => harness.first.enqueueUploads(['first.pdf', 'second.pdf'].map((name, index) => ({
+ kind: 'file', uri: `file:///share/${name}`, name, size: 1000,
+ incomingShareOrder: { batchId: 'batch', index },
+ })), { token: 'token' }));
+ await act(async () => { await flush(); });
+ expect(runtime.uploads).toHaveLength(2);
+ await act(async () => { runtime.uploads[1].resolve(); await flush(); });
+ expect(attachments.map(item => item.name)).toEqual(['second.pdf']);
+ await act(async () => { runtime.uploads[0].resolve(); await harness.latest().waitForPendingUploads(); });
+ expect(attachments.map(item => item.name)).toEqual(['first.pdf', 'second.pdf']);
+});
+
+it('cleans a shared file only after staging takes ownership, retaining failed originals for retry', async () => {
+ const harness = mount('session-a');
+ const cleanup = vi.fn(async () => {
+ expect(harness.latest().getUploadedSource('att-report.pdf')?.uri).toBe('file:///stage/att-report.pdf');
+ expect(harness.options.onUploaded).toHaveBeenCalledOnce();
+ });
+ act(() => harness.first.enqueueUploads([{
+ kind: 'file', uri: 'file:///share/report.pdf', name: 'report.pdf', size: 1000, cleanupLocalUris: cleanup,
+ }], { token: Promise.resolve(null) }));
+ await act(async () => { await harness.latest().waitForPendingUploads(); });
+ expect(cleanup).not.toHaveBeenCalled();
+ const localId = harness.latest().pendingUploads[0].localId;
+ act(() => harness.latest().retryPendingUpload(localId));
+ await act(async () => { await flush(); });
+ await act(async () => { runtime.uploads[0].resolve(); await harness.latest().waitForPendingUploads(); });
+ expect(cleanup).toHaveBeenCalledExactlyOnceWith(['file:///share/report.pdf']);
+});
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index eb7618b7b2..763882993f 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -198,8 +198,11 @@ export function incomingShareText(payloads: readonly ResolvedSharePayload[]): st
.map(payload => payload.value).filter(value => value.trim()).join('\n\n');
}
-export function incomingShareDestination(deviceId: string, sessionId: string): string {
- return JSON.stringify([deviceId, sessionId]);
+export function incomingShareDestination(deviceId: string, sessionId: string,
+ resource?: { collectionId: string; kind: string; id: string }): string {
+ return resource?.collectionId && resource.kind && resource.id
+ ? JSON.stringify([deviceId, 'resource', resource.collectionId, resource.kind, resource.id])
+ : JSON.stringify([deviceId, sessionId]);
}
export function consumeIncomingShareBatch(id: string): boolean {
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 50638a462a..4bea42b51c 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -61,6 +61,8 @@ export interface MobileLocalAttachmentUploadCandidate {
cleanupLocalUris?: (uris: readonly string[]) => Promise<void>;
/** 宿主侧溯源 id(相册 asset.id → attachment 映射用),管线不消费。 */
sourceId?: string;
+ /** Source position within one external share; retained across retries. */
+ incomingShareOrder?: { batchId: string; index: number };
/**
* 圈点标注元数据(uri 已是烧录产物时携带;管线不消费,onUploaded 原样回传,
* 宿主据此给附件打 annotated 标并记录「矢量笔迹 + 原图」的再编辑真相)。
@@ -739,3 +741,19 @@ export function createMobileLocalAttachmentUploadController(
},
};
}
+
+/** Reorder only members of the same share, preserving all unrelated slot positions. */
+export function incomingShareSlotOrder(orders: readonly (MobileLocalAttachmentUploadCandidate['incomingShareOrder'] | undefined)[]): number[] {
+ const result = orders.map((_, index) => index);
+ const groups = new Map<string, number[]>();
+ orders.forEach((order, index) => {
+ if (!order) return;
+ const group = groups.get(order.batchId) ?? [];
+ group.push(index); groups.set(order.batchId, group);
+ });
+ for (const positions of groups.values()) {
+ const sorted = [...positions].sort((a, b) => orders[a]!.index - orders[b]!.index);
+ positions.forEach((position, i) => { result[position] = sorted[i]; });
+ }
+ return result;
+}
diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.ts
index 8edf83e1b4..4f3dc9479b 100644
--- a/apps/mobile/src/session/sessionOutbox.ts
+++ b/apps/mobile/src/session/sessionOutbox.ts
@@ -238,6 +238,8 @@ export function buildOutboxItem(input: {
slashCommandRanges?: Array<{ start: number; end: number }>;
permissionModeAtSend: string;
planModeAtSend?: boolean;
+ /** Optional source order across ready and pending slots, for external shares. */
+ attachmentOrder?: readonly number[];
/** 发送时刻已就绪的附件(占前段槽位)。 */
readyAttachments: readonly RemoteSerializedAttachment[];
/** 就绪附件的本地预览 uri(与 readyAttachments 对齐;缺失传 null)。 */
@@ -268,6 +270,15 @@ export function buildOutboxItem(input: {
if (upload.failed) failedIds.push(upload.localId);
else waitingIds.push(upload.localId);
}
+ if (input.attachmentOrder) {
+ const originalSlots = [...slots], originalMeta = [...slotMeta];
+ input.attachmentOrder.forEach((original, position) => {
+ slots[position] = originalSlots[original]; slotMeta[position] = originalMeta[original];
+ });
+ for (const localId of Object.keys(slotByLocalId)) {
+ slotByLocalId[localId] = input.attachmentOrder.indexOf(slotByLocalId[localId]);
+ }
+ }
return {
clientId: input.clientId,
sessionId: input.sessionId,
diff --git a/apps/mobile/src/session/useIncomingShareComposer.ts b/apps/mobile/src/session/useIncomingShareComposer.ts
index 799f5e5972..aa72901b1d 100644
--- a/apps/mobile/src/session/useIncomingShareComposer.ts
+++ b/apps/mobile/src/session/useIncomingShareComposer.ts
@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';
/** Shares enter the real composer: its existing upload, retry and send pipeline owns delivery. */
export function useIncomingShareComposer(options: {
- destination: string;
+ destination: string | readonly string[];
ready: boolean;
appendText(text: string): void;
attachmentCount: number;
@@ -26,7 +26,8 @@ export function useIncomingShareComposer(options: {
const pendingCount = options.getPendingUploadCount();
useEffect(() => {
const target = latest.current;
- if (!focused || !target.ready || !batch || batch.destination !== target.destination
+ const destinations = typeof target.destination === 'string' ? [target.destination] : target.destination;
+ if (!focused || !target.ready || !batch || !batch.destination || !destinations.includes(batch.destination)
|| !auth.isAuthenticated || getMobileAuthOwner().accountId !== auth.user?.id) return;
const selection = selectIncomingShareUploadCandidates(batch.payloads);
if (selection.candidates.length + target.attachmentCount + target.getPendingUploadCount() > MOBILE_MAX_ATTACHMENTS) {
@@ -42,8 +43,8 @@ export function useIncomingShareComposer(options: {
}
const text = incomingShareText(batch.payloads);
if (text) target.appendText(text);
- if (selection.candidates.length) target.enqueueUploads(selection.candidates.map(candidate => ({
- ...candidate, cleanupLocalUris: deleteIncomingSharedFiles,
+ if (selection.candidates.length) target.enqueueUploads(selection.candidates.map((candidate, index) => ({
+ ...candidate, incomingShareOrder: { batchId: batch.id, index }, cleanupLocalUris: deleteIncomingSharedFiles,
})), { token: auth.getAccessToken() });
if (selection.rejectedUris.length) void deleteIncomingSharedFiles(selection.rejectedUris).catch(() => undefined);
target.onError(selection.rejectedUris.length ? t('composer.upload.noFileRead') : null);
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 0f34012f0a..51b381b538 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -94,6 +94,7 @@ async function deleteLocalUris(uris: readonly string[]): Promise<void> {
export interface UseMobileLocalAttachmentsResult {
beginOutboxAttachmentHandoff: () => Promise<ReturnType<MobileLocalAttachmentUploadController['beginHandoff']>>;
+ insertUploadedAttachment: (current: RemoteSerializedAttachment[], attachment: RemoteSerializedAttachment) => RemoteSerializedAttachment[];
getUploadedSource: (id: string) => MobileLocalAttachmentUploadCandidate | undefined;
/** Resolve a tray upload to its delivered attachment without retaining temporary URIs. */
getUploadedAttachmentId: (localId: string) => string | undefined;
@@ -339,13 +340,10 @@ export function useMobileLocalAttachments(
onAbandoned: undefined, onConsumed: undefined,
});
optionsRef.current.onUploaded(attachment, deliveredCandidate, localId);
- if (candidate.cleanupLocalUris) {
- // 只有持久缩略图已经接管 composer / sent-message 预览后才删源文件;
- // 注册失败时保留到页面卸载,不能让已上传附件立刻变成坏图。
- if (deliveredCandidate.uri !== candidate.uri) {
- // 附件已交给 composer/outbox,清理失败不能再把成功翻成上传失败。
- void candidate.cleanupLocalUris(localUris).catch(() => undefined);
- }
+ if (candidate.cleanupLocalUris && (candidate.kind === 'file' || deliveredCandidate.uri !== candidate.uri)) {
+ // Staging owns retry/send bytes. Images additionally require a replacement
+ // preview before deleting their source; ordinary files have no URI preview.
+ void candidate.cleanupLocalUris(localUris).catch(() => undefined);
}
},
onFailed: (err, localId, candidate) => {
@@ -631,6 +629,18 @@ export function useMobileLocalAttachments(
}
}
},
+ insertUploadedAttachment: (current, attachment) => {
+ const order = uploadedSourcesRef.current.get(attachment.id)?.incomingShareOrder;
+ if (!order) return [...current, attachment];
+ let position = current.length;
+ for (let i = 0; i < current.length; i++) {
+ const other = uploadedSourcesRef.current.get(current[i].id)?.incomingShareOrder;
+ if (other?.batchId !== order.batchId) continue;
+ position = i + 1;
+ if (other.index > order.index) { position = i; break; }
+ }
+ return [...current.slice(0, position), attachment, ...current.slice(position)];
+ },
getUploadedSource: (id) => uploadedSourcesRef.current.get(id),
getUploadedAttachmentId: (localId) => [...uploadedSourcesRef.current].find(([, source]) => source.localId === localId)?.[0],
releaseUploadedSources: (ids) => {