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(sharing): bind close confirmations to current scope

DavidShen41d62f9ef9d4
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx
index ce5971ab25..d4af2cae20 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx
@@ -21,7 +21,7 @@ type SharedTaskTab = 'current' | 'owned';
type ConfirmState =
| { kind: 'remove'; memberId: string; name: string }
| { kind: 'leave' }
- | { kind: 'closeCurrent' }
+ | { kind: 'closeCurrent'; sharedTaskId: string }
| { kind: 'closeAll'; targets: SharedTaskOwnedItem[] };
const tabButton = (active: boolean) => `rounded-full px-3 py-1 text-12 leading-5 transition-colors ${
@@ -155,7 +155,7 @@ export function SharedTaskButton({ session }: { session: Session }) {
}, false) };
case 'closeCurrent':
return { title: t('sharedTask.closeOneTitle'), body: t('sharedTask.closeOneBody'), keep: t('sharedTask.closeAllKeep'), action: t('sharedTask.close'),
- run: () => void run(async () => { await host({ action: 'close', sharedTaskId: detail!.sharedTaskId }); setConfirm(null); toast.success(t('sharedTask.closedToast', { count: 1 })); }) };
+ run: () => void run(async () => { await host({ action: 'close', sharedTaskId: state.sharedTaskId }); setConfirm(null); toast.success(t('sharedTask.closedToast', { count: 1 })); }) };
case 'closeAll':
return { title: t('sharedTask.closeAllTitle'), body: t('sharedTask.closeAllBody'), keep: t('sharedTask.closeAllKeep'),
action: t('sharedTask.closeAllAction', { count: state.targets.length }), danger: true,
@@ -215,7 +215,7 @@ export function SharedTaskButton({ session }: { session: Session }) {
})}
<div className={noticeClass}><Clock size={16} className="mt-0.5 shrink-0" aria-hidden /><p>{t(session.deviceLinkDeviceId ? 'sharedTask.remoteHostOfflineNote' : 'sharedTask.hostOfflineNote')}</p></div>
<div className="mt-5 flex justify-center"><Button variant="secondary" size="lg" disabled={busy} className="w-full px-4 text-[var(--error-fg)]"
- onClick={() => setConfirm({ kind: 'closeCurrent' })}>{t('sharedTask.closeCurrent')}</Button></div>
+ onClick={() => setConfirm({ kind: 'closeCurrent', sharedTaskId: detail.sharedTaskId })}>{t('sharedTask.closeCurrent')}</Button></div>
</>
: <div className="px-1 py-6 text-center">
{emptyIcon(<CircleStop size={18} aria-hidden />)}
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx
index ab2f8e92e9..262401d09f 100644
--- a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx
@@ -199,6 +199,26 @@ it.each(['response', 'rejection'])('retries only failed snapshot items after a c
]);
expect(within(body).queryByRole('alertdialog')).toBeNull();
});
+it('closes the shared task captured when the current-task confirmation opened', async () => {
+ vi.useFakeTimers();
+ try {
+ let currentDetail: SharedTaskDetail = detail;
+ state.host.mockImplementation(async (command: { action: string }) => {
+ if (command.action === 'close') return { ok: true };
+ return { available: true, detail: currentDetail };
+ });
+ const body = await openWindow(ownerSession);
+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.closeCurrent' })));
+ currentDetail = { ...detail, sharedTaskId: 'st2', title: 'Task B' };
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.close' })));
+ expect(state.host.mock.calls.filter(([command]) => command.action === 'close')).toEqual([
+ [{ action: 'close', sharedTaskId: 'st1' }],
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+});
it.each(['account change', 'unmount'])('stops the confirmed batch after %s', async (invalidation) => {
let finish!: (result: SharedTaskCloseResult) => void;
state.account.mockImplementation((command: { action: string }) => command.action === 'owned'
diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsx
index 7132ad6448..6106170d32 100644
--- a/apps/mobile/app/shared-session.tsx
+++ b/apps/mobile/app/shared-session.tsx
@@ -51,6 +51,7 @@ export default function SharedSessionScreen() {
const pending = useRef(false);
const mounted = useRef(true);
const epoch = useRef(0);
+ const pageGeneration = useRef(0);
const peer = deviceId ? parseSharedTaskPeer(deviceId) : null;
const guestId = peer?.role === 'host' ? peer.sharedTaskId : joinedId ?? sharedTaskId;
const guestTarget = peer?.role === 'host' ? deviceId
@@ -117,7 +118,13 @@ export default function SharedSessionScreen() {
return () => { mounted.current = false; epoch.current++; };
}, [accountGeneration, deviceId, sessionId, sharedTaskId]);
useFocusEffect(useCallback(() => {
- return () => { confirmationPending.current = null; };
+ const captured = ++pageGeneration.current;
+ return () => {
+ if (pageGeneration.current === captured) pageGeneration.current++;
+ confirmationPending.current = null;
+ pending.current = false;
+ setBusy(false);
+ };
}, []));
useFocusEffect(useCallback(() => {
let disposed = false;
@@ -145,7 +152,8 @@ export default function SharedSessionScreen() {
const owner = getMobileAuthOwner();
// A read already in flight must not restore state from before this action.
const captured = ++epoch.current;
- const current = () => mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner);
+ const page = pageGeneration.current;
+ const current = () => mounted.current && captured === epoch.current && page === pageGeneration.current && isMobileAuthOwnerCurrent(owner);
try {
if (link.sharedTaskAvailable !== true) { setNotice(t(link.sharedTaskAvailable === false ? 'sharedTask.upgrade' : 'sharedTask.retry')); return; }
await work(current);
@@ -155,12 +163,13 @@ export default function SharedSessionScreen() {
if (guestId && isSharedTaskGone(error)) endAccess();
else setNotice(t(sharedTaskErrorKey(error, context)));
}
- } finally { if (captured === epoch.current) { pending.current = false; setBusy(false); } }
+ } finally { if (captured === epoch.current && page === pageGeneration.current) { pending.current = false; setBusy(false); } }
};
const confirm = (title: string, body: string, cancel: string, action: string, work: (current: () => boolean) => Promise<void>, reload = true, extra?: { items?: string[]; note?: string }) => {
if (confirmationPending.current || pending.current) return;
const owner = getMobileAuthOwner();
const captured = epoch.current;
+ const page = pageGeneration.current;
const request = {};
confirmationPending.current = request;
Keyboard.dismiss();
@@ -170,7 +179,7 @@ export default function SharedSessionScreen() {
}).then((accepted) => {
if (confirmationPending.current !== request) return;
confirmationPending.current = null;
- if (accepted && mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner)) void run(work, reload);
+ if (accepted && mounted.current && captured === epoch.current && page === pageGeneration.current && isMobileAuthOwnerCurrent(owner)) void run(work, reload);
});
};
const openTask = async (id: string, current: () => boolean) => {
@@ -205,12 +214,23 @@ export default function SharedSessionScreen() {
t('sharedTask.closeAllTitle'),
t('sharedTask.closeAllBody'),
t('sharedTask.closeAllKeep'), t('sharedTask.closeAllAction', { count: items.length }), async (current) => {
- const results = await Promise.allSettled(items.map((item) => api.close(item.sharedTaskId)));
+ const closed = new Set<string>();
+ const failed: SharedTaskListItem[] = [];
+ for (const item of items) {
+ if (!current()) return;
+ try {
+ await api.close(item.sharedTaskId);
+ if (!current()) return;
+ closed.add(item.sharedTaskId);
+ } catch {
+ if (!current()) return;
+ failed.push(item);
+ }
+ }
if (!current()) return;
- const closed = new Set(items.filter((_, index) => results[index].status === 'fulfilled').map((item) => item.sharedTaskId));
setOwned((value) => value.filter((item) => !closed.has(item.sharedTaskId)));
- const failed = results.length - closed.size;
- setNotice(t(failed ? 'sharedTask.closeFailedToast' : 'sharedTask.closedToast', { count: failed || closed.size }));
+ const failedCount = failed.length;
+ setNotice(t(failedCount ? 'sharedTask.closeFailedToast' : 'sharedTask.closedToast', { count: failedCount || closed.size }));
}, true, { items: items.map((item) => item.title + ' · ' + deviceName(item.hostDeviceId)), note: t('sharedTask.closeAllScopeNote') });
const leave = () => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async (current) => {
await api.leave(guestId!);
diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
index eead409e47..ffcf97865c 100644
--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
@@ -245,6 +245,18 @@ it('closes only the confirmed owned tasks and retains failures for retry', async
expect(element.textContent).toContain('sharedTask.closeFailedToast');
expect(element.textContent).toContain('two'); expect(element.textContent).not.toContain('one');
});
+it('does not start the next batch close after the page account generation changes', async () => {
+ h.params = { sessionId: 'task', deviceId: 'host' };
+ h.api.list.mockResolvedValue([owned('one'), owned('two')]);
+ let finishFirst!: () => void;
+ h.api.close.mockImplementationOnce(() => new Promise<void>((resolve) => { finishFirst = resolve; }));
+ await render(); await click('sharedTask.tabOwned'); await click('sharedTask.closeAll');
+ await act(async () => confirmation()[1].onPress!());
+ expect(h.api.close.mock.calls.map(([id]) => id)).toEqual(['one']);
+ setMobileAuthOwner('other'); h.generation++; await render();
+ await act(async () => finishFirst());
+ expect(h.api.close.mock.calls.map(([id]) => id)).toEqual(['one']);
+});
it('guards current-task close and member removal behind separate confirmations', async () => {
h.params = { sessionId: 'task', deviceId: 'host' }; h.link.invoke.mockResolvedValue({ available: true, detail });
await render(); await click('sharedTask.removeShort');