Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 恢复设备直接筛选并集中设备管理 (#3970)
Dash6976af5fdffc
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex d1ddcfe1e0..d483ef75e9 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -20,7 +20,7 @@ import {type TextStyle,type ViewStyle,} from 'react-native';-import { Text, TextInput } from '@/components/AppText';+import { Text } from '@/components/AppText';import { DeviceLinkError, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';import {Archive,@@ -75,7 +75,6 @@ import {buildHomeDisplayPullDownActions,buildHomeScopePullDownActions,homeDisplayMenuPatch,- parseHomeScopePullDownAction,type HomeDisplayMenuKey,} from '@/session/homeChromeMenus';import { useConversationSearchFilterMenu } from '@/session/useConversationSearchFilterMenu';@@ -443,12 +442,9 @@ function HomeScreenContent() {const [loggingOut, setLoggingOut] = useState(false);// 菜单关闭动画完成(Modal 卸载)后要执行的动作。iOS 上两个兄弟 Modal 重叠时,第二个 Modal// 是叠在菜单 Modal 的 VC 上 present 的,菜单淡出后卸载会把它连带 dismiss 掉——所以从菜单里- // 打开重命名 / 撤销授权弹窗必须等菜单完全卸载(onClosed)后再挂载,不能同一帧直接 set。+ // 打开账号切换 / 撤销授权弹窗必须等菜单完全卸载(onClosed)后再挂载,不能同一帧直接 set。const pendingMenuActionRef = useRef<(() => void) | null>(null);const pendingAccountSwitcherActionRef = useRef<(() => void) | null>(null);- const [renameTarget, setRenameTarget] = useState<MobileHomeDeviceFilterItem | null>(null);- const [renameDraft, setRenameDraft] = useState('');- const [renameSaving, setRenameSaving] = useState(false);const {actionSheetSession,archiveSession,@@ -542,9 +538,6 @@ function HomeScreenContent() {setHostProjectOrders(new Map());setRevokedTipDeviceId(null);setRetryingDeviceIds(new Set());- setRenameTarget(null);- setRenameDraft('');- setRenameSaving(false);setProjectDrag(null);}, [accountGeneration]);@@ -1354,23 +1347,6 @@ function HomeScreenContent() {// probe invoke clears the revoked mark on success; the tip-close effect handles dismissal.}, [accountGeneration, probeRevokedDeviceAccess]);- const openRenameDevice = useCallback((item: MobileHomeDeviceFilterItem) => {- if (!item.deviceId) return;- const begin = () => {- setRenameTarget(item);- setRenameDraft(item.label);- setError(null);- };- // 自定义范围菜单还没卸掉时不能直接挂重命名 Modal。- // 原生 UIMenu 没有这层 Modal,可以立刻打开。- if (deviceMenuOpen) {- pendingMenuActionRef.current = begin;- setDeviceMenuOpen(false);- return;- }- begin();- }, [deviceMenuOpen]);-// 菜单 Modal 完全关闭(淡出结束 + 卸载)后,执行延后的弹窗动作。const handleDeviceMenuClosed = useCallback(() => {const action = pendingMenuActionRef.current;@@ -1415,55 +1391,6 @@ function HomeScreenContent() {setHeaderFrosted((current) => (current === next ? current : next));}, [homeScrollY]);- const closeRenameDevice = useCallback(() => {- if (renameSaving) return;- setRenameTarget(null);- setRenameDraft('');- }, [renameSaving]);-- const confirmRenameDevice = useCallback(async () => {- const expectedAccountGeneration = accountGeneration;- const target = renameTarget;- const name = renameDraft.trim();- if (!target?.deviceId || !name || renameSaving) return;- if (name === target.label.trim()) {- setRenameTarget(null);- setRenameDraft('');- return;- }-- setRenameSaving(true);- try {- const res = await apiFetch<{ deviceId: string; name: string }>(- `/api/device-link/devices/${encodeURIComponent(target.deviceId)}`,- {- baseUrl: DEVICE_LINK_API_BASE_URL,- body: { name },- method: 'PATCH',- timeoutMs: DEVICE_LIST_TIMEOUT_MS,- },- );- if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;- const nextName = res.name;- setDevices((current) => {- const nextRaw = current.map((device) =>- device.deviceId === target.deviceId ? { ...device, name: nextName } : device);- const next = reconcileDeviceViews(nextRaw).devices;- devicesRef.current = next;- return next;- });- remoteSessionStore.renameDevice(target.deviceId, nextName);- setRenameTarget(null);- setRenameDraft('');- void loadHome({ visible: false });- } catch (err) {- if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;- setError(formatRemoteError(err));- } finally {- if (homeAccountGenerationRef.current === expectedAccountGeneration) setRenameSaving(false);- }- }, [accountGeneration, apiFetch, loadHome, reconcileDeviceViews, renameDraft, renameSaving, renameTarget]);-const deviceRows = useMemo(() => toDeviceListItems(devices, Date.now(), revokedDevices),[devices, i18nInstance.resolvedLanguage, revokedDevices],@@ -2384,33 +2311,13 @@ function HomeScreenContent() {() => buildHomeScopePullDownActions(home.deviceFilters,t('devices.list.allConversations'),- {- openLabel: t('devices.list.menu.openDevice'),- renameLabel: t('devices.list.menu.renameDevice'),- showTasksLabel: t('devices.list.menu.showDeviceTasks'),- },),[home.deviceFilters, t],);const handleHomeScopeAction = useCallback((id: string) => {- const parsed = parseHomeScopePullDownAction(id);- if (parsed.kind === 'open') {- const item = home.deviceFilters.find((filter) => filter.deviceId === parsed.deviceId);- if (!item?.deviceId) return;- guardedPush({- pathname: '/devices/[deviceId]',- params: { deviceId: item.deviceId, name: item.label },- });- return;- }- if (parsed.kind === 'rename') {- const item = home.deviceFilters.find((filter) => filter.deviceId === parsed.deviceId);- if (item) openRenameDevice(item);- return;- }- const item = home.deviceFilters.find((filter) => filter.id === parsed.filterId);+ const item = home.deviceFilters.find((filter) => filter.id === id);if (item) selectHomeScope(item);- }, [guardedPush, home.deviceFilters, openRenameDevice, selectHomeScope]);+ }, [home.deviceFilters, selectHomeScope]);const homeDisplayPullDownActions = useMemo(() => buildHomeDisplayPullDownActions({groupByProject,@@ -2729,15 +2636,6 @@ function HomeScreenContent() {filters={home.deviceFilters}onClose={() => setDeviceMenuOpen(false)}onClosed={handleDeviceMenuClosed}- onOpenDevice={(item) => {- if (!item.deviceId) return;- setDeviceMenuOpen(false);- guardedPush({- pathname: '/devices/[deviceId]',- params: { deviceId: item.deviceId, name: item.label },- });- }}- onRenameDevice={openRenameDevice}onSelect={(item) => {if (item.deviceId && item.state === 'access_revoked') {// 撤销授权提示同样是兄弟 Modal,必须等菜单卸载后再挂(见 pendingMenuActionRef 注释)。@@ -2779,6 +2677,12 @@ function HomeScreenContent() {setChromeMenuCloseInstant(false);setChromeMenuOpen(false);}}+ onOpenDevices={() => {+ pendingMenuActionRef.current = null;+ guardedPush('/devices/manage');+ setChromeMenuCloseInstant(true);+ setChromeMenuOpen(false);+ }}onOpenSettings={() => {pendingMenuActionRef.current = null;guardedPush('/settings');@@ -2836,14 +2740,6 @@ function HomeScreenContent() {topOffset={chromeHeight}visible={displaySettingsOpen}/>- <RenameDeviceModal- draft={renameDraft}- onCancel={closeRenameDevice}- onChangeDraft={setRenameDraft}- onConfirm={confirmRenameDevice}- saving={renameSaving}- visible={renameTarget !== null}- /><SessionOptionsPresenteronAction={handleSessionSheetAction}onClose={() => setActionSheetSession(null)}@@ -2882,8 +2778,6 @@ function DeviceMenuModal({filters,onClose,onClosed,- onOpenDevice,- onRenameDevice,onSelect,topOffset,visible,@@ -2893,8 +2787,6 @@ function DeviceMenuModal({onClose(): void;/** 淡出动画完成、Modal 真正卸载后触发;父级用它把「打开第二个 Modal」延后到菜单卸载之后。 */onClosed?(): void;- onOpenDevice(item: MobileHomeDeviceFilterItem): void;- onRenameDevice(item: MobileHomeDeviceFilterItem): void;onSelect(item: MobileHomeDeviceFilterItem): void;topOffset: number;visible: boolean;@@ -2945,9 +2837,7 @@ function DeviceMenuModal({dimmed={!item.available && item.state !== 'access_revoked'}key={item.id}label={item.label}- onLongPress={item.deviceId ? () => onOpenDevice(item) : undefined}onPress={() => onSelect(item)}- onRename={item.deviceId ? () => onRenameDevice(item) : undefined}selected={item.selected}status={deviceMenuStatus(item)}testID={item.deviceId ? `home.deviceChip.${sanitizeDeviceChipTestId(item.deviceId)}` : undefined}@@ -3091,9 +2981,7 @@ function DeviceMenuItem({dimmed = false,icon,label,- onLongPress,onPress,- onRename,selected,status,testID,@@ -3103,24 +2991,20 @@ function DeviceMenuItem({dimmed?: boolean;icon?: ReactNode;label: string;- onLongPress?: () => void;onPress(): void;- onRename?: () => void;selected: boolean;status?: 'online' | 'offline';testID?: string;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();- const { t } = useTranslation();const rowDisabled = dimmed;return (<PressableaccessibilityLabel={label}accessibilityRole="button"accessibilityState={{ checked: checked || undefined, disabled: rowDisabled, selected: selected || undefined }}- disabled={rowDisabled && !onRename}- onLongPress={rowDisabled ? undefined : onLongPress}+ disabled={rowDisabled}onPress={() => {if (rowDisabled) return;onPress();@@ -3145,91 +3029,10 @@ function DeviceMenuItem({{connectionState === 'failed' ? <View style={styles.deviceConnectionFailedRing} /> : null}</View>) : null}- {onRename ? (- <Pressable- accessibilityLabel={t('devices.list.a11y.renameDevice', { label })}- accessibilityRole="button"- hitSlop={8}- onPress={(event) => {- event.stopPropagation();- onRename();- }}- style={({ pressed }) => [styles.deviceMenuRenameButton, pressed && styles.pressed]}- testID={testID ? `${testID}.rename` : undefined}- >- <Pencil color={colors.textSecondary} size={iconSize.lg} strokeWidth={iconStroke.regular} />- </Pressable>- ) : null}</Pressable>);}-function RenameDeviceModal({- draft,- onCancel,- onChangeDraft,- onConfirm,- saving,- visible,-}: {- draft: string;- onCancel(): void;- onChangeDraft(value: string): void;- onConfirm(): void;- saving: boolean;- visible: boolean;-}) {- const styles = useThemedStyles(makeStyles);- const { colors } = useTheme();- const { t } = useTranslation();- const canSave = draft.trim().length > 0 && !saving;- return (- <Modal animationType="fade" transparent visible={visible} onRequestClose={onCancel}>- <Pressable style={styles.renameDeviceBackdrop} onPress={onCancel} testID="home.renameDevice.backdrop">- <Pressable style={styles.renameDeviceCard} onPress={() => undefined} testID="home.renameDevice.modal">- <Text style={styles.renameDeviceTitle}>{t('devices.list.renameDevice.title')}</Text>- <TextInput- autoFocus- editable={!saving}- maxLength={64}- onChangeText={onChangeDraft}- onSubmitEditing={() => {- if (canSave) onConfirm();- }}- placeholder={t('devices.list.renameDevice.placeholder')}- placeholderTextColor={colors.textTertiary}- returnKeyType="done"- selectTextOnFocus- style={styles.renameDeviceInput}- testID="home.renameDevice.input"- value={draft}- />- {/* 确认对统一规则:共享满宽纵排组(保存在上/取消居底),置于卡片底部。 */}- <MainWindowActionGroup- primaryActions={[{- accessibilityLabel: saving ? t('devices.list.renameDevice.savingA11y') : t('devices.list.renameDevice.saveA11y'),- busy: saving,- disabled: !canSave,- label: saving ? t('devices.common.saving') : t('devices.common.save'),- onPress: onConfirm,- testID: 'home.renameDevice.save',- tone: 'primary',- }]}- cancelAction={{- accessibilityLabel: t('devices.list.a11y.cancelRename'),- disabled: saving,- label: t('devices.common.cancel'),- onPress: onCancel,- testID: 'home.renameDevice.cancel',- }}- testID="home.renameDevice.actions"- />- </Pressable>- </Pressable>- </Modal>- );-}-function RevokedAccessTip({deviceName,onClose,@@ -4606,53 +4409,12 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({position: 'relative',width: 20,},- deviceMenuRenameButton: {- alignItems: 'center',- borderRadius: radius.pill,- height: 34,- justifyContent: 'center',- width: 34,- },deviceMenuDivider: {backgroundColor: colors.border,height: StyleSheet.hairlineWidth,marginHorizontal: spacing.sm,marginVertical: spacing.sm,},- renameDeviceBackdrop: {- alignItems: 'center',- backgroundColor: colors.overlay,- flex: 1,- justifyContent: 'center',- paddingHorizontal: spacing.xl,- },- renameDeviceCard: {- backgroundColor: colors.surfaceElevated,- borderColor: colors.border,- borderRadius: radius.container,- borderWidth: StyleSheet.hairlineWidth,- gap: spacing.md,- maxWidth: 360,- padding: spacing.lg,- width: '100%',- },- renameDeviceTitle: {- color: colors.textPrimary,- fontSize: typeScale.title,- fontWeight: fontWeight.medium,- lineHeight: lineHeight.subtitle,- },- renameDeviceInput: {- backgroundColor: colors.surface,- borderColor: colors.border,- borderRadius: radius.container,- borderWidth: StyleSheet.hairlineWidth,- color: colors.textPrimary,- fontSize: typeScale.body,- minHeight: 48,- paddingHorizontal: spacing.md,- paddingVertical: spacing.sm,- },revokedTipBackdrop: {alignItems: 'center',backgroundColor: colors.overlay,diff --git a/apps/mobile/app/devices/manage.tsx b/apps/mobile/app/devices/manage.tsxnew file mode 100644index 0000000000..98581482e8--- /dev/null+++ b/apps/mobile/app/devices/manage.tsx@@ -0,0 +1,82 @@+import { useIsFocused, useRouter } from 'expo-router';+import { ActivityIndicator, Button, View } from 'react-native';+import { SafeAreaView } from 'react-native-safe-area-context';+import { useTranslation } from 'react-i18next';+import { useAuth } from '@/auth/AuthContext';+import { Text } from '@/components/AppText';+import { MainWindowEmptyState } from '@/components/MobilePrimitives';+import { toDeviceListItems } from '@/device-link/devices';+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';+import { useDeviceManagement } from '@/device-link/useDeviceManagement';+import { DeviceManagementList } from '@/device-link/DeviceManagementList';+import { DeviceManagementDialogs } from '@/device-link/DeviceManagementDialogs';+import {+ SimpleStackHeader,+ simpleScreenSafeAreaEdges,+} from '@/platform/chrome';+import { goBackGuarded } from '@/utils/backGuard';+import { useGuardedPush } from '@/utils/useGuardedPush';+import { useTheme } from '@/theme';+import { spacing } from '@/theme/tokens';++export default function DeviceManagementScreen() {+ const { accountGeneration } = useAuth();+ return <DeviceManagementContent key={accountGeneration} />;+}++function DeviceManagementContent() {+ const { apiFetch } = useAuth();+ const manager = useDeviceManagement(apiFetch, useIsFocused());+ const revoked = useRevokedDevices();+ const { t } = useTranslation();+ const { colors } = useTheme();+ const router = useRouter();+ const guardedPush = useGuardedPush();+ const rows = toDeviceListItems(manager.devices, Date.now(), revoked);+ return (+ <SafeAreaView+ edges={simpleScreenSafeAreaEdges()}+ style={{ flex: 1, backgroundColor: colors.surface }}+ testID="deviceManagement.screen"+ >+ <SimpleStackHeader+ title={t('devices.management.title')}+ backTestID="deviceManagement.back"+ onBack={() => goBackGuarded(router)}+ />+ {manager.error ? (+ <View style={{ padding: spacing.lg }}>+ <Text accessibilityRole="alert" style={{ color: colors.errorText }}>+ {manager.error}+ </Text>+ <Button+ title={t('devices.management.retry')}+ onPress={manager.refresh}+ />+ </View>+ ) : null}+ {manager.loading ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {!manager.loading && !manager.error && rows.length === 0 ? (+ <MainWindowEmptyState+ title={t('devices.presentation.deviceList.emptyTitle')}+ copy={t('devices.presentation.deviceList.emptyCopy')}+ />+ ) : null}+ <DeviceManagementList+ rows={rows}+ busy={manager.loading || manager.renameSaving || manager.deleteSaving}+ onOpen={(device) =>+ guardedPush({+ pathname: '/devices/manage/[deviceId]',+ params: { deviceId: device.deviceId },+ })+ }+ onRename={manager.openRename}+ onDelete={manager.openDelete}+ />+ <DeviceManagementDialogs manager={manager} />+ </SafeAreaView>+ );+}diff --git a/apps/mobile/app/devices/manage/[deviceId].tsx b/apps/mobile/app/devices/manage/[deviceId].tsxnew file mode 100644index 0000000000..fe06b698d9--- /dev/null+++ b/apps/mobile/app/devices/manage/[deviceId].tsx@@ -0,0 +1,150 @@+import { Host, List, ListItem, Text as NativeText } from '@expo/ui';+import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';+import { useCallback } from 'react';+import { ActivityIndicator, Button, View } from 'react-native';+import { SafeAreaView } from 'react-native-safe-area-context';+import { useTranslation } from 'react-i18next';+import { useAuth } from '@/auth/AuthContext';+import { Text } from '@/components/AppText';+import { DeviceManagementDialogs } from '@/device-link/DeviceManagementDialogs';+import { DeviceInformationFields } from '@/device-link/DeviceInformationFields';+import { platformLabel, toDeviceListItem } from '@/device-link/devices';+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';+import { useDeviceManagement } from '@/device-link/useDeviceManagement';+import {+ SimpleStackHeader,+ simpleScreenSafeAreaEdges,+} from '@/platform/chrome';+import { goBackGuarded } from '@/utils/backGuard';+import { useGuardedPush } from '@/utils/useGuardedPush';+import { useTheme } from '@/theme';+import { spacing } from '@/theme/tokens';++export default function DeviceInformationScreen() {+ const { accountGeneration } = useAuth();+ const { deviceId } = useLocalSearchParams<{ deviceId: string }>();+ return (+ <DeviceInformationContent+ key={`${accountGeneration}:${deviceId}`}+ deviceId={deviceId}+ />+ );+}++function DeviceInformationContent({ deviceId }: { deviceId: string }) {+ const { apiFetch } = useAuth();+ const manager = useDeviceManagement(apiFetch, useIsFocused());+ const revoked = useRevokedDevices();+ const { t, i18n } = useTranslation();+ const { mode, colors } = useTheme();+ const router = useRouter();+ const push = useGuardedPush();+ const back = useCallback(() => goBackGuarded(router), [router]);+ const device = manager.devices.find((item) => item.deviceId === deviceId);+ const presentation = device+ ? toDeviceListItem(device, Date.now(), revoked)+ : null;+ const unknown = t('devices.management.unknown');+ const seen = device?.lastSeenAt ? new Date(device.lastSeenAt) : null;+ const fields = device+ ? [+ ['name', device.name],+ ['status', presentation?.statusLabel ?? unknown],+ [+ 'platform',+ device.platform ? platformLabel(device.platform) : unknown,+ ],+ ['model', device.deviceInfo?.modelLabel ?? unknown],+ ['systemVersion', device.deviceInfo?.osVersion ?? unknown],+ ['appVersion', device.appVersion ?? unknown],+ ['cpu', device.deviceInfo?.cpuLabel ?? unknown],+ [+ 'memory',+ device.deviceInfo?.memoryGb+ ? `${device.deviceInfo.memoryGb} GB`+ : unknown,+ ],+ [+ 'lastSeen',+ device.online+ ? t('devices.management.currentlyOnline')+ : seen && Number.isFinite(seen.getTime())+ ? seen.toLocaleString(i18n.language)+ : unknown,+ ],+ ['deviceId', device.deviceId],+ ]+ : [];+ const busy = manager.loading || manager.renameSaving || manager.deleteSaving;+ return (+ <SafeAreaView+ edges={simpleScreenSafeAreaEdges()}+ style={{ flex: 1, backgroundColor: colors.surface }}+ testID="deviceInformation.screen"+ >+ <SimpleStackHeader+ title={device?.name ?? t('devices.management.details')}+ backTestID="deviceInformation.back"+ onBack={back}+ />+ {manager.loading ? (+ <ActivityIndicator color={colors.textSecondary} />+ ) : null}+ {manager.error ? (+ <View style={{ padding: spacing.lg }}>+ <Text accessibilityRole="alert" style={{ color: colors.errorText }}>+ {manager.error}+ </Text>+ <Button+ title={t('devices.management.retry')}+ onPress={manager.refresh}+ />+ </View>+ ) : null}+ {!device && !manager.loading && !manager.error ? (+ <Text style={{ color: colors.textSecondary, padding: spacing.lg }}>+ {t('devices.management.notFound')}+ </Text>+ ) : null}+ {device ? (+ <Host style={{ flex: 1 }} colorScheme={mode}>+ <List>+ <DeviceInformationFields fields={fields} />+ <ListItem+ onPress={() => {+ if (!busy) manager.openRename(device);+ }}+ testID="deviceInformation.rename"+ >+ {t('devices.list.menu.renameDevice')}+ </ListItem>+ <ListItem+ onPress={() => {+ if (!busy) manager.openDelete(device);+ }}+ testID="deviceInformation.delete"+ >+ <NativeText textStyle={{ color: colors.destructive }}>+ {t('devices.management.deleteDevice')}+ </NativeText>+ </ListItem>+ {presentation?.canOpen ? (+ <ListItem+ onPress={() =>+ push({+ pathname: '/devices/[deviceId]',+ params: { deviceId, name: device.name },+ })+ }+ testID="deviceInformation.tasks"+ >+ {t('devices.list.menu.showDeviceTasks')}+ </ListItem>+ ) : null}+ </List>+ </Host>+ ) : null}+ <DeviceManagementDialogs manager={manager} onDeleted={back} />+ </SafeAreaView>+ );+}diff --git a/apps/mobile/docs/mobile-design-guide.md b/apps/mobile/docs/mobile-design-guide.mdindex 3b6c646643..87072106a5 100644--- a/apps/mobile/docs/mobile-design-guide.md+++ b/apps/mobile/docs/mobile-design-guide.md@@ -154,6 +154,8 @@ function Foo() {简单页(设置、账号删除、设备详情、自动化)在 iOS 打开系统导航栏,返回锚点 `settings.backButton` 等 testID 仍要保留。首页顶栏在 iOS 也走系统导航栏,底色跟列表同一块 surface;会话页和文件浏览顶栏仍是自绘。左侧抽屉仍是自绘面板,iOS 用 `FullWindowOverlay` 盖住系统顶栏;Android 继续树内 overlay。搜索筛选钮收起时仍是原来的图标,iOS 点开挂系统 UIMenu;尚未冷更或 Android 继续自绘面板。+首页「所有任务」下拉只负责范围筛选:点设备名直接切换到该设备的任务,不得为补充管理动作改成设备子菜单或增加一次确认。设备详情、重命名与删除集中在左侧抽屉的「设备管理」页;列表不画进入箭头或重命名图标。所有设备无论在线、离线或未开启远程控制,都能点进资料详情,再重命名或删除;右滑显示重命名、左滑显示删除,删除需系统确认。iOS 使用系统原生列表与滑动操作。删除使用服务端接口,在线设备当前需先离线才能删除,不以本地隐藏代替删除。iOS 原生菜单与自绘回退、Android 遵守同一交互边界。+---## 5. 间距 / 圆角 / 触控 / 安全区diff --git a/apps/mobile/e2e/maestro/session_list_controls.yaml b/apps/mobile/e2e/maestro/session_list_controls.yamlindex a4659c8e43..43405de0c1 100644--- a/apps/mobile/e2e/maestro/session_list_controls.yaml+++ b/apps/mobile/e2e/maestro/session_list_controls.yaml@@ -2,13 +2,25 @@ appId: ${APP_ID}---- runFlow: login_mock.yaml- tapOn:- id: "devices.title"+ id: "home.chromeMenu"+- tapOn:+ id: "home.chromeDrawer.devices"- extendedWaitUntil:visible:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"- timeout: 10000-- longPressOn:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"+ timeout: 15000+- tapOn:+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"+- extendedWaitUntil:+ visible:+ id: "deviceInformation.screen"+ timeout: 15000+- scrollUntilVisible:+ element:+ id: "deviceInformation.tasks"+ direction: DOWN+- tapOn:+ id: "deviceInformation.tasks"- extendedWaitUntil:visible:id: "deviceDetail.screen"diff --git a/apps/mobile/e2e/maestro/visual_session_list_controls.yaml b/apps/mobile/e2e/maestro/visual_session_list_controls.yamlindex f9144ad9ea..3b912a391e 100644--- a/apps/mobile/e2e/maestro/visual_session_list_controls.yaml+++ b/apps/mobile/e2e/maestro/visual_session_list_controls.yaml@@ -1,15 +1,27 @@appId: ${APP_ID}---- runFlow: login_mock_no_clear.yaml-# 设备 chip 现在位于 DeviceMenuModal 内,菜单关闭时未挂载;先点 devices.title 打开范围菜单。+# 设备详情从左侧菜单的设备管理进入;标题下拉只负责筛选。- tapOn:- id: "devices.title"+ id: "home.chromeMenu"+- tapOn:+ id: "home.chromeDrawer.devices"- extendedWaitUntil:visible:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"timeout: 15000-- longPressOn:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"+- tapOn:+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"+- extendedWaitUntil:+ visible:+ id: "deviceInformation.screen"+ timeout: 15000+- scrollUntilVisible:+ element:+ id: "deviceInformation.tasks"+ direction: DOWN+- tapOn:+ id: "deviceInformation.tasks"- extendedWaitUntil:visible:id: "deviceDetail.screen"diff --git a/apps/mobile/e2e/maestro/visual_session_states.yaml b/apps/mobile/e2e/maestro/visual_session_states.yamlindex a675310d5a..fe05f9a6fa 100644--- a/apps/mobile/e2e/maestro/visual_session_states.yaml+++ b/apps/mobile/e2e/maestro/visual_session_states.yaml@@ -3,15 +3,27 @@ appId: ${APP_ID}- runFlow: login_mock_no_clear.yaml- assertVisible:id: "devices.list"-# 设备 chip 现在位于 DeviceMenuModal 内,菜单关闭时未挂载;先点 devices.title 打开范围菜单。+# 设备详情从左侧菜单的设备管理进入;标题下拉只负责筛选。- tapOn:- id: "devices.title"+ id: "home.chromeMenu"+- tapOn:+ id: "home.chromeDrawer.devices"+- extendedWaitUntil:+ visible:+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"+ timeout: 15000+- tapOn:+ id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"- extendedWaitUntil:visible:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"+ id: "deviceInformation.screen"timeout: 15000-- longPressOn:- id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"+- scrollUntilVisible:+ element:+ id: "deviceInformation.tasks"+ direction: DOWN+- tapOn:+ id: "deviceInformation.tasks"- extendedWaitUntil:visible:id: "deviceDetail.screen"diff --git a/apps/mobile/scripts/maestro-e2e.mjs b/apps/mobile/scripts/maestro-e2e.mjsindex 50f4b92365..5763705ad8 100644--- a/apps/mobile/scripts/maestro-e2e.mjs+++ b/apps/mobile/scripts/maestro-e2e.mjs@@ -106,6 +106,8 @@ for (const flow of resolvedFlows) {'-e',`XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID=${hostDeviceChipId}`,'-e',+ `XDT_MOBILE_E2E_HOST_DEVICE_ID=${hostDeviceId}`,+ '-e',`XDT_MOBILE_E2E_EXPO_URL=${expoUrl ?? ''}`,'-e',`XDT_MOBILE_E2E_HOST_AUTOMATIONS_URL=${hostAutomationsUrl}`,diff --git a/apps/mobile/src/__tests__/homeChromeMenus.test.ts b/apps/mobile/src/__tests__/homeChromeMenus.test.tsindex 233a496a36..53f7599994 100644--- a/apps/mobile/src/__tests__/homeChromeMenus.test.ts+++ b/apps/mobile/src/__tests__/homeChromeMenus.test.ts@@ -5,7 +5,6 @@ import {buildHomeScopeMenuItems,buildHomeScopePullDownActions,homeDisplayMenuPatch,- parseHomeScopePullDownAction,} from "@/session/homeChromeMenus";import type { MobileHomeDeviceFilterItem } from "@/session/mobileHome";@@ -26,49 +25,18 @@ function filter(}describe("home chrome menus", () => {- it("nests open and rename under each native device scope item", () => {- const actions = buildHomeScopePullDownActions(- [- filter({ id: "all", label: "全部任务", selected: true }),- filter({- id: "mac",- label: "MacBook",- deviceId: "d1",- selected: false,- }),- filter({- id: "offline",- label: "旧电脑",- deviceId: "d2",- available: false,- }),- ],- "全部任务",- {- openLabel: "打开",- renameLabel: "重命名",- showTasksLabel: "查看任务",- },- );+ it("selects native device scopes directly without a management submenu", () => {+ const actions = buildHomeScopePullDownActions([+ filter({ id: "all", label: "全部任务" }),+ filter({ id: "mac", label: "MacBook", deviceId: "d1", selected: true }),+ filter({ id: "offline", label: "旧电脑", deviceId: "d2", available: false }),+ ], "全部任务");- expect(actions.map((item) => item.id)).toEqual(["all", "scope.submenu:mac"]);- expect(actions[1]?.subactions?.map((item) => item.id)).toEqual([- "mac",- "scope.open:d1",- "scope.rename:d1",+ expect(actions).toEqual([+ { id: "all", title: "全部任务", state: "off" },+ { id: "mac", title: "MacBook", state: "on" },]);- expect(parseHomeScopePullDownAction("scope.open:d1")).toEqual({- kind: "open",- deviceId: "d1",- });- expect(parseHomeScopePullDownAction("scope.rename:d1")).toEqual({- kind: "rename",- deviceId: "d1",- });- expect(parseHomeScopePullDownAction("mac")).toEqual({- kind: "select",- filterId: "mac",- });+ expect(actions.every((item) => !item.subactions)).toBe(true);});it("lists all-conversations and available devices, marking the selected one", () => {diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex d35aa2d833..10ca485225 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -360,23 +360,21 @@ describe('mobile home desktop-first surface', () => {expect(source).not.toContain("const testID = item.deviceId ? 'home.deviceChip' : 'home.deviceChip.all';");expect(localSmokeSource).toContain('process.env.XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID = mockHostDeviceChipId;');expect(maestroSource).toContain('XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID=${hostDeviceChipId}');- expect(deviceDetailFlow).toContain('id: "${XDT_MOBILE_E2E_HOST_DEVICE_CHIP_ID}"');+ expect(deviceDetailFlow).toContain('id: "deviceManagement.open.${XDT_MOBILE_E2E_HOST_DEVICE_ID}"');});- it('lets mobile rename account devices through the authoritative device-link API', () => {- const source = readSource('app/devices/index.tsx');-- expect(source).toContain('const [renameTarget, setRenameTarget]');- expect(source).toContain('function RenameDeviceModal');- expect(source).toContain('onRenameDevice={openRenameDevice}');- expect(source).toContain('testID={testID ? `${testID}.rename` : undefined}');- expect(source).toContain('testID="home.renameDevice.input"');- expect(source).toContain("testID: 'home.renameDevice.save'");- expect(source).toContain('`/api/device-link/devices/${encodeURIComponent(target.deviceId)}`');- expect(source).toContain("method: 'PATCH'");- expect(source).toContain('body: { name }');- expect(source).toContain('remoteSessionStore.renameDevice(target.deviceId, nextName)');- expect(source).not.toContain('clearManualName');+ it('keeps device management in the drawer and scope selection direct', () => {+ const home = readSource('app/devices/index.tsx');+ const drawer = readSource('src/session/HomeChromeDrawer.tsx');+ const management = readSource('app/devices/manage.tsx');++ expect(drawer).toContain('testID="home.chromeDrawer.devices"');+ expect(home).toContain("guardedPush('/devices/manage')");+ expect(home).not.toContain('onRenameDevice=');+ expect(home).not.toContain('onOpenDevice=');+ expect(management).toContain('key={accountGeneration}');+ expect(management).toContain("pathname: '/devices/manage/[deviceId]'");+ expect(management).toContain('onRename={manager.openRename}');});it('scopes multi-device connection feedback to the affected device chip', () => {diff --git a/apps/mobile/src/__tests__/useDeviceManagement.test.tsx b/apps/mobile/src/__tests__/useDeviceManagement.test.tsxnew file mode 100644index 0000000000..f6f9aeaf25--- /dev/null+++ b/apps/mobile/src/__tests__/useDeviceManagement.test.tsx@@ -0,0 +1,383 @@+// @vitest-environment jsdom+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 { useDeviceManagement } from '@/device-link/useDeviceManagement';+import {+ setMobileAuthOwner,+ __testing as authOwnerTesting,+} from '@/auth/authOwnerGeneration';++const mocks = vi.hoisted(() => ({+ renameDevice: vi.fn(),+ removeDevice: vi.fn(),+ clearRevoked: vi.fn(),+ getDeviceIdentity: vi.fn(),+ setDeviceIdentity: vi.fn(),+}));+vi.mock('@/auth/secureStorage', () => ({+ getSecureItem: vi.fn(),+ setSecureItem: vi.fn(),+}));+vi.mock('@/device-link/revokedDevicesStore', () => ({+ revokedDevicesStore: mocks,+}));+vi.mock('@/config/env', () => ({+ DEVICE_LINK_API_BASE_URL: 'https://relay.example.invalid',+}));+vi.mock('@/device-link/remoteStatus', () => ({+ formatRemoteError: (error: Error) => error.message,+}));+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: mocks }));++const device: DeviceView = {+ deviceId: 'mac/1',+ name: 'MacBook',+ platform: 'darwin',+ appVersion: null,+ lastSeenAt: null,+ online: true,+ busy: false,+ remoteControlEnabled: true,+ isSelf: false,+};+const apiFetch = vi.fn();+let root: Root;+let state: ReturnType<typeof useDeviceManagement>;+function Harness({ focused }: { focused: boolean }) {+ state = useDeviceManagement(apiFetch, focused);+ return null;+}+async function render(key = 'account-a', focused = true) {+ await act(async () => root.render(createElement(Harness, { key, focused })));+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+beforeEach(() => {+ (+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+ ).IS_REACT_ACT_ENVIRONMENT = true;+ vi.clearAllMocks();+ authOwnerTesting.reset();+ mocks.getDeviceIdentity.mockReturnValue([]);+ mocks.setDeviceIdentity.mockImplementation((items) =>+ mocks.getDeviceIdentity.mockReturnValue(items),+ );+ apiFetch.mockReset().mockResolvedValue({ devices: [device] });+ root = createRoot(document.createElement('div'));+});+afterEach(() => {+ act(() => root.unmount());+});++it('keeps the last device list on refresh failure and can retry', async () => {+ await render();+ apiFetch.mockRejectedValueOnce(new Error('offline'));+ await act(async () => state.refresh());+ expect(state.devices).toEqual([device]);+ expect(state.error).toBe('offline');+ expect(state.loading).toBe(false);+ await act(async () => state.refresh());+ expect(state.error).toBeNull();+});++it('saves a trimmed device name once, then uses the authoritative returned name', async () => {+ await render();+ const save = deferred<{ name: string; deviceId: string }>();+ await act(async () => state.openRename(device));+ act(() => state.setRenameDraft(' Office Mac '));+ apiFetch.mockImplementation((_path, options) =>+ options.method === 'PATCH'+ ? save.promise+ : Promise.resolve({ devices: [{ ...device, name: 'Office Mac' }] }),+ );+ let request!: Promise<void>;+ act(() => {+ request = state.confirmRename();+ void state.confirmRename();+ state.refresh();+ state.closeRename();+ });+ expect(state.renameTarget).toEqual(device);+ expect(+ apiFetch.mock.calls.filter(([, options]) => options.method === 'PATCH'),+ ).toHaveLength(1);+ expect(apiFetch).toHaveBeenCalledWith(+ '/api/device-link/devices/mac%2F1',+ expect.objectContaining({+ method: 'PATCH',+ body: { name: 'Office Mac' },+ baseUrl: 'https://relay.example.invalid',+ }),+ );+ await act(async () => {+ save.resolve({ deviceId: device.deviceId, name: 'Office Mac' });+ await request;+ });+ expect(state.devices[0]?.name).toBe('Office Mac');+ expect(mocks.renameDevice).toHaveBeenCalledWith(+ device.deviceId,+ 'Office Mac',+ );+ expect(state.renameTarget).toBeNull();+ expect(state.renameSaving).toBe(false);+});++it('keeps the rename editor and original name after a failed save', async () => {+ await render();+ act(() => state.openRename(device));+ act(() => state.setRenameDraft('New name'));+ apiFetch.mockRejectedValueOnce(new Error('rename failed'));+ await act(async () => state.confirmRename());+ expect(state.renameError?.message).toBe('rename failed');+ expect(state.renameTarget).toEqual(device);+ expect(state.renameDraft).toBe('New name');+ expect(state.devices[0]?.name).toBe('MacBook');+ expect(mocks.renameDevice).not.toHaveBeenCalled();+});++it('ignores an old list response after switching accounts', async () => {+ const oldList = deferred<{ devices: DeviceView[] }>();+ apiFetch.mockReturnValueOnce(oldList.promise);+ await render();+ const otherDevice = { ...device, deviceId: 'other', name: 'Other account' };+ apiFetch.mockResolvedValue({ devices: [otherDevice] });+ await render('account-b');+ await act(async () => oldList.resolve({ devices: [device] }));+ expect(state.devices).toEqual([otherDevice]);+});++it('does not let a previous account rename update the new account or shared store', async () => {+ await render();+ act(() => state.openRename(device));+ act(() => state.setRenameDraft('Old account name'));+ const save = deferred<{ deviceId: string; name: string }>();+ apiFetch.mockReturnValueOnce(save.promise);+ let request!: Promise<void>;+ act(() => {+ request = state.confirmRename();+ });+ apiFetch.mockResolvedValue({ devices: [] });+ await render('account-b');+ await act(async () => {+ save.resolve({ deviceId: device.deviceId, name: 'Old account name' });+ await request;+ });+ expect(state.devices).toEqual([]);+ expect(state.renameTarget).toBeNull();+ expect(mocks.renameDevice).not.toHaveBeenCalled();+});++it('ignores a list response after leaving the page and refreshes on return', async () => {+ const oldList = deferred<{ devices: DeviceView[] }>();+ apiFetch.mockReturnValueOnce(oldList.promise);+ await render();+ await render('account-a', false);+ await act(async () => oldList.resolve({ devices: [device] }));+ expect(state.devices).toEqual([]);+ await render();+ expect(state.devices).toEqual([device]);+});++it('deletes once and clears device projections only after server success', async () => {+ await render();+ act(() => state.openDelete(device));+ const removal = deferred<{ deviceId: string; deleted: boolean }>();+ apiFetch.mockImplementation((_path, options) =>+ options.method === 'DELETE'+ ? removal.promise+ : Promise.resolve({ devices: [] }),+ );+ let request!: Promise<boolean>;+ act(() => {+ request = state.confirmDelete();+ void state.confirmDelete();+ state.closeDelete();+ state.openRename(device);+ });+ expect(state.deleteTarget).toEqual(device);+ expect(state.renameTarget).toBeNull();+ expect(mocks.removeDevice).not.toHaveBeenCalled();+ expect(+ apiFetch.mock.calls.filter(([, options]) => options.method === 'DELETE'),+ ).toHaveLength(1);+ expect(apiFetch).toHaveBeenCalledWith(+ '/api/device-link/devices/mac%2F1',+ expect.objectContaining({ method: 'DELETE' }),+ );+ await act(async () => {+ removal.resolve({ deviceId: device.deviceId, deleted: true });+ expect(await request).toBe(true);+ });+ expect(state.devices).toEqual([]);+ expect(mocks.removeDevice).toHaveBeenCalledWith(device.deviceId);+ expect(mocks.clearRevoked).toHaveBeenCalledWith(device.deviceId);+});++it('keeps device records and access state when deletion fails, including an online race', async () => {+ await render();+ act(() => state.openDelete(device));+ apiFetch.mockRejectedValueOnce(+ Object.assign(new Error('online'), { code: 'ALREADY_EXISTS' }),+ );+ await act(async () => {+ expect(await state.confirmDelete()).toBe(false);+ });+ expect(state.deleteError).toBeTruthy();+ expect(state.devices).toEqual([device]);+ expect(state.deleteTarget).toEqual(device);+ expect(mocks.removeDevice).not.toHaveBeenCalled();+ expect(mocks.clearRevoked).not.toHaveBeenCalled();+});++it('does not clear shared device state after an old-account deletion completes', async () => {+ await render();+ act(() => state.openDelete(device));+ const removal = deferred<{ deviceId: string; deleted: boolean }>();+ apiFetch.mockReturnValueOnce(removal.promise);+ let request!: Promise<boolean>;+ act(() => {+ request = state.confirmDelete();+ });+ apiFetch.mockResolvedValue({ devices: [] });+ await render('account-b');+ await act(async () => {+ removal.resolve({ deviceId: device.deviceId, deleted: true });+ expect(await request).toBe(false);+ });+ expect(mocks.removeDevice).not.toHaveBeenCalled();+ expect(mocks.clearRevoked).not.toHaveBeenCalled();+});++it('does not treat deleted=false as successful deletion', async () => {+ await render();+ act(() => state.openDelete(device));+ apiFetch.mockResolvedValueOnce({ deviceId: device.deviceId, deleted: false });+ await act(async () => {+ expect(await state.confirmDelete()).toBe(false);+ });+ expect(state.devices).toEqual([device]);+ expect(mocks.removeDevice).not.toHaveBeenCalled();+});++it('does not reload after cancelling rename and immediately allows deleting the same device', async () => {+ await render();+ const requestCount = apiFetch.mock.calls.length;+ act(() => state.openRename(device));+ act(() => state.closeRename());+ expect(state.loading).toBe(false);+ expect(apiFetch).toHaveBeenCalledTimes(requestCount);+ act(() => state.openDelete(device));+ expect(state.deleteTarget).toEqual(device);+});++it('rejects repeated oversized names without a request, then saves a 64-character name', async () => {+ await render();+ act(() => state.openRename(device));+ const oversized = 'x'.repeat(65);+ await act(async () => state.confirmRename(oversized));+ const firstError = state.renameError;+ expect(firstError?.message).toContain('64');+ expect(state.renameDraft).toBe(oversized);+ expect(apiFetch).toHaveBeenCalledTimes(1);+ await act(async () => state.confirmRename(oversized));+ expect(state.renameError).not.toBe(firstError);+ expect(apiFetch).toHaveBeenCalledTimes(1);+ const valid = 'x'.repeat(64);+ apiFetch.mockResolvedValueOnce({ deviceId: device.deviceId, name: valid });+ await act(async () => state.confirmRename(valid));+ expect(state.renameTarget).toBeNull();+ expect(state.devices[0]?.name).toBe(valid);+});++it('reuses known names for placeholder snapshots and keeps a successful rename across refreshes', async () => {+ mocks.getDeviceIdentity.mockReturnValue([+ { deviceId: device.deviceId, name: 'Known Mac' },+ ]);+ apiFetch.mockResolvedValue({+ devices: [{ ...device, online: false, name: 'unknown' }],+ });+ await render();+ expect(state.devices[0]?.name).toBe('Known Mac');+ act(() => state.openRename(state.devices[0]!));+ apiFetch.mockResolvedValueOnce({+ deviceId: device.deviceId,+ name: 'Renamed Mac',+ });+ await act(async () => state.confirmRename('Renamed Mac'));+ expect(mocks.getDeviceIdentity()).toEqual([+ { deviceId: device.deviceId, name: 'Renamed Mac' },+ ]);+ apiFetch.mockResolvedValue({+ devices: [{ ...device, online: false, name: 'no' }],+ });+ await act(async () => state.refresh());+ expect(state.devices[0]?.name).toBe('Renamed Mac');+ act(() => state.openDelete(state.devices[0]!));+ apiFetch.mockResolvedValueOnce({ deviceId: device.deviceId, deleted: true });+ await act(async () => state.confirmDelete());+ expect(mocks.getDeviceIdentity()).toEqual([]);+});++it('ignores a rename response when the auth owner changes before React remounts', async () => {+ setMobileAuthOwner('account-a');+ await render();+ act(() => state.openRename(device));+ const save = deferred<{ deviceId: string; name: string }>();+ apiFetch.mockReturnValueOnce(save.promise);+ let request!: Promise<void>;+ act(() => {+ request = state.confirmRename('Old name');+ });+ setMobileAuthOwner('account-b');+ await act(async () => {+ save.resolve({ deviceId: device.deviceId, name: 'Old name' });+ await request;+ });+ expect(mocks.renameDevice).not.toHaveBeenCalled();+ expect(mocks.setDeviceIdentity).not.toHaveBeenCalled();+ expect(state.devices[0]?.name).toBe('MacBook');+});++it('uses a newly learned shared name even when the current view still contains a placeholder', async () => {+ apiFetch.mockResolvedValue({+ devices: [{ ...device, online: false, name: 'unknown' }],+ });+ await render();+ mocks.getDeviceIdentity.mockReturnValue([+ { deviceId: device.deviceId, name: 'Known Mac' },+ ]);+ await act(async () => state.refresh());+ expect(state.devices[0]?.name).toBe('Known Mac');+ mocks.getDeviceIdentity.mockReturnValue([+ { deviceId: device.deviceId, name: 'Latest Mac' },+ ]);+ await act(async () => state.refresh());+ expect(state.devices[0]?.name).toBe('Latest Mac');+});++it.each(['rename', 'delete'] as const)(+ 'does not submit an old %s dialog after the auth owner changes',+ async (action) => {+ setMobileAuthOwner('account-a');+ await render();+ act(() =>+ action === 'rename' ? state.openRename(device) : state.openDelete(device),+ );+ setMobileAuthOwner('account-b');+ await act(async () => {+ if (action === 'rename') await state.confirmRename('Old account name');+ else expect(await state.confirmDelete()).toBe(false);+ });+ expect(apiFetch).toHaveBeenCalledTimes(1);+ expect(mocks.setDeviceIdentity).not.toHaveBeenCalled();+ },+);diff --git a/apps/mobile/src/__tests__/visualMock.test.ts b/apps/mobile/src/__tests__/visualMock.test.tsnew file mode 100644index 0000000000..b7043163cb--- /dev/null+++ b/apps/mobile/src/__tests__/visualMock.test.ts@@ -0,0 +1,65 @@+import { beforeEach, expect, it, vi } from 'vitest';+import type { DeviceView } from '@cindy/device-link';++vi.mock('@/config/env', () => ({ MOBILE_VISUAL_MOCK_REALDATA_URL: '' }));+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: {} }));+beforeEach(() => vi.resetModules());++it('deletes an offline fixture without resurrecting it in later directory reads', async () => {+ const mock = await import('@/debug/visualMock');+ const path = `/api/device-link/devices/${mock.VISUAL_MOCK_OFFLINE_DEVICE_ID}`;+ expect(+ await mock.visualMockApiFetch(path, { baseUrl: '', method: 'DELETE' }),+ ).toEqual({+ deviceId: mock.VISUAL_MOCK_OFFLINE_DEVICE_ID,+ deleted: true,+ });+ const result = await mock.visualMockApiFetch<{ devices: DeviceView[] }>(+ '/api/device-link/devices',+ );+ expect(+ result.devices.some(+ (device) => device.deviceId === mock.VISUAL_MOCK_OFFLINE_DEVICE_ID,+ ),+ ).toBe(false);+ expect(mock.visualMockDevices()).toEqual(result.devices);+ await expect(+ mock.visualMockApiFetch(path, { baseUrl: '', method: 'DELETE' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+});++it('rejects online deletion and partial ID matches without losing devices', async () => {+ const mock = await import('@/debug/visualMock');+ const before = mock.visualMockDevices();+ const path = `/api/device-link/devices/${mock.VISUAL_MOCK_DEVICE_ID}`;+ await expect(+ mock.visualMockApiFetch(path, { baseUrl: '', method: 'DELETE' }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ await expect(+ mock.visualMockApiFetch(`${path}-extra`, { baseUrl: '', method: 'DELETE' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mock.visualMockDevices()).toEqual(before);+});++it('persists a renamed fixture in later directory reads', async () => {+ const mock = await import('@/debug/visualMock');+ const path = `/api/device-link/devices/${mock.VISUAL_MOCK_DEVICE_ID}`;+ expect(+ await mock.visualMockApiFetch(path, {+ baseUrl: '',+ method: 'PATCH',+ body: { name: ' Office Mac ' },+ }),+ ).toEqual({+ deviceId: mock.VISUAL_MOCK_DEVICE_ID,+ name: 'Office Mac',+ });+ const result = await mock.visualMockApiFetch<{ devices: DeviceView[] }>(+ '/api/device-link/devices',+ );+ expect(+ result.devices.find(+ (device) => device.deviceId === mock.VISUAL_MOCK_DEVICE_ID,+ )?.name,+ ).toBe('Office Mac');+});diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex 18ad8a027a..3a669efe28 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -1,4 +1,5 @@import { SHARED_REMOTE_CONTROL_FIXTURE } from '@cindy/maker-shared/fixtures';+import { ApiError, type ApiFetchOptions } from '@/api/client';import type { DeviceView, LinkAcceptPayload } from '@cindy/device-link';import type { MobileUser } from '@/auth/AuthContext';import { MOBILE_VISUAL_MOCK_REALDATA_URL } from '@/config/env';@@ -19,6 +20,7 @@ import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSessionexport const VISUAL_MOCK_DEVICE_ID = 'cindy-visual-mock-mac';export const VISUAL_MOCK_DEVICE_NAME = 'CINDY Visual Mock Mac';+export const VISUAL_MOCK_OFFLINE_DEVICE_ID = 'cindy-visual-mock-offline-mac';const VISUAL_MOCK_REALDATA_DEVICE_ID = 'cindy-realdata-mac';const VISUAL_MOCK_REALDATA_DEVICE_NAME = 'CINDY Real Data Mac';export const VISUAL_MOCK_SESSION_ID = 'session-primary';@@ -61,6 +63,8 @@ export const visualMockUser: MobileUser = {let realDataSnapshot: VisualRealDataSnapshot | null = null;let realDataLoadPromise: Promise<VisualRealDataSnapshot | null> | null = null;let didWarnRealDataLoad = false;+const deletedDeviceIds = new Set<string>();+const renamedDevices = new Map<string, string>();export function visualMockDevices(): DeviceView[] {const realData = realDataSnapshot;@@ -100,7 +104,19 @@ export function visualMockDevices(): DeviceView[] {remoteControlEnabled: true,isSelf: false,},- ];+ {+ deviceId: VISUAL_MOCK_OFFLINE_DEVICE_ID,+ name: 'CINDY Offline Mock Mac',+ platform: 'darwin',+ appVersion: '0.0.0-visual-mock',+ lastSeenAt: ISO_NOW,+ online: false,+ busy: false,+ remoteControlEnabled: false,+ isSelf: false,+ },+ ].filter((device) => !deletedDeviceIds.has(device.deviceId))+ .map((device) => ({ ...device, name: renamedDevices.get(device.deviceId) ?? device.name }));}export function seedVisualMockStore(): void {@@ -253,12 +269,24 @@ async function visualMockInvoke<T = unknown>(}}-export async function visualMockApiFetch<T>(path: string): Promise<T> {+export async function visualMockApiFetch<T>(path: string, options?: Omit<ApiFetchOptions, 'token'>): Promise<T> {await loadVisualRealDataSnapshot();if (path === '/api/device-link/devices') return { devices: visualMockDevices() } as T;if (path.startsWith('/api/device-link/devices/')) {- const device = visualMockDevices().find((item) => path.includes(encodeURIComponent(item.deviceId)));- return { deviceId: device?.deviceId ?? VISUAL_MOCK_DEVICE_ID, name: device?.name ?? VISUAL_MOCK_DEVICE_NAME } as T;+ const device = visualMockDevices().find((item) => path === `/api/device-link/devices/${encodeURIComponent(item.deviceId)}`);+ if (!device) throw new ApiError('NOT_FOUND', 404, 'Device not found');+ if (options?.method === 'DELETE') {+ if (device.online) throw new ApiError('ALREADY_EXISTS', 409, 'Device is online');+ deletedDeviceIds.add(device.deviceId);+ renamedDevices.delete(device.deviceId);+ return { deviceId: device.deviceId, deleted: true } as T;+ }+ if (options?.method === 'PATCH') {+ const name = (options.body as { name?: unknown } | undefined)?.name;+ if (typeof name !== 'string' || !name.trim()) throw new ApiError('INVALID_ARGUMENT', 400, 'Device name is required');+ renamedDevices.set(device.deviceId, name.trim());+ }+ return { deviceId: device.deviceId, name: renamedDevices.get(device.deviceId) ?? device.name } as T;}if (path === '/api/device-link/media/presign-get') return { url: IMAGE_DATA_URL } as T;if (path === '/api/device-link/media/presign-put') return { url: IMAGE_DATA_URL, key: 'visual-mock-upload' } as T;diff --git a/apps/mobile/src/device-link/DeviceInformationFields.ios.tsx b/apps/mobile/src/device-link/DeviceInformationFields.ios.tsxnew file mode 100644index 0000000000..e30c254c2e--- /dev/null+++ b/apps/mobile/src/device-link/DeviceInformationFields.ios.tsx@@ -0,0 +1,15 @@+import { LabeledContent, Section, Text } from '@expo/ui/swift-ui';+import { useTranslation } from 'react-i18next';++export function DeviceInformationFields({ fields }: { fields: string[][] }) {+ const { t } = useTranslation();+ return (+ <Section>+ {fields.map(([key, value]) => (+ <LabeledContent key={key} label={t(`devices.management.fields.${key}`)}>+ <Text>{value}</Text>+ </LabeledContent>+ ))}+ </Section>+ );+}diff --git a/apps/mobile/src/device-link/DeviceInformationFields.tsx b/apps/mobile/src/device-link/DeviceInformationFields.tsxnew file mode 100644index 0000000000..6f274da7c7--- /dev/null+++ b/apps/mobile/src/device-link/DeviceInformationFields.tsx@@ -0,0 +1,22 @@+import { ListItem, Text } from '@expo/ui';+import { useTranslation } from 'react-i18next';+import { useTheme } from '@/theme';++export function DeviceInformationFields({ fields }: { fields: string[][] }) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ return (+ <>+ {fields.map(([key, value]) => (+ <ListItem+ key={key}+ supportingText={+ <Text textStyle={{ color: colors.textSecondary }}>{value}</Text>+ }+ >+ {t(`devices.management.fields.${key}`)}+ </ListItem>+ ))}+ </>+ );+}diff --git a/apps/mobile/src/device-link/DeviceManagementDialogs.tsx b/apps/mobile/src/device-link/DeviceManagementDialogs.tsxnew file mode 100644index 0000000000..644ded2e7a--- /dev/null+++ b/apps/mobile/src/device-link/DeviceManagementDialogs.tsx@@ -0,0 +1,99 @@+import { useEffect, useRef } from 'react';+import { Alert, Platform } from 'react-native';+import { useTranslation } from 'react-i18next';+import { RenameDeviceModal } from '@/session/RenameDeviceModal';+import type { useDeviceManagement } from './useDeviceManagement';++export function DeviceManagementDialogs({+ manager,+ onDeleted,+}: {+ manager: ReturnType<typeof useDeviceManagement>;+ onDeleted?(): void;+}) {+ const { t } = useTranslation();+ const {+ deleteTarget,+ deleteError,+ deleteSaving,+ closeDelete,+ confirmDelete,+ renameTarget,+ renameSaving,+ renameError,+ } = manager;+ const latest = useRef(manager);+ latest.current = manager;+ useEffect(() => {+ if (Platform.OS !== 'ios' || !renameTarget || renameSaving) return;+ Alert.prompt(+ t('devices.list.renameDevice.title'),+ renameError?.message,+ [+ {+ text: t('devices.common.cancel'),+ style: 'cancel',+ onPress: () => latest.current.closeRename(),+ },+ {+ text: t('devices.common.save'),+ onPress: (value?: string) => {+ const name = value?.trim() ?? '';+ if (!name) {+ latest.current.closeRename();+ return;+ }+ latest.current.setRenameDraft(name);+ void latest.current.confirmRename(name);+ },+ },+ ],+ 'plain-text',+ latest.current.renameDraft,+ );+ }, [renameTarget, renameSaving, renameError, t]);+ useEffect(() => {+ if (!deleteTarget || deleteSaving) return;+ Alert.alert(+ t('devices.management.deleteTitle', { name: deleteTarget.name }),+ deleteError ?? t('devices.management.deleteMessage'),+ [+ {+ text: t('devices.common.cancel'),+ style: 'cancel',+ onPress: closeDelete,+ },+ {+ text: t('devices.management.deleteDevice'),+ style: 'destructive',+ onPress: () => {+ void confirmDelete().then((deleted) => {+ if (deleted) onDeleted?.();+ });+ },+ },+ ],+ { cancelable: true, onDismiss: closeDelete },+ );+ }, [+ deleteTarget,+ deleteError,+ deleteSaving,+ closeDelete,+ confirmDelete,+ onDeleted,+ t,+ ]);+ if (Platform.OS === 'ios') return null;+ return (+ <RenameDeviceModal+ draft={manager.renameDraft}+ error={manager.renameError?.message ?? null}+ onCancel={manager.closeRename}+ onChangeDraft={manager.setRenameDraft}+ onConfirm={() => void manager.confirmRename()}+ saving={manager.renameSaving}+ visible={manager.renameTarget !== null}+ />+ );+}diff --git a/apps/mobile/src/device-link/DeviceManagementList.ios.tsx b/apps/mobile/src/device-link/DeviceManagementList.ios.tsxnew file mode 100644index 0000000000..c1511a9a79--- /dev/null+++ b/apps/mobile/src/device-link/DeviceManagementList.ios.tsx@@ -0,0 +1,112 @@+import { Host, ListItem } from '@expo/ui';+import { Button, List, SwipeActions, Text } from '@expo/ui/swift-ui';+import {+ disabled,+ font,+ foregroundStyle,+ labelStyle,+ listRowBackground,+ listStyle,+ scrollContentBackground,+ tint,+} from '@expo/ui/swift-ui/modifiers';+import { useTranslation } from 'react-i18next';+import { Monitor } from 'lucide-react-native';+import { useTheme } from '@/theme';+import { iconSize, iconStroke } from '@/theme/tokens';+import type { DeviceManagementListProps } from './DeviceManagementList.types';++export function DeviceManagementList({+ rows,+ busy,+ onOpen,+ onRename,+ onDelete,+}: DeviceManagementListProps) {+ const { mode, colors } = useTheme();+ const { t } = useTranslation();+ return (+ <Host+ style={{ flex: 1, backgroundColor: colors.surface }}+ colorScheme={mode}+ >+ <List+ modifiers={[listStyle('plain'), scrollContentBackground('hidden')]}+ testID="deviceManagement.list"+ >+ {rows.map(({ device, statusLabel, statusDetail }) => (+ <SwipeActions+ key={device.deviceId}+ modifiers={[listRowBackground(colors.surface)]}+ >+ <ListItem+ onPress={() => onOpen(device)}+ leading={+ <Monitor+ size={iconSize.md}+ strokeWidth={iconStroke.regular}+ color={+ device.online ? colors.statusReady : colors.textSecondary+ }+ />+ }+ supportingText={+ <Text+ modifiers={[+ font({ textStyle: 'caption' }),+ foregroundStyle({+ type: 'hierarchical',+ style: 'secondary',+ }),+ ]}+ >+ {device.online+ ? statusLabel+ : `${statusLabel} · ${statusDetail}`}+ </Text>+ }+ testID={`deviceManagement.open.${device.deviceId}`}+ >+ <Text+ modifiers={[+ font({+ textStyle: 'body',+ weight: device.online ? 'medium' : 'regular',+ }),+ foregroundStyle({+ type: 'hierarchical',+ style: device.online ? 'primary' : 'secondary',+ }),+ ]}+ >+ {device.name}+ </Text>+ </ListItem>+ <SwipeActions.Actions edge="leading" allowsFullSwipe={false}>+ <Button+ label={t('devices.list.menu.renameDevice')}+ systemImage="pencil"+ onPress={() => onRename(device)}+ modifiers={[disabled(busy), labelStyle('iconOnly')]}+ testID={`deviceManagement.rename.${device.deviceId}`}+ />+ </SwipeActions.Actions>+ <SwipeActions.Actions edge="trailing" allowsFullSwipe={false}>+ <Button+ label={t('devices.common.delete')}+ systemImage="trash"+ onPress={() => onDelete(device)}+ modifiers={[+ disabled(busy),+ tint(colors.destructive),+ labelStyle('iconOnly'),+ ]}+ testID={`deviceManagement.delete.${device.deviceId}`}+ />+ </SwipeActions.Actions>+ </SwipeActions>+ ))}+ </List>+ </Host>+ );+}diff --git a/apps/mobile/src/device-link/DeviceManagementList.tsx b/apps/mobile/src/device-link/DeviceManagementList.tsxnew file mode 100644index 0000000000..5a6ae34263--- /dev/null+++ b/apps/mobile/src/device-link/DeviceManagementList.tsx@@ -0,0 +1,130 @@+import { useRef } from 'react';+import { Pressable, ScrollView, StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import { Monitor } from 'lucide-react-native';+import { Text } from '@/components/AppText';+import {+ ClassicSwipeable,+ type ClassicSwipeableMethods,+} from '@/platform/gestureHandler';+import { useTheme } from '@/theme';+import {+ fontWeight,+ iconSize,+ iconStroke,+ spacing,+ typeScale,+} from '@/theme/tokens';+import type { DeviceManagementListProps } from './DeviceManagementList.types';++export function DeviceManagementList(props: DeviceManagementListProps) {+ const openRow = useRef<ClassicSwipeableMethods | null>(null);+ return (+ <ScrollView onScrollBeginDrag={() => openRow.current?.close()}>+ {props.rows.map((row) => (+ <DeviceRow+ key={row.device.deviceId}+ {...props}+ row={row}+ onWillOpen={(ref) => {+ if (openRow.current !== ref) openRow.current?.close();+ openRow.current = ref;+ }}+ />+ ))}+ </ScrollView>+ );+}++function DeviceRow({+ row,+ busy,+ onOpen,+ onRename,+ onDelete,+ onWillOpen,+}: DeviceManagementListProps & {+ row: DeviceManagementListProps['rows'][number];+ onWillOpen(ref: ClassicSwipeableMethods | null): void;+}) {+ const ref = useRef<ClassicSwipeableMethods | null>(null);+ const { colors } = useTheme();+ const { t } = useTranslation();+ const action = (remove: boolean) => (+ <Pressable+ accessibilityRole="button"+ disabled={busy}+ onPress={() => {+ ref.current?.close();+ (remove ? onDelete : onRename)(row.device);+ }}+ style={[styles.action, { backgroundColor: colors.surfaceElevated }]}+ >+ <Text style={{ color: remove ? colors.destructive : colors.textPrimary }}>+ {t(remove ? 'devices.common.delete' : 'devices.list.menu.renameDevice')}+ </Text>+ </Pressable>+ );+ return (+ <ClassicSwipeable+ ref={ref}+ renderLeftActions={() => action(false)}+ renderRightActions={() => action(true)}+ overshootLeft={false}+ overshootRight={false}+ onSwipeableWillOpen={() => onWillOpen(ref.current)}+ >+ <Pressable+ accessibilityRole="button"+ onPress={() => onOpen(row.device)}+ testID={`deviceManagement.open.${row.device.deviceId}`}+ style={[+ styles.row,+ { backgroundColor: colors.surface, borderBottomColor: colors.border },+ ]}+ >+ <Monitor+ size={iconSize.md}+ strokeWidth={iconStroke.regular}+ color={row.device.online ? colors.statusReady : colors.textSecondary}+ />+ <View style={styles.labels}>+ <Text+ style={{+ color: row.device.online+ ? colors.textPrimary+ : colors.textTertiary,+ fontSize: typeScale.body,+ fontWeight: row.device.online+ ? fontWeight.medium+ : fontWeight.regular,+ }}+ >+ {row.device.name}+ </Text>+ <Text style={{ color: colors.textSecondary }}>+ {row.statusLabel} · {row.statusDetail}+ </Text>+ </View>+ </Pressable>+ </ClassicSwipeable>+ );+}+const styles = StyleSheet.create({+ row: {+ flexDirection: 'row',+ alignItems: 'center',+ minHeight: 60,+ padding: spacing.lg,+ gap: spacing.md,+ borderBottomWidth: StyleSheet.hairlineWidth,+ },+ labels: { flex: 1, gap: spacing.xs },+ action: {+ minWidth: 88,+ minHeight: 44,+ alignItems: 'center',+ justifyContent: 'center',+ padding: spacing.lg,+ },+});diff --git a/apps/mobile/src/device-link/DeviceManagementList.types.ts b/apps/mobile/src/device-link/DeviceManagementList.types.tsnew file mode 100644index 0000000000..c4fb9ac89c--- /dev/null+++ b/apps/mobile/src/device-link/DeviceManagementList.types.ts@@ -0,0 +1,13 @@+import type { DeviceView } from '@cindy/device-link';++export interface DeviceManagementListProps {+ rows: Array<{+ device: DeviceView;+ statusLabel: string;+ statusDetail: string;+ }>;+ busy: boolean;+ onOpen(device: DeviceView): void;+ onRename(device: DeviceView): void;+ onDelete(device: DeviceView): void;+}diff --git a/apps/mobile/src/device-link/deviceName.ts b/apps/mobile/src/device-link/deviceName.tsnew file mode 100644index 0000000000..3ea256b3c8--- /dev/null+++ b/apps/mobile/src/device-link/deviceName.ts@@ -0,0 +1 @@+export const MAX_DEVICE_NAME_LENGTH = 64;diff --git a/apps/mobile/src/device-link/useDeviceManagement.ts b/apps/mobile/src/device-link/useDeviceManagement.tsnew file mode 100644index 0000000000..ca7f04735f--- /dev/null+++ b/apps/mobile/src/device-link/useDeviceManagement.ts@@ -0,0 +1,265 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import type { DeviceView } from '@cindy/device-link';+import type { ApiFetchOptions } from '@/api/client';+import { DEVICE_LINK_API_BASE_URL } from '@/config/env';+import { formatRemoteError } from '@/device-link/remoteStatus';+import { remoteSessionStore } from '@/session/remoteSessionStore';+import { revokedDevicesStore } from '@/device-link/revokedDevicesStore';+import { i18n } from '@/i18n';+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from '@/auth/authOwnerGeneration';+import {+ hydrateDeviceIdentityCache,+ normalizeDeviceDisplayName,+ reconcileDeviceIdentities,+} from './deviceIdentityStore';+import { MAX_DEVICE_NAME_LENGTH } from './deviceName';++type ApiFetch = <T>(path: string, options: ApiFetchOptions) => Promise<T>;+const DEVICE_TIMEOUT_MS = 8_000;++/** The screen is keyed by accountGeneration so a previous account never shares this state. */+export function useDeviceManagement(apiFetch: ApiFetch, focused: boolean) {+ const [devices, setDevices] = useState<DeviceView[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [refreshVersion, setRefreshVersion] = useState(0);+ const [renameTarget, setRenameTarget] = useState<DeviceView | null>(null);+ const [renameDraft, setRenameDraft] = useState('');+ const [renameSaving, setRenameSaving] = useState(false);+ const [renameError, setRenameError] = useState<Error | null>(null);+ const [deleteTarget, setDeleteTarget] = useState<DeviceView | null>(null);+ const [deleteSaving, setDeleteSaving] = useState(false);+ const [deleteError, setDeleteError] = useState<string | null>(null);+ const savingRef = useRef(false);+ const editingRef = useRef(false);+ editingRef.current = renameTarget !== null || deleteTarget !== null;+ const lifetimeRef = useRef({ active: true, owner: getMobileAuthOwner() });+ useEffect(() => {+ const lifetime = { active: true, owner: lifetimeRef.current.owner };+ lifetimeRef.current = lifetime;+ return () => {+ lifetime.active = false;+ };+ }, []);++ useEffect(() => {+ // Closing an editor must preserve scroll position and keep the next action+ // immediately available. Refresh only on focus or an explicit retry.+ if (!focused || editingRef.current) return;+ let cancelled = false;+ const owner = lifetimeRef.current.owner;+ const isCurrent = () => !cancelled && isMobileAuthOwnerCurrent(owner);+ if (!isCurrent()) return;+ setLoading(true);+ setError(null);+ void apiFetch<{ devices: DeviceView[] }>('/api/device-link/devices', {+ baseUrl: DEVICE_LINK_API_BASE_URL,+ timeoutMs: DEVICE_TIMEOUT_MS,+ })+ .then((result) => {+ 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;+ });+ })+ .catch((cause) => {+ // Keep the last successful list on transient network errors.+ if (isCurrent()) setError(formatRemoteError(cause));+ })+ .finally(() => {+ if (isCurrent()) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [apiFetch, focused, refreshVersion]);++ const refresh = useCallback(() => {+ if (!savingRef.current && !renameTarget && !deleteTarget)+ setRefreshVersion((value) => value + 1);+ }, [renameTarget, deleteTarget]);++ const openRename = useCallback(+ (device: DeviceView) => {+ // Do not race a pending list snapshot or another rename.+ if (loading || savingRef.current || deleteTarget) return;+ setRenameTarget(device);+ setRenameDraft(device.name);+ setRenameError(null);+ },+ [loading, deleteTarget],+ );++ const closeRename = useCallback(() => {+ if (!savingRef.current) setRenameTarget(null);+ }, []);++ const confirmRename = useCallback(+ async (draft?: string) => {+ const target = renameTarget;+ const name = (draft ?? renameDraft).trim();+ const lifetime = lifetimeRef.current;+ const owner = lifetime.owner;+ const isCurrent = () =>+ lifetime.active && isMobileAuthOwnerCurrent(owner);+ if (!isCurrent() || !target || !name || savingRef.current) return;+ if (name === target.name.trim()) {+ setRenameTarget(null);+ return;+ }+ if (name.length > MAX_DEVICE_NAME_LENGTH) {+ setRenameDraft(name);+ // A fresh error also reopens the native prompt after repeated invalid submissions.+ setRenameError(+ new Error(+ i18n.t('devices.management.nameTooLong', {+ limit: MAX_DEVICE_NAME_LENGTH,+ }),+ ),+ );+ return;+ }+ savingRef.current = true;+ setRenameSaving(true);+ setRenameError(null);+ try {+ const result = await apiFetch<{ deviceId: string; name: string }>(+ `/api/device-link/devices/${encodeURIComponent(target.deviceId)}`,+ {+ baseUrl: DEVICE_LINK_API_BASE_URL,+ body: { name },+ method: 'PATCH',+ timeoutMs: DEVICE_TIMEOUT_MS,+ },+ );+ if (!isCurrent()) return;+ setDevices((current) =>+ current.map((device) =>+ device.deviceId === target.deviceId+ ? { ...device, name: result.name }+ : device,+ ),+ );+ remoteSessionStore.renameDevice(target.deviceId, result.name);+ remoteSessionStore.setDeviceIdentity(+ remoteSessionStore+ .getDeviceIdentity()+ .map((item) =>+ item.deviceId === target.deviceId+ ? { ...item, name: result.name }+ : item,+ ),+ );+ setRenameTarget(null);+ } catch (cause) {+ if (isCurrent()) setRenameError(new Error(formatRemoteError(cause)));+ } finally {+ if (isCurrent()) {+ savingRef.current = false;+ setRenameSaving(false);+ }+ }+ },+ [apiFetch, renameDraft, renameTarget],+ );++ const openDelete = useCallback(+ (device: DeviceView) => {+ if (loading || savingRef.current || renameTarget) return;+ setDeleteError(null);+ setDeleteTarget(device);+ },+ [loading, renameTarget],+ );++ const closeDelete = useCallback(() => {+ if (!savingRef.current) setDeleteTarget(null);+ }, []);++ const confirmDelete = useCallback(async () => {+ const target = deleteTarget;+ const lifetime = lifetimeRef.current;+ const owner = lifetime.owner;+ const isCurrent = () => lifetime.active && isMobileAuthOwnerCurrent(owner);+ if (!isCurrent() || !target || savingRef.current) return false;+ savingRef.current = true;+ setDeleteSaving(true);+ setDeleteError(null);+ try {+ const result = await apiFetch<{ deviceId: string; deleted: boolean }>(+ `/api/device-link/devices/${encodeURIComponent(target.deviceId)}`,+ {+ baseUrl: DEVICE_LINK_API_BASE_URL,+ method: 'DELETE',+ timeoutMs: DEVICE_TIMEOUT_MS,+ },+ );+ if (!isCurrent()) return false;+ if (!result.deleted)+ throw new Error(i18n.t('devices.management.deleteFailed'));+ setDevices((current) =>+ current.filter((device) => device.deviceId !== target.deviceId),+ );+ remoteSessionStore.removeDevice(target.deviceId);+ remoteSessionStore.setDeviceIdentity(+ remoteSessionStore+ .getDeviceIdentity()+ .filter((item) => item.deviceId !== target.deviceId),+ );+ revokedDevicesStore.clearRevoked(target.deviceId);+ setDeleteTarget(null);+ return true;+ } catch (cause) {+ if (isCurrent())+ setDeleteError(+ (cause as { code?: string })?.code === 'ALREADY_EXISTS'+ ? i18n.t('devices.management.deleteOnline')+ : formatRemoteError(cause),+ );+ return false;+ } finally {+ if (isCurrent()) {+ savingRef.current = false;+ setDeleteSaving(false);+ }+ }+ }, [apiFetch, deleteTarget]);++ return {+ devices,+ loading,+ error,+ refresh,+ openRename,+ closeRename,+ confirmRename,+ renameTarget,+ renameDraft,+ setRenameDraft,+ renameSaving,+ renameError,+ deleteTarget,+ deleteSaving,+ deleteError,+ openDelete,+ closeDelete,+ confirmDelete,+ };+}diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex daaf29fea4..ee017174a8 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -1,4 +1,31 @@{+ "management": {+ "title": "Device Management",+ "openDevice": "View details for {{name}}",+ "details": "Device details",+ "retry": "Retry",+ "unknown": "Not available",+ "notFound": "This device is no longer in your account.",+ "deleteDevice": "Delete device",+ "deleteTitle": "Delete {{name}}?",+ "deleteMessage": "Remove this device from your device list. This does not delete files on the computer.",+ "deleteFailed": "Could not delete the device.",+ "deleteOnline": "This device is online. Take it offline before deleting it.",+ "currentlyOnline": "Currently online",+ "nameTooLong": "Device names must be {{limit}} characters or fewer.",+ "fields": {+ "name": "Name",+ "status": "Status",+ "platform": "Platform",+ "model": "Model",+ "systemVersion": "System version",+ "appVersion": "Cindy version",+ "cpu": "Processor",+ "memory": "Memory",+ "lastSeen": "Last online",+ "deviceId": "Device ID"+ }+ },"common": {"cancel": "Cancel","save": "Save",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 8416a96093..4783584937 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -1,4 +1,31 @@{+ "management": {+ "title": "デバイス管理",+ "openDevice": "{{name}} のデバイス詳細を表示",+ "details": "デバイスの詳細",+ "retry": "再試行",+ "unknown": "情報なし",+ "notFound": "このデバイスはアカウントに登録されていません。",+ "deleteDevice": "デバイスを削除",+ "deleteTitle": "「{{name}}」を削除しますか?",+ "deleteMessage": "デバイスを一覧から削除します。コンピューター上のファイルは削除されません。",+ "deleteFailed": "デバイスを削除できませんでした。",+ "deleteOnline": "デバイスがオンラインです。オフラインにしてから削除してください。",+ "currentlyOnline": "現在オンライン",+ "nameTooLong": "デバイス名は {{limit}} 文字以内で入力してください。",+ "fields": {+ "name": "名前",+ "status": "状態",+ "platform": "プラットフォーム",+ "model": "モデル",+ "systemVersion": "システムバージョン",+ "appVersion": "Cindy バージョン",+ "cpu": "プロセッサー",+ "memory": "メモリ",+ "lastSeen": "最終オンライン",+ "deviceId": "デバイス ID"+ }+ },"common": {"cancel": "キャンセル","save": "保存",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 322f7a4ed2..e25fdf9345 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -1,4 +1,31 @@{+ "management": {+ "title": "기기 관리",+ "openDevice": "{{name}} 기기 상세 정보 보기",+ "details": "기기 상세 정보",+ "retry": "다시 시도",+ "unknown": "정보 없음",+ "notFound": "이 기기는 더 이상 계정에 없습니다.",+ "deleteDevice": "기기 삭제",+ "deleteTitle": "{{name}} 기기를 삭제할까요?",+ "deleteMessage": "기기 목록에서 이 기기를 삭제합니다. 컴퓨터의 파일은 삭제되지 않습니다.",+ "deleteFailed": "기기를 삭제하지 못했습니다.",+ "deleteOnline": "기기가 온라인입니다. 오프라인으로 전환한 후 삭제하세요.",+ "currentlyOnline": "현재 온라인",+ "nameTooLong": "기기 이름은 {{limit}}자 이하여야 합니다.",+ "fields": {+ "name": "이름",+ "status": "상태",+ "platform": "플랫폼",+ "model": "모델",+ "systemVersion": "시스템 버전",+ "appVersion": "Cindy 버전",+ "cpu": "프로세서",+ "memory": "메모리",+ "lastSeen": "최근 접속",+ "deviceId": "기기 ID"+ }+ },"common": {"cancel": "취소","save": "저장",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex f3c001f72c..4f90ce9813 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -1,4 +1,31 @@{+ "management": {+ "title": "设备管理",+ "openDevice": "查看 {{name}} 的设备详情",+ "details": "设备详情",+ "retry": "重试",+ "unknown": "暂无信息",+ "notFound": "该设备已不在你的账号中。",+ "deleteDevice": "删除设备",+ "deleteTitle": "删除“{{name}}”?",+ "deleteMessage": "将此设备从设备列表中移除,不会删除电脑上的文件。",+ "deleteFailed": "删除设备失败。",+ "deleteOnline": "设备当前在线,请让设备离线后再删除。",+ "currentlyOnline": "当前在线",+ "nameTooLong": "设备名称不能超过 {{limit}} 个字符。",+ "fields": {+ "name": "名称",+ "status": "状态",+ "platform": "平台",+ "model": "机型",+ "systemVersion": "系统版本",+ "appVersion": "Cindy 版本",+ "cpu": "处理器",+ "memory": "内存",+ "lastSeen": "最近在线",+ "deviceId": "设备 ID"+ }+ },"common": {"cancel": "取消","save": "保存",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 1ea8509327..206d52b5c6 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -1,4 +1,31 @@{+ "management": {+ "title": "裝置管理",+ "openDevice": "查看 {{name}} 的裝置詳細資訊",+ "details": "裝置詳細資訊",+ "retry": "重試",+ "unknown": "暫無資訊",+ "notFound": "此裝置已不在你的帳號中。",+ "deleteDevice": "刪除裝置",+ "deleteTitle": "刪除「{{name}}」?",+ "deleteMessage": "將此裝置從裝置列表中移除,不會刪除電腦上的檔案。",+ "deleteFailed": "刪除裝置失敗。",+ "deleteOnline": "裝置目前在線,請讓裝置離線後再刪除。",+ "currentlyOnline": "目前在線",+ "nameTooLong": "裝置名稱不能超過 {{limit}} 個字元。",+ "fields": {+ "name": "名稱",+ "status": "狀態",+ "platform": "平台",+ "model": "機型",+ "systemVersion": "系統版本",+ "appVersion": "Cindy 版本",+ "cpu": "處理器",+ "memory": "記憶體",+ "lastSeen": "最近上線",+ "deviceId": "裝置 ID"+ }+ },"common": {"cancel": "取消","save": "儲存",diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsxindex 6b7d24cad6..b5ebc075cc 100644--- a/apps/mobile/src/session/HomeChromeDrawer.tsx+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx@@ -1,14 +1,14 @@/*** HomeChromeDrawer —— 首页左上角系统菜单。*- * 从左边滑出,不是下拉卡:现在有搜索任务和设置。+ * 从左边滑出,不是下拉卡:承载搜索、设备管理、设置和账号入口。* 不用 RN Modal,避免和首页其它 Modal 抢 present/dismiss。* iOS 系统导航栏在 RN 内容之上,树内 overlay 盖不住顶栏,所以走* react-native-screens FullWindowOverlay(独立 UIWindow)。* 新窗口里要自带 GestureHandlerRootView,左滑关闭才有效。* Android 无系统顶栏,继续树内 overlay。动画遵循 reduce-motion。*/-import { LogOut, Search, Settings, UsersRound } from 'lucide-react-native';+import { LogOut, Monitor, Search, Settings, UsersRound } from 'lucide-react-native';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {AccessibilityInfo,@@ -62,6 +62,7 @@ export function HomeChromeDrawer({onClosed,onOpenSearch,onOpenAccounts,+ onOpenDevices,onOpenSettings,onLogout,loggingOut = false,@@ -74,6 +75,7 @@ export function HomeChromeDrawer({onClosed?(): void;onOpenSearch(): void;onOpenAccounts(): void;+ onOpenDevices(): void;onOpenSettings(): void;onLogout(): void;loggingOut?: boolean;@@ -321,6 +323,17 @@ export function HomeChromeDrawer({</Text></Pressable>+ <Pressable+ accessibilityLabel={t('devices.management.title')}+ accessibilityRole="button"+ onPress={onOpenDevices}+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}+ testID="home.chromeDrawer.devices"+ >+ <Monitor color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />+ <Text numberOfLines={1} style={styles.menuLabel}>{t('devices.management.title')}</Text>+ </Pressable>+<PressableaccessibilityLabel={t("devices.list.a11y.openSettings")}accessibilityRole="button"diff --git a/apps/mobile/src/session/RenameDeviceModal.tsx b/apps/mobile/src/session/RenameDeviceModal.tsxnew file mode 100644index 0000000000..03dd24abf3--- /dev/null+++ b/apps/mobile/src/session/RenameDeviceModal.tsx@@ -0,0 +1,146 @@+import { Modal, Pressable, StyleSheet } from 'react-native';+import { useTranslation } from 'react-i18next';+import { Text, TextInput } from '@/components/AppText';+import { MainWindowActionGroup } from '@/components/MobilePrimitives';+import { MAX_DEVICE_NAME_LENGTH } from '@/device-link/deviceName';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+} from '@/theme/tokens';++export function RenameDeviceModal({+ draft,+ error,+ onCancel,+ onChangeDraft,+ onConfirm,+ saving,+ visible,+}: {+ draft: string;+ error: string | null;+ onCancel(): void;+ onChangeDraft(value: string): void;+ onConfirm(): void;+ saving: boolean;+ visible: boolean;+}) {+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ const { t } = useTranslation();+ const canSave = draft.trim().length > 0 && !saving;+ return (+ <Modal+ animationType="fade"+ transparent+ visible={visible}+ onRequestClose={onCancel}+ >+ <Pressable+ style={styles.renameDeviceBackdrop}+ onPress={onCancel}+ testID="home.renameDevice.backdrop"+ >+ <Pressable+ style={styles.renameDeviceCard}+ onPress={() => undefined}+ testID="home.renameDevice.modal"+ >+ <Text style={styles.renameDeviceTitle}>+ {t('devices.list.renameDevice.title')}+ </Text>+ <TextInput+ autoFocus+ editable={!saving}+ maxLength={MAX_DEVICE_NAME_LENGTH}+ onChangeText={onChangeDraft}+ onSubmitEditing={() => {+ if (canSave) onConfirm();+ }}+ placeholder={t('devices.list.renameDevice.placeholder')}+ placeholderTextColor={colors.textTertiary}+ returnKeyType="done"+ selectTextOnFocus+ style={styles.renameDeviceInput}+ testID="home.renameDevice.input"+ value={draft}+ />+ {error ? (+ <Text accessibilityRole="alert" style={styles.error}>+ {error}+ </Text>+ ) : null}+ {/* 确认对统一规则:共享满宽纵排组(保存在上/取消居底),置于卡片底部。 */}+ <MainWindowActionGroup+ primaryActions={[+ {+ accessibilityLabel: saving+ ? t('devices.list.renameDevice.savingA11y')+ : t('devices.list.renameDevice.saveA11y'),+ busy: saving,+ disabled: !canSave,+ label: saving+ ? t('devices.common.saving')+ : t('devices.common.save'),+ onPress: onConfirm,+ testID: 'home.renameDevice.save',+ tone: 'primary',+ },+ ]}+ cancelAction={{+ accessibilityLabel: t('devices.list.a11y.cancelRename'),+ disabled: saving,+ label: t('devices.common.cancel'),+ onPress: onCancel,+ testID: 'home.renameDevice.cancel',+ }}+ testID="home.renameDevice.actions"+ />+ </Pressable>+ </Pressable>+ </Modal>+ );+}++const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ error: { color: colors.destructive, fontSize: typeScale.body },+ renameDeviceBackdrop: {+ alignItems: 'center',+ backgroundColor: colors.overlay,+ flex: 1,+ justifyContent: 'center',+ paddingHorizontal: spacing.xl,+ },+ renameDeviceCard: {+ backgroundColor: colors.surfaceElevated,+ borderColor: colors.border,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ gap: spacing.md,+ maxWidth: 360,+ padding: spacing.lg,+ width: '100%',+ },+ renameDeviceTitle: {+ color: colors.textPrimary,+ fontSize: typeScale.title,+ fontWeight: fontWeight.medium,+ lineHeight: lineHeight.subtitle,+ },+ renameDeviceInput: {+ backgroundColor: colors.surface,+ borderColor: colors.border,+ borderRadius: radius.container,+ borderWidth: StyleSheet.hairlineWidth,+ color: colors.textPrimary,+ fontSize: typeScale.body,+ minHeight: 48,+ paddingHorizontal: spacing.md,+ paddingVertical: spacing.sm,+ },+ });diff --git a/apps/mobile/src/session/homeChromeMenus.ts b/apps/mobile/src/session/homeChromeMenus.tsindex a4bd7606d0..29e516db78 100644--- a/apps/mobile/src/session/homeChromeMenus.ts+++ b/apps/mobile/src/session/homeChromeMenus.ts@@ -192,35 +192,9 @@ function inlineGroup(};}-export const HOME_SCOPE_OPEN_PREFIX = "scope.open:";-export const HOME_SCOPE_RENAME_PREFIX = "scope.rename:";--export function parseHomeScopePullDownAction(- id: string,-):- | { kind: "select"; filterId: string }- | { kind: "open"; deviceId: string }- | { kind: "rename"; deviceId: string } {- if (id.startsWith(HOME_SCOPE_OPEN_PREFIX)) {- return { kind: "open", deviceId: id.slice(HOME_SCOPE_OPEN_PREFIX.length) };- }- if (id.startsWith(HOME_SCOPE_RENAME_PREFIX)) {- return {- kind: "rename",- deviceId: id.slice(HOME_SCOPE_RENAME_PREFIX.length),- };- }- return { kind: "select", filterId: id };-}-export function buildHomeScopePullDownActions(filters: readonly MobileHomeDeviceFilterItem[],allConversationsLabel: string,- deviceActions: {- openLabel: string;- renameLabel: string;- showTasksLabel: string;- },): NativePullDownAction[] {const allFilter = filters.find((item) => item.deviceId === null) ?? null;const deviceFilters = filters.filter(@@ -234,22 +208,7 @@ export function buildHomeScopePullDownActions(}for (const item of deviceFilters) {if (!item.deviceId) continue;- items.push({- id: `scope.submenu:${item.id}`,- state: item.selected ? "on" : "off",- subactions: [- checkable(item.id, deviceActions.showTasksLabel, item.selected),- {- id: `${HOME_SCOPE_OPEN_PREFIX}${item.deviceId}`,- title: deviceActions.openLabel,- },- {- id: `${HOME_SCOPE_RENAME_PREFIX}${item.deviceId}`,- title: deviceActions.renameLabel,- },- ],- title: item.label,- });+ items.push(checkable(item.id, item.label, item.selected));}return items;}