Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): close only confirmed shared task snapshots
DavidShen116b8fc019f0
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsxindex 0397e38d5f..ce5971ab25 100644--- a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx@@ -22,7 +22,7 @@ type ConfirmState =| { kind: 'remove'; memberId: string; name: string }| { kind: 'leave' }| { kind: 'closeCurrent' }- | { kind: 'closeAll' };+ | { kind: 'closeAll'; targets: SharedTaskOwnedItem[] };const tabButton = (active: boolean) => `rounded-full px-3 py-1 text-12 leading-5 transition-colors ${active ? 'bg-[var(--surface-chip)] text-[var(--text-primary)]' : 'text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)]'}`;@@ -118,14 +118,27 @@ export function SharedTaskButton({ session }: { session: Session }) {}if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) toast.success(t('sharedTask.invitationCopied'));});- const closeAll = () => run(async () => {+ const closeAll = (targets: SharedTaskOwnedItem[]) => run(async () => {const captured = epoch.current;const owner = getDataOwnerGeneration();- const result = await window.electronAPI.sharedTask.account({ action: 'close', all: true }) as SharedTaskCloseResult;- if (captured !== epoch.current || !isDataOwnerGenerationCurrent(owner)) return;- setConfirm(null);- if (result.closed.length) toast.success(t('sharedTask.closedToast', { count: result.closed.length }));- if (result.failed.length) toast.error(t('sharedTask.closeFailedToast', { count: result.failed.length }));+ const current = () => captured === epoch.current && isDataOwnerGenerationCurrent(owner);+ const failed: SharedTaskOwnedItem[] = [];+ let closed = 0;+ for (const item of targets) {+ if (!current()) return;+ try {+ const result = await window.electronAPI.sharedTask.account({ action: 'close', sharedTaskId: item.sharedTaskId }) as SharedTaskCloseResult;+ if (!current()) return;+ if (result.closed.includes(item.sharedTaskId)) closed++;+ else failed.push(item);+ } catch {+ if (!current()) return;+ failed.push(item);+ }+ }+ setConfirm(failed.length ? { kind: 'closeAll', targets: failed } : null);+ if (closed) toast.success(t('sharedTask.closedToast', { count: closed }));+ if (failed.length) toast.error(t('sharedTask.closeFailedToast', { count: failed.length }));});const memberName = (memberId: string, fallback: string) =>detail?.memberLabels.find((label) => label.memberId === memberId)?.displayName ?? fallback;@@ -145,8 +158,8 @@ export function SharedTaskButton({ session }: { session: Session }) {run: () => void run(async () => { await host({ action: 'close', sharedTaskId: detail!.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: owned?.length ?? 0 }), danger: true,- run: () => void closeAll() };+ action: t('sharedTask.closeAllAction', { count: state.targets.length }), danger: true,+ run: () => void closeAll(state.targets) };}};const emptyIcon = (icon: React.ReactNode) => <span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]">{icon}</span>;@@ -237,7 +250,7 @@ export function SharedTaskButton({ session }: { session: Session }) {</div><div className="mt-4 border-t border-[var(--border-default)] pt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllNote')}</div><div className="mt-5 flex justify-center"><Button variant="secondary" size="lg" disabled={busy} className="w-full gap-2 text-[var(--error-fg)]"- onClick={() => setConfirm({ kind: 'closeAll' })}><CircleStop size={18} aria-hidden />{t('sharedTask.closeAll', { count: owned.length })}</Button></div>+ onClick={() => setConfirm({ kind: 'closeAll', targets: owned.map((item) => ({ ...item })) })}><CircleStop size={18} aria-hidden />{t('sharedTask.closeAll', { count: owned.length })}</Button></div></>;const confirmation = confirm ? confirmCopy(confirm) : null;return <>@@ -269,7 +282,7 @@ export function SharedTaskButton({ session }: { session: Session }) {confirmVariant="destructive" descriptionClassName="text-13" loading={busy} zIndex={10002} maxWidth={440} onConfirm={confirmation?.run}content={confirm?.kind === 'closeAll' ? <><div className="space-y-2 rounded-lg bg-[var(--surface-chip)] p-3 text-12">- {(owned ?? []).map((item) => <div key={item.sharedTaskId} className="break-words">{item.title} <span className="text-[var(--text-secondary)]">· {item.local ? t('sharedTask.thisDevice') : t('sharedTask.otherDevice')}</span></div>)}+ {confirm.targets.map((item) => <div key={item.sharedTaskId} className="break-words">{item.title} <span className="text-[var(--text-secondary)]">· {item.local ? t('sharedTask.thisDevice') : t('sharedTask.otherDevice')}</span></div>)}</div><p className="mt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllScopeNote')}</p></> : undefined} /></Dialog.Content>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.tsxindex e6e5cdb494..ab2f8e92e9 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@@ -3,12 +3,12 @@ import { createElement } from 'react';import { act, fireEvent, waitFor, within } from '@testing-library/react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import { sharedTaskHostPeer, type SharedTaskDetail } from '@cindy/device-link';+import { sharedTaskHostPeer, type SharedTaskCloseResult, type SharedTaskDetail, type SharedTaskOwnedItem } from '@cindy/device-link';import { SharedTaskButton } from '../SharedTaskButton';import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import type { Session } from '@/lib/ccAgent.types';import { toast } from '@/lib/toast';-const state = vi.hoisted(() => ({ invoke: vi.fn(), host: vi.fn(), account: vi.fn(), t: (key: string) => key }));+const state = vi.hoisted(() => ({ invoke: vi.fn(), host: vi.fn(), account: vi.fn(), t: vi.fn((key: string, _options?: unknown) => key) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'owner' }) }));vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));@@ -120,15 +120,18 @@ it('ignores a late unsupported response after the data owner changes', async ()await act(async () => reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] unsupported')));expect(body.textContent).not.toContain('sharedTask.upgrade');});-it('lists owned shares and routes close-all through the account command', async () => {- state.account.mockImplementation((command: { action: string }) => {+it('keeps the confirmed snapshot when an owned-list refresh completes before closing', async () => {+ let refresh!: (items: SharedTaskOwnedItem[]) => void;+ let reads = 0;+ state.account.mockImplementation((command: { action: string; sharedTaskId?: string }) => {if (command.action === 'owned') {+ if (++reads === 2) return new Promise<SharedTaskOwnedItem[]>((resolve) => { refresh = resolve; });return Promise.resolve([{ sharedTaskId: 'st1', sessionId: 'session-1', ownerAccountId: 'owner', hostDeviceId: 'device-a', title: 'Task A', revision: 1, local: true },{ sharedTaskId: 'st9', sessionId: 'session-9', ownerAccountId: 'owner', hostDeviceId: 'device-b', title: 'Task B', revision: 1, local: false },]);}- if (command.action === 'close') return Promise.resolve({ closed: ['st1', 'st9'], failed: [] });+ if (command.action === 'close') return Promise.resolve({ closed: [command.sharedTaskId], failed: [] });return Promise.resolve(detail);});const body = await openWindow(ownerSession);@@ -151,8 +154,68 @@ it('lists owned shares and routes close-all through the account command', async'sharedTask.closeAllKeep', 'sharedTask.closeAllAction',]);expect(body.textContent).toContain('Task B');+ await act(async () => refresh([{ ...detail, sharedTaskId: 'new-share', title: 'New Task', local: false }]));+ expect(body.textContent).toContain('New Task');+ expect(confirmation.textContent).not.toContain('New Task');+ expect(confirmation.textContent).toContain('Task A');+ expect(confirmation.textContent).toContain('Task B');+ expect(state.t.mock.calls.filter(([key]) => key === 'sharedTask.closeAllAction').at(-1)).toEqual(['sharedTask.closeAllAction', { count: 2 }]);await act(async () => { fireEvent.click([...body.querySelectorAll('button')].find((b) => b.textContent?.startsWith('sharedTask.closeAllAction'))!); });- await waitFor(() => expect(state.account).toHaveBeenCalledWith({ action: 'close', all: true }));+ expect(state.account.mock.calls.filter(([command]) => command.action === 'close')).toEqual([+ [{ action: 'close', sharedTaskId: 'st1' }],+ [{ action: 'close', sharedTaskId: 'st9' }],+ ]);+ expect(within(body).queryByRole('alertdialog')).toBeNull();+});+it.each(['response', 'rejection'])('retries only failed snapshot items after a close %s', async (failure) => {+ let retry = false;+ const items = [+ { ...detail, local: true },+ { ...detail, sharedTaskId: 'st9', title: 'Task B', local: false },+ ];+ state.account.mockImplementation(async (command: { action: string; sharedTaskId?: string }) => {+ if (command.action === 'owned') return retry ? [{ ...detail, sharedTaskId: 'new-share', title: 'New Task', local: true }] : items;+ if (command.sharedTaskId === 'st1' && !retry) {+ if (failure === 'rejection') throw new Error('offline');+ return { closed: [], failed: [{ sharedTaskId: 'st1' }] };+ }+ return { closed: [command.sharedTaskId], failed: [] };+ });+ const body = await openWindow(ownerSession);+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: /sharedTask.tabOwned/ })));+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.closeAll' })));+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.closeAllAction' })));+ const confirmation = within(body).getByRole('alertdialog');+ expect(confirmation.textContent).toContain('Task A');+ expect(confirmation.textContent).not.toContain('Task B');+ expect(state.t.mock.calls.filter(([key]) => key === 'sharedTask.closeAllAction').at(-1)).toEqual(['sharedTask.closeAllAction', { count: 1 }]);+ expect(toast.error).toHaveBeenCalledWith('sharedTask.closeFailedToast');+ retry = true;+ await act(async () => fireEvent.click(within(confirmation).getByRole('button', { name: 'sharedTask.closeAllAction' })));+ expect(state.account.mock.calls.filter(([command]) => command.action === 'close')).toEqual([+ [{ action: 'close', sharedTaskId: 'st1' }],+ [{ action: 'close', sharedTaskId: 'st9' }],+ [{ action: 'close', sharedTaskId: 'st1' }],+ ]);+ expect(within(body).queryByRole('alertdialog')).toBeNull();+});+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'+ ? Promise.resolve([{ ...detail, local: true }, { ...detail, sharedTaskId: 'st9', title: 'Task B', local: false }])+ : new Promise<SharedTaskCloseResult>((resolve) => { finish = resolve; }));+ const body = await openWindow(ownerSession);+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: /sharedTask.tabOwned/ })));+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.closeAll' })));+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.closeAllAction' })));+ if (invalidation === 'account change') setDataOwnerGeneration('other');+ else await act(async () => root.render(null));+ await act(async () => finish({ closed: ['st1'], failed: [] }));+ expect(state.account.mock.calls.filter(([command]) => command.action === 'close')).toEqual([+ [{ action: 'close', sharedTaskId: 'st1' }],+ ]);+ expect(toast.success).not.toHaveBeenCalled();+ expect(toast.error).not.toHaveBeenCalled();});it('keeps the member screen behind a named removal confirmation and cancels without removing', async () => {state.host.mockResolvedValue({ available: true, detail: { ...detail,