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): 离开确认弹窗未决时发送等待用户选择

Dashe20c258b67d6
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index de56ade0f8..a3f851c876 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -612,7 +612,7 @@ export default function NewRemoteSessionScreen() {
const [creating, setCreating] = useState(false);
const [createStartedAt, setCreateStartedAt] = useState<number | null>(null);
const [createPhase, setCreatePhase] = useState<SlowSendPhase>('preparing');
- const leaveConfirmedRef = useConfirmLeaveWhileUploading(creating && createPhase === 'uploading');
+ const waitForLeaveDecision = useConfirmLeaveWhileUploading(creating && createPhase === 'uploading');
const [error, setError] = useState<string | null>(() => {
const creationError = readRouteString(params.creationError);
return creationError ? t('session.screen.createFailedNotice', { message: creationError }) : null;
@@ -4528,7 +4528,8 @@ export default function NewRemoteSessionScreen() {
// 此时不该带着残缺附件去开新会话。等待期间离开会先确认;确认离开后在途上传随页面丢弃,同样放弃。
setCreatePhase('uploading');
const { failedCount, abandoned } = await waitForPendingUploads();
- if (abandoned || leaveConfirmedRef.current) return;
+ // 离开确认弹窗未决时,等用户选择:选「放弃发送」就不发,选「继续等待」照常创建。
+ if (abandoned || await waitForLeaveDecision()) 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 7cf2e43564..06cb321f32 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -9,6 +9,7 @@ const h = vi.hoisted(() => ({
management: null as any,
alert: vi.fn(),
leaveGuard: [] as boolean[],
+ leaveDecision: (async () => false) as () => Promise<boolean>,
confirm: vi.fn(),
leave: vi.fn(),
focused: true,
@@ -106,7 +107,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); return { current: false }; } }));
+vi.mock('@/session/useConfirmLeaveWhileUploading', () => ({ useConfirmLeaveWhileUploading: (active: boolean) => { h.leaveGuard.push(active); return () => h.leaveDecision(); } }));
vi.mock('@/components/MobilePrimitives', () => ({
MainWindowActionButton: ({ action }: any) => el('button', {
'data-testid': action.testID, 'aria-label': action.accessibilityLabel, 'aria-busy': action.busy ? 'true' : undefined,
@@ -280,7 +281,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.leaveGuard = [];
+ h.discarded = []; h.deleted = []; h.leaveGuard = []; h.leaveDecision = async () => false;
h.local = {
options: null, setPending: null,
addImages: vi.fn(), addDocument: vi.fn(), addPastedImages: vi.fn(), enqueueUploads: vi.fn(),
@@ -890,6 +891,25 @@ describe('group attachments', () => {
expect(h.leaveGuard.at(-1)).toBe(false);
});
+ // The leave dialog stays open after the upload settles: nothing may be sent before the answer.
+ it('holds the send for an open leave dialog, then sends or drops it by the answer', async () => {
+ await render(group({ openPlan: null, supportsAttachments: true }));
+ await focusComposer();
+ await act(async () => { h.row.onChangeText('配图'); });
+ let answer!: (discard: boolean) => void;
+ h.leaveDecision = () => new Promise((resolve) => { answer = resolve; });
+ await click('botGroup.composer.send');
+ expect(h.chat.act).not.toHaveBeenCalled();
+ await act(async () => answer(false));
+ expect(h.chat.act).toHaveBeenCalledTimes(1);
+
+ h.chat.act.mockClear();
+ await act(async () => { h.row.onChangeText('再来一条'); });
+ await click('botGroup.composer.send');
+ await act(async () => answer(true));
+ expect(h.chat.act).not.toHaveBeenCalled();
+ });
+
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__/useConfirmLeaveWhileUploading.test.tsx b/apps/mobile/src/__tests__/useConfirmLeaveWhileUploading.test.tsx
index 07c400fd75..885f92ead1 100644
--- a/apps/mobile/src/__tests__/useConfirmLeaveWhileUploading.test.tsx
+++ b/apps/mobile/src/__tests__/useConfirmLeaveWhileUploading.test.tsx
@@ -24,14 +24,18 @@ beforeEach(() => {
afterEach(() => act(() => root.unmount()));
function mount(active: boolean) {
- let confirmed!: { current: boolean };
+ let waitForLeaveDecision!: () => Promise<boolean>;
function Harness() {
- confirmed = useConfirmLeaveWhileUploading(active);
+ waitForLeaveDecision = useConfirmLeaveWhileUploading(active);
return null;
}
act(() => root.render(<Harness />));
const [enabled, onPrevent] = h.prevent.mock.calls.at(-1)!;
- return { enabled, onPrevent, confirmed };
+ const action = { type: 'GO_BACK' };
+ const leave = () => onPrevent({ data: { action } });
+ const choose = (style: 'cancel' | 'destructive') => h.alert.mock.calls.at(-1)![2]
+ .find((button: { style?: string }) => button.style === style).onPress();
+ return { enabled, leave, choose, action, waitForLeaveDecision, dismiss: () => h.alert.mock.calls.at(-1)![3].onDismiss() };
}
describe('useConfirmLeaveWhileUploading', () => {
@@ -40,20 +44,41 @@ describe('useConfirmLeaveWhileUploading', () => {
expect(mount(true).enabled).toBe(true);
});
- it('keeps waiting on cancel and leaves, marking the send abandoned, on discard', () => {
- const { onPrevent, confirmed } = mount(true);
- const action = { type: 'GO_BACK' };
- onPrevent({ data: { action } });
- const [, , buttons] = h.alert.mock.calls[0];
- const stay = buttons.find((b: { style?: string }) => b.style === 'cancel');
- const discard = buttons.find((b: { style?: string }) => b.style === 'destructive');
+ it('lets the send continue when nobody tried to leave', async () => {
+ await expect(mount(true).waitForLeaveDecision()).resolves.toBe(false);
+ });
- stay.onPress?.();
+ // The native alert stays open after an upload settles, so the send must wait for the choice.
+ it('holds the send until the open dialog is answered', async () => {
+ const stay = mount(true);
+ stay.leave();
+ let settled: boolean | undefined;
+ const waiting = stay.waitForLeaveDecision().then((value) => { settled = value; });
+ await Promise.resolve();
+ expect(settled).toBeUndefined();
+ stay.choose('cancel');
+ await waiting;
+ expect(settled).toBe(false);
expect(h.dispatch).not.toHaveBeenCalled();
- expect(confirmed.current).toBe(false);
- discard.onPress();
- expect(h.dispatch).toHaveBeenCalledWith(action);
- expect(confirmed.current).toBe(true);
+ const discard = mount(true);
+ discard.leave();
+ const discarding = discard.waitForLeaveDecision();
+ discard.choose('destructive');
+ await expect(discarding).resolves.toBe(true);
+ expect(h.dispatch).toHaveBeenCalledWith(discard.action);
+ await expect(discard.waitForLeaveDecision()).resolves.toBe(true);
+ });
+
+ it('treats dismissing the dialog as keep waiting, and never stacks a second dialog', async () => {
+ const harness = mount(true);
+ harness.leave();
+ harness.leave();
+ expect(h.alert).toHaveBeenCalledTimes(1);
+ const waiting = harness.waitForLeaveDecision();
+ harness.dismiss();
+ await expect(waiting).resolves.toBe(false);
+ harness.leave();
+ expect(h.alert).toHaveBeenCalledTimes(2);
});
});
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index 4f3d30487e..725b604406 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -101,7 +101,7 @@ export function BotGroupComposer({
const [division, setDivision] = useState(false);
const [sending, setSending] = useState(false);
const [waitingUploads, setWaitingUploads] = useState(false);
- const leaveConfirmedRef = useConfirmLeaveWhileUploading(waitingUploads);
+ const waitForLeaveDecision = useConfirmLeaveWhileUploading(waitingUploads);
const [stopping, setStopping] = useState(false);
const inputRef = useRef<NativeTextInput>(null);
const textRef = useRef(text); textRef.current = text;
@@ -196,8 +196,9 @@ export function BotGroupComposer({
// once the chat is gone the upload is dropped, so nothing is sent either.
setWaitingUploads(true);
const { failedCount, abandoned } = await tray.waitForPendingUploads();
+ const discarded = abandoned || await waitForLeaveDecision();
setWaitingUploads(false);
- if (abandoned || leaveConfirmedRef.current) return;
+ if (discarded) 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
index e380bba407..b9e16ad051 100644
--- a/apps/mobile/src/session/useConfirmLeaveWhileUploading.ts
+++ b/apps/mobile/src/session/useConfirmLeaveWhileUploading.ts
@@ -1,6 +1,6 @@
import { usePreventRemove } from 'expo-router/react-navigation';
import { useNavigation } from 'expo-router';
-import { useRef, type MutableRefObject } from 'react';
+import { useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert } from 'react-native';
@@ -8,29 +8,42 @@ import { Alert } from 'react-native';
* 发送正在等附件上传时拦截所有离开方式(顶栏返回、iOS 边缘右滑、Android 返回键)。
* 离开会丢弃在途上传,这条消息随之放弃发送,先让用户确认。
*
- * 返回的 ref 在用户确认放弃的瞬间同步置 true:导航卸载是异步的,上传恰好在这之间
- * 完成时,等待方可能以 abandoned:false 醒来,需据此 ref 一并放弃。
+ * 弹窗是原生模态,打开期间页面不卸载、上传可能已落定。发送方在等待上传返回后必须
+ * `await` 返回的 waitForLeaveDecision():弹窗未决时等用户选择,返回 true 表示用户
+ * 确认放弃(或已放弃),发送方应放弃发送;false 表示继续发送。
*/
-export function useConfirmLeaveWhileUploading(active: boolean): MutableRefObject<boolean> {
+export function useConfirmLeaveWhileUploading(active: boolean): () => Promise<boolean> {
const { t } = useTranslation();
const navigation = useNavigation();
- const leaveConfirmedRef = useRef(false);
+ const discardedRef = useRef(false);
+ const pendingRef = useRef<Promise<boolean> | null>(null);
usePreventRemove(active, ({ data }) => {
+ // 弹窗已开时再次触发离开(再滑一次)不叠第二个弹窗。
+ if (pendingRef.current) return;
+ let settle!: (discard: boolean) => void;
+ pendingRef.current = new Promise<boolean>((resolve) => { settle = resolve; });
+ const decide = (discard: boolean) => {
+ pendingRef.current = null;
+ settle(discard);
+ };
Alert.alert(
t('session.leaveWhileUploading.title'),
t('session.leaveWhileUploading.body'),
[
- { text: t('session.leaveWhileUploading.stay'), style: 'cancel' },
+ { text: t('session.leaveWhileUploading.stay'), style: 'cancel', onPress: () => decide(false) },
{
text: t('session.leaveWhileUploading.discard'),
style: 'destructive',
onPress: () => {
- leaveConfirmedRef.current = true;
+ discardedRef.current = true;
+ decide(true);
navigation.dispatch(data.action);
},
},
],
+ // Android 点弹窗外会直接关闭,等价于继续等待。
+ { cancelable: true, onDismiss: () => decide(false) },
);
});
- return leaveConfirmedRef;
+ return useCallback(async () => (await pendingRef.current) ?? discardedRef.current, []);
}