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): 附件上传中离开时先确认,放弃后不发出缺图消息

Dash85ec962d0eb6
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 387ff337dc..8fa52ba80a 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -176,6 +176,7 @@ import type { MobileGoalLimitsInput } from '@cindy/maker-shared/device-link-cont
import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from '@/session/ComposerAttachmentTray';
import { useComposerPendingImagePreview } from '@/session/useComposerPendingImagePreview';
import { SlowSendNotice, type SlowSendPhase } from '@/session/SlowSendNotice';
+import { useConfirmLeaveWhileUploading } from '@/session/useConfirmLeaveWhileUploading';
import { ImageLightbox } from '@/session/ImageLightbox';
import {
useComposerImageAnnotations,
@@ -611,6 +612,7 @@ export default function NewRemoteSessionScreen() {
const [creating, setCreating] = useState(false);
const [createStartedAt, setCreateStartedAt] = useState<number | null>(null);
const [createPhase, setCreatePhase] = useState<SlowSendPhase>('preparing');
+ useConfirmLeaveWhileUploading(creating && createPhase === 'uploading');
const [error, setError] = useState<string | null>(() => {
const creationError = readRouteString(params.creationError);
return creationError ? t('session.screen.createFailedNotice', { message: creationError }) : null;
@@ -4523,9 +4525,10 @@ export default function NewRemoteSessionScreen() {
}
// 拍照 / 选图后立刻点创建是常见路径:等在途图片上传落定(乐观托盘)。
// 有失败就中止创建——错误文案已由上传回调写入 attachmentError,让用户处理;
- // 此时不该带着残缺附件去开新会话。
+ // 此时不该带着残缺附件去开新会话。等待期间离开会先确认;确认离开后在途上传随页面丢弃,同样放弃。
setCreatePhase('uploading');
- const { failedCount } = await waitForPendingUploads();
+ const { failedCount, abandoned } = await waitForPendingUploads();
+ if (abandoned) return;
if (!isCurrentOwner()) return;
if (!ensureDeviceAlive()) return;
if (failedCount > 0) return;
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index adab1e6988..3270b502a8 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -8,6 +8,7 @@ const h = vi.hoisted(() => ({
chat: null as any,
management: null as any,
alert: vi.fn(),
+ leaveGuard: [] as boolean[],
confirm: vi.fn(),
leave: vi.fn(),
focused: true,
@@ -105,6 +106,7 @@ vi.mock('@/components/AppText', () => ({
TextInput: ({ testID, ...props }: any) => { h.inputs[testID] = props; return el('input', { 'data-testid': testID, value: props.value ?? '', readOnly: true }); },
}));
vi.mock('@/components/PaperPlaneIcon', () => ({ PaperPlaneIcon: () => null }));
+vi.mock('@/session/useConfirmLeaveWhileUploading', () => ({ useConfirmLeaveWhileUploading: (active: boolean) => { h.leaveGuard.push(active); } }));
vi.mock('@/components/MobilePrimitives', () => ({
MainWindowActionButton: ({ action }: any) => el('button', {
'data-testid': action.testID, 'aria-label': action.accessibilityLabel, 'aria-busy': action.busy ? 'true' : undefined,
@@ -278,7 +280,7 @@ beforeEach(() => {
h.uuid = 0; h.inputs = {}; h.teammateQuery = ''; h.teammates = { rows: [], loading: false, failed: false };
h.platform.OS = 'ios'; h.focused = true; h.keyboardAvoidingView = null; h.headerBlur = []; h.headerFade = [];
h.chat = { reload: vi.fn(), act: vi.fn(async () => ({ effects: [] })), online: true };
- h.discarded = []; h.deleted = [];
+ h.discarded = []; h.deleted = []; h.leaveGuard = [];
h.local = {
options: null, setPending: null,
addImages: vi.fn(), addDocument: vi.fn(), addPastedImages: vi.fn(), enqueueUploads: vi.fn(),
@@ -874,6 +876,20 @@ describe('group attachments', () => {
expect(byId('botGroup.attachmentTray')).toBeNull();
});
+ // Leaving mid-upload drops the photo: ask first, and never send the text alone.
+ it('asks before leaving while a send waits on an upload, and sends nothing once left', async () => {
+ await render(group({ openPlan: null, supportsAttachments: true }));
+ await focusComposer();
+ await act(async () => { h.row.onChangeText('配图'); });
+ let settle!: (result: { failedCount: number; abandoned: boolean }) => void;
+ h.local.wait.mockImplementationOnce(() => new Promise((resolve) => { settle = resolve; }));
+ await click('botGroup.composer.send');
+ expect(h.leaveGuard.at(-1)).toBe(true);
+ await act(async () => settle({ failedCount: 0, abandoned: true }));
+ expect(h.chat.act).not.toHaveBeenCalled();
+ expect(h.leaveGuard.at(-1)).toBe(false);
+ });
+
it('reclaims unsent uploads when the chat closes', async () => {
await render(group({ openPlan: null, supportsAttachments: true }));
const photo = uploaded('att-4', 'c.jpg');
diff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
index 95e78a2234..ea3490a0ca 100644
--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
@@ -258,6 +258,17 @@ describe('useMobileLocalAttachments abandonment on scope change', () => {
expect(runtime.uploads).toHaveLength(0);
});
+ // Leaving the new-task page mid-upload used to send the message without its image:
+ // unmount discards the upload, which does not count as a failure.
+ it('tells a send waiting on uploads that the composer left', async () => {
+ const harness = mount('session-a');
+ act(() => harness.first.enqueueUploads([imageCandidate('a.png', vi.fn())], { token: 'token' }));
+ await act(async () => { await flush(); });
+ const waiting = harness.latest().waitForPendingUploads();
+ act(() => root.render(null));
+ await expect(waiting).resolves.toEqual({ failedCount: 0, abandoned: true });
+ });
+
it('abandons exactly once when an upload finishes after the composer scope moved on', async () => {
const harness = mount('session-a');
const abandoned = vi.fn();
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 915462f9b3..ffc398ca0c 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -1,4 +1,10 @@
{
+ "leaveWhileUploading": {
+ "title": "Discard this message?",
+ "body": "Attachments are still uploading. If you leave now, this message won't be sent.",
+ "stay": "Keep Waiting",
+ "discard": "Discard"
+ },
"entry": {
"title": "Open Task",
"loading": "Loading task…",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index a1dbdff563..46901d709d 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -1,4 +1,10 @@
{
+ "leaveWhileUploading": {
+ "title": "送信を中止しますか?",
+ "body": "添付のアップロードがまだ終わっていません。今離れるとこのメッセージは送信されません。",
+ "stay": "待つ",
+ "discard": "送信を中止"
+ },
"entry": {
"title": "タスクを開く",
"loading": "タスクを読み込み中…",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 20ef1b5e2d..1497666c37 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -1,4 +1,10 @@
{
+ "leaveWhileUploading": {
+ "title": "보내기를 취소할까요?",
+ "body": "첨부 업로드가 아직 끝나지 않았습니다. 지금 나가면 이 메시지는 보내지지 않습니다.",
+ "stay": "계속 기다리기",
+ "discard": "보내지 않기"
+ },
"entry": {
"title": "작업 열기",
"loading": "작업 불러오는 중…",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 6dd1e85bc1..4c52c65f8e 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -1,4 +1,10 @@
{
+ "leaveWhileUploading": {
+ "title": "放弃发送?",
+ "body": "附件还没上传完,现在离开这条消息就不会发送。",
+ "stay": "继续等待",
+ "discard": "放弃发送"
+ },
"entry": {
"title": "打开任务",
"loading": "正在读取任务…",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index fc688d03a8..600a9df22c 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -1,4 +1,10 @@
{
+ "leaveWhileUploading": {
+ "title": "放棄傳送?",
+ "body": "附件還沒上傳完,現在離開這則訊息就不會傳送。",
+ "stay": "繼續等待",
+ "discard": "放棄傳送"
+ },
"entry": {
"title": "開啟任務",
"loading": "正在讀取任務…",
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index 41b32318a3..bb01173002 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -20,6 +20,7 @@ import { Alert, Platform, Pressable, ScrollView, StyleSheet, View, type TextInpu
import { randomUUID } from 'expo-crypto';
import { Camera, Folder, Image as ImageIcon, Plus, Square, Users, X } from 'lucide-react-native';
import { useTranslation } from 'react-i18next';
+import { useConfirmLeaveWhileUploading } from '@/session/useConfirmLeaveWhileUploading';
import { BOT_GROUP_MESSAGE_MAX_CHARS, type BotGroupMemberView, type BotGroupMention } from '@cindy/maker-shared/botGroupChat';
import {
filterBotGroupMentionCandidates,
@@ -99,6 +100,8 @@ export function BotGroupComposer({
const [tracked, setTracked] = useState<BotGroupTrackedMention[]>([]);
const [division, setDivision] = useState(false);
const [sending, setSending] = useState(false);
+ const [waitingUploads, setWaitingUploads] = useState(false);
+ useConfirmLeaveWhileUploading(waitingUploads);
const [stopping, setStopping] = useState(false);
const inputRef = useRef<NativeTextInput>(null);
const textRef = useRef(text); textRef.current = text;
@@ -189,8 +192,12 @@ export function BotGroupComposer({
let release: (() => void) | null = null;
try {
// A photo picked a moment ago may still be uploading; it goes with this message. A failed
- // upload stays in the tray with 重试 and nothing is sent.
- const { failedCount } = await tray.waitForPendingUploads();
+ // upload stays in the tray with 重试 and nothing is sent. Leaving meanwhile asks first;
+ // once the chat is gone the upload is dropped, so nothing is sent either.
+ setWaitingUploads(true);
+ const { failedCount, abandoned } = await tray.waitForPendingUploads();
+ setWaitingUploads(false);
+ if (abandoned) return;
const attachments = attachmentsSupported ? [...tray.attachmentsRef.current] : [];
if (failedCount > 0 || (!draftText && attachments.length === 0)) {
restoreDraft();
diff --git a/apps/mobile/src/session/useConfirmLeaveWhileUploading.ts b/apps/mobile/src/session/useConfirmLeaveWhileUploading.ts
new file mode 100644
index 0000000000..66707d9f45
--- /dev/null
+++ b/apps/mobile/src/session/useConfirmLeaveWhileUploading.ts
@@ -0,0 +1,27 @@
+import { usePreventRemove } from 'expo-router/react-navigation';
+import { useNavigation } from 'expo-router';
+import { useTranslation } from 'react-i18next';
+import { Alert } from 'react-native';
+
+/**
+ * 发送正在等附件上传时拦截所有离开方式(顶栏返回、iOS 边缘右滑、Android 返回键)。
+ * 离开会丢弃在途上传,这条消息随之放弃发送,先让用户确认。
+ */
+export function useConfirmLeaveWhileUploading(active: boolean): void {
+ const { t } = useTranslation();
+ const navigation = useNavigation();
+ usePreventRemove(active, ({ data }) => {
+ Alert.alert(
+ t('session.leaveWhileUploading.title'),
+ t('session.leaveWhileUploading.body'),
+ [
+ { text: t('session.leaveWhileUploading.stay'), style: 'cancel' },
+ {
+ text: t('session.leaveWhileUploading.discard'),
+ style: 'destructive',
+ onPress: () => navigation.dispatch(data.action),
+ },
+ ],
+ );
+ });
+}
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 706f3e0f61..0f34012f0a 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -133,8 +133,11 @@ export interface UseMobileLocalAttachmentsResult {
discardAllPendingUploads: () => void;
/** 切换 attachmentScopeKey 前封住旧作用域;迟到 picker / 粘贴结果也会被拒绝。 */
discardAllPendingUploadsForScopeChange: () => void;
- /** 等全部在途上传落定;返回期间失败个数(>0 时调用方应中止发送)。 */
- waitForPendingUploads: () => Promise<{ failedCount: number }>;
+ /**
+ * 等全部在途上传落定;返回期间失败个数(>0 时调用方应中止发送)。
+ * abandoned:等待期间 composer 已卸载、在途上传已被丢弃,调用方必须放弃发送。
+ */
+ waitForPendingUploads: () => Promise<{ failedCount: number; abandoned: boolean }>;
/**
* 把当前全部未 claim 上传任务(active + 失败卡)划归一条乐观消息并返回快照
* (顺序 = 入队序):任务离开托盘 / 限额 / waitForPendingUploads,产物经
@@ -173,6 +176,7 @@ export function useMobileLocalAttachments(
const { t } = useTranslation();
const [pendingUploads, setPendingUploads] = useState<readonly PendingLocalAttachmentUpload[]>([]);
const pickerBusyRef = useRef(false);
+ const disposedRef = useRef(false);
/** 本 hook 拥有的 WebView 粘贴缓存;注册持久缩略图后或卸载时统一回收。 */
const pastedImageLocalUrisRef = useRef(new Set<string>());
const cleanupPastedImageLocalUris = async (uris: readonly string[]): Promise<void> => {
@@ -407,6 +411,7 @@ export function useMobileLocalAttachments(
};
useEffect(() => () => {
+ disposedRef.current = true;
controller.dispose();
const pastedUris = [...pastedImageLocalUrisRef.current].filter((uri) => !controller.isRetainingUri(uri));
void deleteLocalUris([...stagingUrisRef.current]);
@@ -422,6 +427,14 @@ export function useMobileLocalAttachments(
flushPastePlaceholderWaiters();
}, [controller]);
+ const waitForPendingUploadsInScope = async (): Promise<{ failedCount: number }> => {
+ if (!isAttachmentScopeActive()) return { failedCount: 0 };
+ await waitForPastePlaceholders();
+ if (!isAttachmentScopeActive()) return { failedCount: 0 };
+ const result = await controller.waitForIdle();
+ return isAttachmentScopeActive() ? result : { failedCount: 0 };
+ };
+
/** 限额口径的在途占坑数(见接口 doc):上传中任务 + 粘贴占位。 */
const getPendingSlotCount = () => controller.pendingCount() + getPastePlaceholderTotal();
@@ -651,13 +664,12 @@ export function useMobileLocalAttachments(
// 再等 controller 队列——否则占位窗口内抢发会把刚粘贴的图漏在消息外
//(review P2)。占位失败不计入 failedCount:那张图从未成为附件,语义等同
// 用户手动移除,不应中止发送。
- waitForPendingUploads: async () => {
- if (!isAttachmentScopeActive()) return { failedCount: 0 };
- await waitForPastePlaceholders();
- if (!isAttachmentScopeActive()) return { failedCount: 0 };
- const result = await controller.waitForIdle();
- return isAttachmentScopeActive() ? result : { failedCount: 0 };
- },
+ // 卸载会把在途任务标记丢弃,waitForIdle 不把丢弃计入失败;必须单独报出 abandoned,
+ // 否则调用方会带着缺图的附件列表照常发送(上传中点返回,发出无图消息)。
+ waitForPendingUploads: async () => ({
+ ...await waitForPendingUploadsInScope(),
+ abandoned: disposedRef.current,
+ }),
claimActiveUploads: () => {
if (!isAttachmentScopeActive()) return [];
const snapshot = controller.claimableTasks();