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): clarify rejected device deletion after refreshing status

creed69ae90b60baa
diff --git a/apps/mobile/src/__tests__/useDeviceManagement.test.tsx b/apps/mobile/src/__tests__/useDeviceManagement.test.tsx
index f6f9aeaf25..f6da5ff706 100644
--- a/apps/mobile/src/__tests__/useDeviceManagement.test.tsx
+++ b/apps/mobile/src/__tests__/useDeviceManagement.test.tsx
@@ -3,6 +3,8 @@ import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import type { DeviceView } from '@cindy/device-link';
+import { i18n } from '@/i18n';
+import { apiFetchRaw, registerAccountUnavailableHandler } from '@/api/client';
import { useDeviceManagement } from '@/device-link/useDeviceManagement';
import {
setMobileAuthOwner,
@@ -76,6 +78,8 @@ beforeEach(() => {
});
afterEach(() => {
act(() => root.unmount());
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
});
it('keeps the last device list on refresh failure and can retry', async () => {
@@ -381,3 +385,244 @@ it.each(['rename', 'delete'] as const)(
expect(mocks.setDeviceIdentity).not.toHaveBeenCalled();
},
);
+
+// #7742: exercise the real hook's rejected-delete path. A fresh offline list
+// must not produce the online-device explanation or clear access projections.
+it.each([
+ [false, 'offline', 'deleteRejectedWhileOffline'],
+ [true, 'offline', 'deleteRejectedWhileOffline'],
+ [false, 'online', 'deleteOnline'],
+ [false, 'missing', 'deleteFailed'],
+ [false, 'failure', 'deleteOnline'],
+ [false, 'timeout', 'deleteOnline'],
+] as const)(
+ 'explains rejected deletion from the fresh list (%s -> %s)',
+ async (online, outcome, message) => {
+ const target = { ...device, online, name: 'Known Mac' };
+ apiFetch.mockResolvedValueOnce({ devices: [target] });
+ await render();
+ act(() => state.openDelete(target));
+ apiFetch.mockRejectedValueOnce(
+ Object.assign(new Error('online'), { code: 'ALREADY_EXISTS' }),
+ );
+ const refreshed =
+ outcome === 'missing'
+ ? []
+ : [{ ...target, online: outcome === 'online', name: 'unknown' }];
+ const failed = outcome === 'failure' || outcome === 'timeout';
+ if (failed)
+ apiFetch.mockRejectedValueOnce(
+ Object.assign(new Error(outcome), {
+ code:
+ outcome === 'timeout' ? 'REQUEST_TIMEOUT' : 'NETWORK_UNAVAILABLE',
+ }),
+ );
+ else apiFetch.mockResolvedValueOnce({ devices: refreshed });
+ await act(async () => expect(await state.confirmDelete()).toBe(false));
+ expect(apiFetch).toHaveBeenCalledTimes(3);
+ expect(apiFetch).toHaveBeenLastCalledWith(
+ '/api/device-link/devices',
+ expect.objectContaining({
+ baseUrl: 'https://relay.example.invalid',
+ timeoutMs: 5_000,
+ }),
+ );
+ expect(state.deleteError).toBe(i18n.t(`devices.management.${message}`));
+ expect(state.deleteTarget).toEqual(target);
+ expect(state.deleteSaving).toBe(false);
+ expect(state.devices).toEqual(
+ failed
+ ? [target]
+ : refreshed.map((item) => ({ ...item, name: 'Known Mac' })),
+ );
+ expect(mocks.removeDevice).not.toHaveBeenCalled();
+ expect(mocks.clearRevoked).not.toHaveBeenCalled();
+ expect(mocks.setDeviceIdentity).not.toHaveBeenCalled();
+ },
+);
+
+it('keeps the rejected-delete refresh bounded to one request while the dialog is busy', async () => {
+ await render();
+ act(() => state.openDelete(device));
+ const list = deferred<{ devices: DeviceView[] }>();
+ apiFetch
+ .mockRejectedValueOnce(
+ Object.assign(new Error('online'), { code: 'ALREADY_EXISTS' }),
+ )
+ .mockReturnValueOnce(list.promise);
+ let request!: Promise<boolean>;
+ await act(async () => {
+ request = state.confirmDelete();
+ });
+ expect(state.deleteSaving).toBe(true);
+ await act(async () => {
+ expect(await state.confirmDelete()).toBe(false);
+ state.refresh();
+ state.closeDelete();
+ });
+ expect(apiFetch).toHaveBeenCalledTimes(3);
+ expect(state.deleteTarget).toEqual(device);
+ await act(async () => {
+ list.resolve({ devices: [{ ...device, online: false }] });
+ expect(await request).toBe(false);
+ });
+ expect(state.deleteError).toBe(
+ i18n.t('devices.management.deleteRejectedWhileOffline'),
+ );
+ expect(state.deleteSaving).toBe(false);
+});
+
+it.each(['owner change', 'unmount'] as const)(
+ 'ignores a rejected-delete refresh after %s',
+ async (change) => {
+ setMobileAuthOwner('account-a');
+ await render();
+ act(() => state.openDelete(device));
+ const list = deferred<{ devices: DeviceView[] }>();
+ apiFetch
+ .mockRejectedValueOnce(
+ Object.assign(new Error('online'), { code: 'ALREADY_EXISTS' }),
+ )
+ .mockReturnValueOnce(list.promise);
+ let request!: Promise<boolean>;
+ await act(async () => {
+ request = state.confirmDelete();
+ });
+ expect(apiFetch).toHaveBeenCalledTimes(3);
+ if (change === 'owner change') setMobileAuthOwner('account-b');
+ else {
+ apiFetch.mockResolvedValue({ devices: [] });
+ await render('account-b');
+ }
+ await act(async () => {
+ list.resolve({
+ devices: [{ ...device, name: 'Old account', online: false }],
+ });
+ expect(await request).toBe(false);
+ });
+ expect(state.devices).toEqual(change === 'owner change' ? [device] : []);
+ expect(state.deleteError).toBeNull();
+ expect(mocks.setDeviceIdentity).not.toHaveBeenCalled();
+ expect(mocks.removeDevice).not.toHaveBeenCalled();
+ },
+);
+
+it('does not refresh after a non-conflict deletion failure', async () => {
+ await render();
+ act(() => state.openDelete(device));
+ apiFetch.mockRejectedValueOnce(new Error('network unavailable'));
+ await act(async () => expect(await state.confirmDelete()).toBe(false));
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ expect(state.deleteError).toBe('network unavailable');
+});
+
+it('ends the rejected-delete wait after five seconds and ignores a late list through the real API client', async () => {
+ const target = { ...device, online: false };
+ const late = deferred<{
+ ok: boolean;
+ status: number;
+ json(): Promise<unknown>;
+ }>();
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({ devices: [target] }),
+ })
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ json: async () => ({
+ error: { code: 'ALREADY_EXISTS', message: 'online' },
+ }),
+ })
+ .mockReturnValueOnce(late.promise);
+ vi.stubGlobal('fetch', fetch);
+ apiFetch.mockImplementation(apiFetchRaw);
+ await render();
+ act(() => state.openDelete(target));
+ vi.useFakeTimers();
+ let request!: Promise<boolean>;
+ await act(async () => {
+ request = state.confirmDelete();
+ });
+ expect(state.deleteSaving).toBe(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_999);
+ });
+ expect(state.deleteSaving).toBe(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ expect(await request).toBe(false);
+ });
+ expect(state.deleteSaving).toBe(false);
+ expect(state.deleteError).toBe(i18n.t('devices.management.deleteOnline'));
+ await act(async () => {
+ late.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({ devices: [] }),
+ });
+ });
+ expect(state.devices).toEqual([target]);
+ expect(state.deleteTarget).toEqual(target);
+ expect(mocks.removeDevice).not.toHaveBeenCalled();
+});
+
+it('does not terminate the new account when the rejected-delete refresh returns a stale auth failure', async () => {
+ setMobileAuthOwner('account-a');
+ const late = deferred<{
+ ok: boolean;
+ status: number;
+ json(): Promise<unknown>;
+ }>();
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({ devices: [device] }),
+ })
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ json: async () => ({
+ error: { code: 'ALREADY_EXISTS', message: 'online' },
+ }),
+ })
+ .mockReturnValueOnce(late.promise),
+ );
+ apiFetch.mockImplementation(apiFetchRaw);
+ const terminate = vi.fn();
+ const unregister = registerAccountUnavailableHandler(terminate);
+ try {
+ await render();
+ act(() => state.openDelete(device));
+ let request!: Promise<boolean>;
+ await act(async () => {
+ request = state.confirmDelete();
+ });
+ setMobileAuthOwner('account-b');
+ await act(async () => {
+ late.resolve({
+ ok: false,
+ status: 401,
+ json: async () => ({
+ error: {
+ code: 'ACCOUNT_UNAVAILABLE',
+ message: 'account unavailable',
+ },
+ }),
+ });
+ expect(await request).toBe(false);
+ });
+ expect(terminate).not.toHaveBeenCalled();
+ expect(state.devices).toEqual([device]);
+ expect(state.deleteError).toBeNull();
+ } finally {
+ unregister();
+ }
+});
diff --git a/apps/mobile/src/device-link/useDeviceManagement.ts b/apps/mobile/src/device-link/useDeviceManagement.ts
index ca7f04735f..c9fd94bdca 100644
--- a/apps/mobile/src/device-link/useDeviceManagement.ts
+++ b/apps/mobile/src/device-link/useDeviceManagement.ts
@@ -19,6 +19,24 @@ import { MAX_DEVICE_NAME_LENGTH } from './deviceName';
type ApiFetch = <T>(path: string, options: ApiFetchOptions) => Promise<T>;
const DEVICE_TIMEOUT_MS = 8_000;
+const REJECTED_DELETE_REFRESH_TIMEOUT_MS = 5_000;
+
+function reconcileListedDevices(incoming: DeviceView[], current: DeviceView[]) {
+ // Prefer home's latest valid identities, falling back to this account's
+ // last successful view. No extra persistent cache is needed.
+ const known = [...current, ...remoteSessionStore.getDeviceIdentity()];
+ const cache = hydrateDeviceIdentityCache({
+ names: Object.fromEntries(
+ known
+ .filter((item) => normalizeDeviceDisplayName(item.name))
+ .map((item) => [item.deviceId, item.name]),
+ ),
+ order: Object.fromEntries(
+ known.map((item, index) => [item.deviceId, index]),
+ ),
+ });
+ return reconcileDeviceIdentities(incoming, cache).devices;
+}
/** The screen is keyed by accountGeneration so a previous account never shares this state. */
export function useDeviceManagement(apiFetch: ApiFetch, focused: boolean) {
@@ -63,20 +81,7 @@ export function useDeviceManagement(apiFetch: ApiFetch, focused: boolean) {
if (!isCurrent()) return;
setDevices((current) => {
if (!isCurrent()) return current;
- // Prefer home's latest valid identities, falling back to this account's
- // last successful view. No extra persistent cache is needed.
- const known = [...current, ...remoteSessionStore.getDeviceIdentity()];
- const cache = hydrateDeviceIdentityCache({
- names: Object.fromEntries(
- known
- .filter((item) => normalizeDeviceDisplayName(item.name))
- .map((item) => [item.deviceId, item.name]),
- ),
- order: Object.fromEntries(
- known.map((item, index) => [item.deviceId, index]),
- ),
- });
- return reconcileDeviceIdentities(result.devices, cache).devices;
+ return reconcileListedDevices(result.devices, current);
});
})
.catch((cause) => {
@@ -227,12 +232,47 @@ export function useDeviceManagement(apiFetch: ApiFetch, focused: boolean) {
setDeleteTarget(null);
return true;
} catch (cause) {
- if (isCurrent())
- setDeleteError(
- (cause as { code?: string })?.code === 'ALREADY_EXISTS'
- ? i18n.t('devices.management.deleteOnline')
- : formatRemoteError(cause),
+ if (!isCurrent()) return false;
+ if ((cause as { code?: string })?.code !== 'ALREADY_EXISTS') {
+ setDeleteError(formatRemoteError(cause));
+ return false;
+ }
+ // A rejection is not proof that the device is online in the list (#7742).
+ // The editor/saving guards prevent a competing refresh while this runs.
+ let message = i18n.t('devices.management.deleteOnline');
+ try {
+ const result = await apiFetch<{ devices: DeviceView[] }>(
+ '/api/device-link/devices',
+ {
+ baseUrl: DEVICE_LINK_API_BASE_URL,
+ timeoutMs: REJECTED_DELETE_REFRESH_TIMEOUT_MS,
+ cache: 'no-store',
+ assertCurrent: () => {
+ if (!isCurrent()) throw new Error('STALE_DEVICE_MANAGEMENT');
+ },
+ },
);
+ if (!isCurrent()) return false;
+ const listed = result.devices.find(
+ (item) => item.deviceId === target.deviceId,
+ );
+ setDevices((current) =>
+ isCurrent()
+ ? reconcileListedDevices(result.devices, current)
+ : current,
+ );
+ message = i18n.t(
+ !listed
+ ? 'devices.management.deleteFailed'
+ : listed.online
+ ? 'devices.management.deleteOnline'
+ : 'devices.management.deleteRejectedWhileOffline',
+ );
+ } catch {
+ // Keep the previous list and the existing rejection message on failure
+ // or timeout. Only a confirmed DELETE may clear shared device state.
+ }
+ if (isCurrent()) setDeleteError(message);
return false;
} finally {
if (isCurrent()) {
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index d4d92d17b0..a6651f4aef 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -11,6 +11,7 @@
"deleteMessage": "Remove this device from your account and disconnect remote access. Its sessions and files are kept. Sign in again on that device to rejoin.",
"deleteFailed": "Could not delete the device.",
"deleteOnline": "This server does not yet support removing online devices. Retry after the service is upgraded.",
+ "deleteRejectedWhileOffline": "Couldn’t delete the device: the server still lists it as online, although it shows as offline here.",
"currentlyOnline": "Currently online",
"availableSection": "Online",
"offlineSection": "Offline",
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index bc8d452675..7f4585131b 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -11,6 +11,7 @@
"deleteMessage": "アカウントからこのデバイスを削除し、リモート接続を切断します。デバイス上のセッションとファイルは保持されます。再度ログインすると追加できます。",
"deleteFailed": "デバイスを削除できませんでした。",
"deleteOnline": "現在のサーバーはオンラインのデバイス削除に未対応です。サービス更新後に再試行してください。",
+ "deleteRejectedWhileOffline": "デバイスを削除できませんでした。一覧ではオフラインですが、サーバーではまだオンラインとして記録されています。",
"currentlyOnline": "現在オンライン",
"availableSection": "オンラインのデバイス",
"offlineSection": "オフラインのデバイス",
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index 428b115837..6ae4232a77 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -11,6 +11,7 @@
"deleteMessage": "계정에서 이 기기를 제거하고 원격 연결을 끊습니다. 기기의 세션과 파일은 유지됩니다. 해당 기기에서 다시 로그인하면 추가할 수 있습니다.",
"deleteFailed": "기기를 삭제하지 못했습니다.",
"deleteOnline": "현재 서버는 온라인 기기 제거를 지원하지 않습니다. 서비스 업데이트 후 다시 시도하세요.",
+ "deleteRejectedWhileOffline": "기기를 삭제하지 못했습니다. 목록에서는 오프라인이지만 서버에는 아직 온라인으로 기록되어 있습니다.",
"currentlyOnline": "현재 온라인",
"availableSection": "온라인 기기",
"offlineSection": "오프라인 기기",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 3e99f884a2..be672b7730 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -11,6 +11,7 @@
"deleteMessage": "将此设备从账号中移除并断开远程连接。设备上的任务和文件会保留,重新登录后可再次加入。",
"deleteFailed": "删除设备失败。",
"deleteOnline": "当前服务端尚不支持移除在线设备,请待服务升级后重试。",
+ "deleteRejectedWhileOffline": "未能删除设备:服务端仍将它记为在线,与列表中的离线状态不一致",
"currentlyOnline": "当前在线",
"availableSection": "在线设备",
"offlineSection": "离线设备",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index 57d27bd803..cfbf2bb489 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -11,6 +11,7 @@
"deleteMessage": "將此裝置從帳號中移除並中斷遠端連線。裝置上的任務和檔案會保留,重新登入後可再次加入。",
"deleteFailed": "刪除裝置失敗。",
"deleteOnline": "目前伺服器尚不支援移除線上裝置,請待服務升級後重試。",
+ "deleteRejectedWhileOffline": "未能刪除裝置:伺服器仍將它記為線上,與清單中的離線狀態不一致",
"currentlyOnline": "目前在線",
"availableSection": "在線裝置",
"offlineSection": "離線裝置",