Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): reconcile already-departed guest removals
DavidShen504fba0a7091
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.tsindex 051810986f..48cc10e11e 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts@@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { createSharedTaskApi, parseSharedTaskSnapshot, type SharedTaskDetail } from '@cindy/device-link';import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks.js';import { SharedTaskHost, type SharedTaskHostOptions } from '../sharedTaskHost.js';+import { executeSharedTaskHostCommand } from '../sharedTaskCommands.js';+import { createIpcError } from '../../../shared/ipc-errors.js';const detail = (revision = 1): SharedTaskDetail => ({sharedTaskId: 'sharedTask', sessionId: 'session', ownerAccountId: 'owner', hostDeviceId: 'desktop',@@ -330,6 +332,51 @@ describe('task host sharedTask lifecycle', () => {expect(canRead()).toBe(false);expect(canRead('b')).toBe(true);});+ it('completes removal through the shared command when the guest already left', async () => {+ await host.open('session');+ const oldPeer = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ api.remove.mockImplementation(async () => {+ serverDetail = { ...detail(2), guests: [detail().guests[1]] };+ throw createIpcError('NOT_FOUND', 'Member no longer joined');+ });+ await expect(executeSharedTaskHostCommand(+ { action: 'remove', sharedTaskId: 'sharedTask', memberId: 'member-a' },+ { available: () => true, host: () => host },+ )).resolves.toEqual({ ok: true });+ expect(host.detail('sharedTask')?.status).toBe('active');+ expect(host.detail('sharedTask')?.guests.map((guest) => guest.memberId)).toEqual(['member-b']);+ expect(oldPeer.isCurrent()).toBe(false);+ expect(canRead()).toBe(false);+ expect(canRead('b')).toBe(true);+ expect(options.revoke).toHaveBeenCalledExactlyOnceWith('sharedTask', 'member-a');+ expect(api.close).not.toHaveBeenCalled();+ });+ it.each(['still-joined', 'closed', 'refresh-failed', 'account-changed'])(+ 'does not treat NOT_FOUND as removal success when %s', async (outcome) => {+ await host.open('session');+ api.remove.mockRejectedValue(createIpcError('NOT_FOUND', 'Missing'));+ if (outcome === 'closed') serverDetail = { ...detail(2), status: 'closed', guests: [] };+ if (outcome === 'refresh-failed') api.get.mockRejectedValueOnce(new Error('offline'));+ if (outcome === 'account-changed') api.get.mockImplementationOnce(async () => {+ current = false; return { ...detail(2), guests: [] };+ });+ await expect(host.remove('sharedTask', 'member-a')).rejects.toThrow();+ if (outcome === 'refresh-failed') {+ expect(canRead()).toBe(false);+ expect(canRead('b')).toBe(true);+ }+ },+ );+ it.each(['PERMISSION_DENIED', 'DEVICE_LINK_NOT_CONNECTED'] as const)(+ 'preserves %s even if the refreshed member has left', async (code) => {+ await host.open('session');+ const error = createIpcError(code, 'Request failed');+ api.remove.mockRejectedValue(error);+ serverDetail = { ...detail(2), guests: [detail().guests[1]] };+ await expect(host.remove('sharedTask', 'member-a')).rejects.toBe(error);+ expect(canRead('b')).toBe(true);+ },+ );it('retains a removal fence on network failure and recovers it only by reconciliation', async () => {await host.open('session');api.remove.mockRejectedValue(new Error('offline'));diff --git a/apps/desktop/src/main/device-link/sharedTaskHost.ts b/apps/desktop/src/main/device-link/sharedTaskHost.tsindex 5f95491865..7a9cccc796 100644--- a/apps/desktop/src/main/device-link/sharedTaskHost.ts+++ b/apps/desktop/src/main/device-link/sharedTaskHost.ts@@ -3,6 +3,7 @@ import {type SharedTaskDetail, type SharedTaskIdentity, type SharedTaskQueueItem,} from '@cindy/device-link';import type { SharedTaskJournal } from '../localDb/sharedTasks.js';+import { isIpcError } from '../../shared/ipc-errors.js';import { SharedTaskAccess } from './sharedTaskAccess.js';interface HostedSharedTask {@@ -244,9 +245,13 @@ export class SharedTaskHost {// Suspend host reads/writes immediately. A failed request can leave this// member authorized, so send permanent revocation only from fresh authority.return this.serial(sharedTaskId, async () => {+ let missingMember: Error | undefined;try {this.requireEntry(sharedTaskId);await this.options.api.remove(sharedTaskId, memberId);+ } catch (error) {+ if (!isIpcError(error) || error.code !== 'NOT_FOUND') throw error;+ missingMember = error;} finally {// On an ambiguous timeout, regain permission only from a fresh authority// response. If reconciliation also fails, this member stays suspended.@@ -261,6 +266,14 @@ export class SharedTaskHost {throw error;}}+ if (missingMember) {+ // A guest may leave while the owner confirms removal. Only a verified,+ // still-active task with that member absent makes removal complete.+ const detail = this.detail(sharedTaskId);+ if (detail?.status !== 'active' || detail.guests.some((guest) => guest.memberId === memberId)) {+ throw missingMember;+ }+ }});}close(sharedTaskId: string): Promise<void> {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 2ee6c06971..e6b1d42678 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@@ -81,6 +81,34 @@ it('keeps invitation request failures distinct and does not attempt to copy', asawait waitFor(() => expect(toast.error).toHaveBeenCalledWith('sharedTask.requestTimedOut'));expect(copy).not.toHaveBeenCalled();});+it.each([false, true])('refreshes members after an already-left removal completes (remote=%s)', async (remote) => {+ let currentDetail: SharedTaskDetail = { ...detail, guests: [+ { memberId: 'left', accountId: 'guest-left', deviceIds: ['phone-a'], version: 1 },+ { memberId: 'staying', accountId: 'guest-staying', deviceIds: ['phone-b'], version: 1 },+ ], memberLabels: [+ { memberId: 'left', displayName: 'Departing Guest', joinedAt: 1 },+ { memberId: 'staying', displayName: 'Remaining Guest', joinedAt: 1 },+ ] };+ const command = vi.fn(async (input: { action: string }) => {+ if (input.action === 'remove') {+ // The host reconciled NOT_FOUND against the active task's fresh members.+ currentDetail = { ...currentDetail, revision: 2, guests: currentDetail.guests.slice(1), memberLabels: currentDetail.memberLabels.slice(1) };+ return { ok: true };+ }+ return { available: true, detail: currentDetail };+ });+ state.host.mockImplementation(command);+ state.invoke.mockImplementation((_peer, _channel, [input]) => command(input));+ const body = await openWindow(remote ? { ...ownerSession, deviceLinkDeviceId: 'owner-computer' } : ownerSession);+ await act(async () => fireEvent.click(within(body).getAllByRole('button', { name: 'sharedTask.removeShort' })[0]));+ await act(async () => fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.remove' })));+ await waitFor(() => expect(body.textContent).not.toContain('Departing Guest'));+ expect(body.textContent).toContain('Remaining Guest');+ expect(within(body).queryByRole('button', { name: 'sharedTask.remove' })).toBeNull();+ expect(within(body).getByRole('button', { name: 'sharedTask.closeCurrent' })).toBeDefined();+ expect(command).toHaveBeenCalledWith({ action: 'remove', sharedTaskId: 'st1', memberId: 'left' });+ expect(toast.error).not.toHaveBeenCalled();+});it('ignores a late unsupported response after the data owner changes', async () => {let reject!: (error: unknown) => void;state.host.mockReturnValue(new Promise((_resolve, fail) => { reject = fail; }));diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsxindex 6ddc25cc8f..23a7ced4ab 100644--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx@@ -178,6 +178,33 @@ it('guards current-task close and member removal behind separate confirmations',await act(async () => confirmation()[1].onPress!());expect(h.link.invoke).toHaveBeenCalledWith('host', 'maker:shared-task', [{ action: 'close', sharedTaskId: 'shared' }]);});+it.each(['ios', 'android'] as const)('%s refreshes members after the host reconciles an already-left removal', async (platform) => {+ Platform.OS = platform;+ h.params = { sessionId: 'task', deviceId: 'host' };+ let currentDetail = { ...detail, memberLabels: [+ { memberId: 'member', displayName: 'Departing Guest' },+ { memberId: 'staying', displayName: 'Remaining Guest' },+ ] };+ h.link.invoke.mockImplementation(async (_peer, _channel, [command]) => {+ if (command.action === 'remove') {+ // SharedTaskHost verified the guest is absent while sharing stays active.+ currentDetail = { ...currentDetail, memberLabels: currentDetail.memberLabels.slice(1) };+ return { ok: true };+ }+ return { available: true, detail: currentDetail };+ });+ await render();+ await click('sharedTask.removeShort');+ await act(async () => confirmation()[1].onPress!());+ expect(h.link.invoke).toHaveBeenCalledWith('host', 'maker:shared-task', [{ action: 'remove', sharedTaskId: 'shared', memberId: 'member' }]);+ expect(element.textContent).not.toContain('Departing Guest');+ expect(element.textContent).toContain('Remaining Guest');+ expect(element.textContent).toContain('sharedTask.closeCurrent');+ expect(element.textContent).not.toContain('sharedTask.unavailable');+ expect(element.textContent).not.toContain('sharedTask.ended');+ expect(h.revoked).not.toHaveBeenCalled();+ expect(h.link.closeLink).not.toHaveBeenCalled();+});it('ignores an old poll after switching away from and back to the current task', async () => {h.params = { sessionId: 'task', deviceId: 'host' };let finishOld!: (value: unknown) => void;