diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt index 3b00550d34..cd0373d350 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/account/AccountProfileCards.kt @@ -219,7 +219,7 @@ internal fun AccountSettingsDevicesSection( ) Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text( - device.name.ifBlank { device.id }, + device.displayName, fontSize = 15.sp, fontWeight = FontWeight.Medium, maxLines = 1, diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt index a6913c6fd2..d6e8a979fe 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/remote/ConnectAccountDeviceScreen.kt @@ -207,7 +207,7 @@ private fun DeviceListCard( ) Column(verticalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.weight(1f)) { Text( - device.name.ifBlank { device.id }, + device.displayName, fontSize = 15.sp, fontWeight = FontWeight.Medium, maxLines = 1, diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt index 9577f44e38..95f7a7ca1b 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/MobileScreen.kt @@ -474,7 +474,7 @@ internal fun MobileScreen(onAccountRestored: (Boolean) -> Unit = {}) { createDevices = readyAccount?.devices.orEmpty().map { device -> com.openbitfun.mobile.app.ui.remote.CreateDeviceChoice( id = device.id, - name = device.name, + name = device.displayName, online = device.online, selected = device.id == readyAccount?.selectedDeviceId, ) diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt index fc0504dfa9..5cc203f65c 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/shell/sidebar/SidebarRemoteWorkspaceSection.kt @@ -173,7 +173,7 @@ internal fun SidebarRemoteWorkspaceSection( projectedDevices.take(visibleDeviceCount).forEach { device -> val active = device.id == activeDeviceId SidebarDeviceSelectorRow( - deviceName = device.name.ifBlank { device.id }, + deviceName = device.displayName, online = device.online, selected = active, loading = active && (remoteState is RemoteSessionUiState.Loading || diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets index e42de18746..7f8b4b7b1c 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AccountProfilePanel.ets @@ -1,8 +1,9 @@ import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; +import { accountDeviceDisplayName, CloudAccountDevice } from '../../services/CloudAccountClient'; import { AccountDeviceSelectionPolicy } from '../policy/AccountDeviceSelectionPolicy'; import { DeviceModelSettingsEntryPolicy } from '../policy/DeviceModelSettingsEntryPolicy'; +import { DeviceDirectoryEntry, DeviceDirectoryState } from '../state/DeviceDirectoryState'; import { CARD, CONTENT_ON_ACTION, @@ -20,6 +21,7 @@ import { DefaultAccountAvatar } from './DefaultAccountAvatar'; /** Account identity and device management shared by Settings and account entry. */ @ComponentV2 export struct AccountProfilePanel { + @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param accountUsername: string = ''; @Param accountAvatarUrl: string = ''; @Param accountUserId: string = ''; @@ -42,7 +44,6 @@ export struct AccountProfilePanel { async (): Promise => []; @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = async (_device: CloudAccountDevice): Promise => {}; - @Local accountDevices: CloudAccountDevice[] = []; @Local accountDevicesBusy: boolean = false; @Local accountDevicesError: string = ''; @Local switchingDeviceId: string = ''; @@ -172,7 +173,7 @@ export struct AccountProfilePanel { if (!this.isAccountAuthenticated()) { Text(RemoteI18n.t('remote.settings.deviceLoginRequired')) .fontSize(MobileDesignTypography.bodySmall.size).lineHeight(MobileDesignTypography.bodySmall.lineHeight).fontColor(MUTED).width('100%') - } else if (this.accountDevicesBusy && this.accountDevices.length === 0) { + } else if (this.accountDevicesBusy && this.directoryState.devices.length === 0) { Text(RemoteI18n.t('remote.settings.deviceLoading')) .fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).width('100%') } else if (this.desktopDevices().length === 0) { @@ -189,7 +190,7 @@ export struct AccountProfilePanel { } .width('100%') }, (device: CloudAccountDevice): string => - `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${device.deviceName}` + + `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${accountDeviceDisplayName(device)}` + `:${this.isCurrentControlDevice(device) ? 'driven' : 'idle'}` + `:${this.supportsDeviceModelDefaults ? 'model-defaults' : 'no-model-defaults'}`) } @@ -219,7 +220,7 @@ export struct AccountProfilePanel { .width(28) .height(28) Column({ space: 2 }) { - Text(device.deviceName || device.deviceId) + Text(accountDeviceDisplayName(device)) .fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium).fontColor(INK) .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) Text(this.deviceStatus(device)) @@ -349,7 +350,7 @@ export struct AccountProfilePanel { this.accountDevicesBusy = true; this.accountDevicesError = ''; try { - this.accountDevices = await this.cloudListDevices(); + await this.cloudListDevices(); } catch (err) { this.accountDevicesError = err instanceof Error ? err.message : RemoteI18n.t('remote.settings.deviceLoadFailed'); @@ -358,8 +359,8 @@ export struct AccountProfilePanel { } } - private desktopDevices(): CloudAccountDevice[] { - return this.accountDevices.filter((device: CloudAccountDevice): boolean => + private desktopDevices(): DeviceDirectoryEntry[] { + return this.directoryState.devices.filter((device: DeviceDirectoryEntry): boolean => device.deviceId !== this.deviceId && device.deviceName !== 'HarmonyOS Phone'); } @@ -488,7 +489,7 @@ export struct AccountProfilePanel { @Monitor('accountUserId') private handleAccountUserChanged(): void { - if (this.isAccountAuthenticated() && this.accountDevices.length === 0) { + if (this.isAccountAuthenticated() && this.directoryState.devices.length === 0) { this.refreshAccountDevices(); } } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets index b65596fece..93898c02ce 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootOverlaySurfaces.ets @@ -128,6 +128,7 @@ export struct AppSidebarSurface { @ComponentV2 export struct AppSettingsSurface { + @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param shellState: AppShellState = new AppShellState(); @Param remotePageState: RemotePageState = new RemotePageState(); @Param generalPageState: GeneralChatPageState = new GeneralChatPageState(); @@ -145,6 +146,7 @@ export struct AppSettingsSurface { }) } else { SettingsSheet({ + directoryState: this.deviceDirectoryState, sheetState: this.shellState.settingsSheet, accountUsername: this.remotePageState.accountUsername, accountAvatarUrl: this.remotePageState.accountAvatarUrl, @@ -179,12 +181,14 @@ export struct AppSettingsSurface { @ComponentV2 export struct AppConnectSurface { + @Param deviceDirectoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param remotePageState: RemotePageState = new RemotePageState(); @Param deviceId: string = ''; @Param actions: AppRootPresentationActions = emptyAppRootPresentationActions(); build() { ConnectView({ + directoryState: this.deviceDirectoryState, remoteUrl: this.remotePageState.remoteUrl, userId: this.remotePageState.userId, statusText: this.remotePageState.conversation.statusText, diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets index 0a3a17d88f..ae50ff0452 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/AppRootPresentation.ets @@ -635,6 +635,7 @@ export struct AppRootPresentation { @Builder SettingsContent() { AppSettingsSurface({ + deviceDirectoryState: this.deviceDirectoryState, shellState: this.shellState, remotePageState: this.remotePageState, generalPageState: this.generalPageState, @@ -645,6 +646,7 @@ export struct AppRootPresentation { @Builder ConnectContent() { AppConnectSurface({ + deviceDirectoryState: this.deviceDirectoryState, remotePageState: this.remotePageState, deviceId: this.deviceId, actions: this.actions diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets index 98742c2b5f..eb33613f06 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectAccountDevicePage.ets @@ -1,12 +1,14 @@ import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; import { RemoteI18n } from '../../i18n/RemoteI18n'; -import { CloudAccountDevice } from '../../services/CloudAccountClient'; +import { accountDeviceDisplayName, CloudAccountDevice } from '../../services/CloudAccountClient'; import { ACCENT, CARD, STATUS_SUCCESS, INK, LINE, MUTED, PAGE_BG, STATUS_DANGER, SOFT } from './Theme'; import { AccountDeviceSelectionPolicy } from '../policy/AccountDeviceSelectionPolicy'; +import { DeviceDirectoryEntry, DeviceDirectoryState } from '../state/DeviceDirectoryState'; import { NavigationBackButton } from './NavigationBackButton'; @ComponentV2 export struct ConnectAccountDevicePage { + @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param deviceId: string = ''; @Param controlTargetDeviceId: string = ''; @Param connectionState: string = 'idle'; @@ -15,7 +17,6 @@ export struct ConnectAccountDevicePage { async (): Promise => []; @Event cloudSelectDevice: (device: CloudAccountDevice) => Promise = async (_device: CloudAccountDevice): Promise => {}; - @Local accountDevices: CloudAccountDevice[] = []; @Local accountDevicesBusy: boolean = false; @Local accountDevicesError: string = ''; @Local switchingDeviceId: string = ''; @@ -77,7 +78,7 @@ export struct ConnectAccountDevicePage { } .width('100%').height(38) - if (this.accountDevicesBusy && this.accountDevices.length === 0) { + if (this.accountDevicesBusy && this.directoryState.devices.length === 0) { Column() { this.AccountDeviceSkeletonRow() this.AccountDeviceSkeletonRow() @@ -95,7 +96,7 @@ export struct ConnectAccountDevicePage { ForEach(this.desktopDevices(), (device: CloudAccountDevice) => { this.AccountConnectDeviceRow(device) }, (device: CloudAccountDevice): string => - `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${device.deviceName}`) + `${device.deviceId}:${device.online ? 'online' : 'offline'}:${device.lastSeenAt || 0}:${accountDeviceDisplayName(device)}`) } .width('100%') } @@ -127,7 +128,7 @@ export struct ConnectAccountDevicePage { SymbolGlyph($r('sys.symbol.desktop')) .fontSize(22).fontColor([MUTED]).width(26).height(24).opacity(device.online ? 0.68 : 0.38) Column({ space: 3 }) { - Text(device.deviceName || device.deviceId) + Text(accountDeviceDisplayName(device)) .fontSize(MobileDesignTypography.titleSmall.size).fontWeight(FontWeight.Medium).fontColor(INK) .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) Text(this.accountDeviceStatus(device)) @@ -171,7 +172,7 @@ export struct ConnectAccountDevicePage { this.accountDevicesBusy = true; this.accountDevicesError = ''; try { - this.accountDevices = await this.cloudListDevices(); + await this.cloudListDevices(); } catch (err) { this.accountDevicesError = err instanceof Error ? err.message : RemoteI18n.t('remote.settings.deviceLoadFailed'); @@ -180,8 +181,8 @@ export struct ConnectAccountDevicePage { } } - private desktopDevices(): CloudAccountDevice[] { - return this.accountDevices.filter((device: CloudAccountDevice): boolean => + private desktopDevices(): DeviceDirectoryEntry[] { + return this.directoryState.devices.filter((device: DeviceDirectoryEntry): boolean => device.deviceId !== this.deviceId && device.deviceName !== 'HarmonyOS Phone'); } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets index 47d07139f0..aa0ed54087 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConnectView.ets @@ -1,6 +1,7 @@ import { MobileDesignTypography } from '../../generated/MobileDesignTokens'; import { RemoteI18n } from '../../i18n/RemoteI18n'; import { CloudAccountDevice } from '../../services/CloudAccountClient'; +import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; import { ConnectAccountDevicePage } from './ConnectAccountDevicePage'; import { AppActionButton, AppActionStyle } from './AppActionButton'; import { NavigationBackButton } from './NavigationBackButton'; @@ -21,6 +22,7 @@ import { WindowInsetsBinding } from '../../services/WindowSystemBarService'; */ @ComponentV2 export struct ConnectView { + @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param remoteUrl: string = ''; @Param userId: string = ''; @Param statusText: string = RemoteI18n.t('status.waitingConnection'); @@ -72,6 +74,7 @@ export struct ConnectView { @Builder AccountDeviceSelectionPage() { ConnectAccountDevicePage({ + directoryState: this.directoryState, deviceId: this.deviceId, controlTargetDeviceId: this.controlTargetDeviceId, connectionState: this.connectionState, diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets index fbbe311a8d..9630ebc114 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SettingsSheet.ets @@ -1,6 +1,7 @@ import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; import { RemoteI18n } from '../../i18n/RemoteI18n'; import { SettingsSheetState } from '../state/SettingsSheetState'; +import { DeviceDirectoryState } from '../state/DeviceDirectoryState'; import { DeviceModelDefaultsRequestPath } from '../state/DeviceModelDefaultsSheetState'; import { CARD, INK, LINE, MUTED, PAGE_BG } from './Theme'; import { CurrentControlSection } from './CurrentControlSection'; @@ -17,6 +18,7 @@ import { RemotePermissionSection } from './RemotePermissionSection'; @ComponentV2 export struct SettingsSheet { + @Param directoryState: DeviceDirectoryState = new DeviceDirectoryState(); @Param sheetState: SettingsSheetState = new SettingsSheetState(); @Param accountUsername: string = ''; @Param accountAvatarUrl: string = ''; @@ -162,6 +164,7 @@ export struct SettingsSheet { Scroll() { Column({ space: 0 }) { AccountProfilePanel({ + directoryState: this.directoryState, accountUsername: this.accountUsername, accountAvatarUrl: this.accountAvatarUrl, accountUserId: this.authenticatedUserId, diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets index 596f24acd1..0145880263 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/SidebarWorkspaceSection.ets @@ -170,7 +170,7 @@ export struct SidebarWorkspaceSection { tint: SIDEBAR_INK }) .hitTestBehavior(HitTestMode.None) - Text(entry.deviceName) + Text(entry.displayName) .fontSize(MobileDesignTypography.bodyMedium.size) .fontWeight(this.isSelected(entry) ? FontWeight.Bold : FontWeight.Regular) .fontColor(SIDEBAR_INK) @@ -200,7 +200,7 @@ export struct SidebarWorkspaceSection { .alignItems(VerticalAlign.Center) .backgroundColor(this.isSelected(entry) ? SIDEBAR_SELECTION : TRANSPARENT) .borderRadius(10) - .accessibilityText(`${entry.deviceName}, ${this.isActiveDevice(entry.deviceId) ? ConnectionStatusPresenter.label(this.connectionState) : + .accessibilityText(`${entry.displayName}, ${this.isActiveDevice(entry.deviceId) ? ConnectionStatusPresenter.label(this.connectionState) : RemoteI18n.t(entry.online ? 'sidebar.deviceOnline' : 'sidebar.deviceOffline')}`) .enabled(this.canUseDevice(entry) || this.canRetryDevice(entry)) .onClick(() => { @@ -342,7 +342,7 @@ export struct SidebarWorkspaceSection { tools: this.workspaceTools, canBrowse: this.isActiveDevice(this.workspacePickerDevice().deviceId), onBrowse: this.onWorkspaceTools, - deviceName: this.workspacePickerDevice().deviceName, + deviceName: this.workspacePickerDevice().displayName, savedConnections: this.workspacePickerDevice().deviceId === this.savedConnectionsTargetId ? this.savedConnections : [], workspaces: this.workspacePickerDevice().catalogSource.length > 0 ? this.workspacePickerDevice().recentWorkspaces : this.workspacesForDevice(this.workspacePickerDevice()), diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets index 1356cbfb69..c811a9c572 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/preview/ImmersiveBottomPreview.ets @@ -115,16 +115,13 @@ function gallery(): MiniAppSummary[] { return apps; } -function settingsDevices(): CloudAccountDevice[] { - const devices: CloudAccountDevice[] = []; +function settingsDevices(): DeviceDirectoryEntry[] { + const devices: DeviceDirectoryEntry[] = []; for (let index = 0; index < SETTINGS_DEVICES; index++) { const device = index + 1; - devices.push({ - deviceId: `account-desktop-${device}`, - deviceName: `Account desktop ${device}`, - online: device % 3 !== 0, - lastSeenAt: device - }); + const entry = emptyDeviceDirectoryEntry(`account-desktop-${device}`, `Account desktop ${device}`, device % 3 !== 0); + entry.lastSeenAt = device; + devices.push(entry); } return devices; } @@ -351,7 +348,9 @@ export struct ImmersiveBottomPreview { // be the greyed state. This fixture is the connected desktop's, so it // advertises the command and the sheet shows the entry it really shows. this.remotePageState.setHostCapabilities([REMOTE_CAPABILITY_DEVICE_MODEL_DEFAULTS_V1]); - this.previewActions = previewActionsWithDevices(settingsDevices()); + const devices = settingsDevices(); + this.directoryState.replace(devices); + this.previewActions = previewActionsWithDevices(devices); return; } if (scenarioId.endsWith('-connect')) { @@ -469,6 +468,7 @@ export struct ImmersiveBottomPreview { @Builder private Settings() { AppSettingsSurface({ + deviceDirectoryState: this.directoryState, shellState: this.shellState, remotePageState: this.remotePageState, actions: this.previewActions @@ -478,6 +478,7 @@ export struct ImmersiveBottomPreview { @Builder private Connect() { AppConnectSurface({ + deviceDirectoryState: this.directoryState, remotePageState: this.remotePageState, actions: this.previewActions }) diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets index 0c512a258b..24931d4b45 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets @@ -29,7 +29,7 @@ export class WorkspaceDirectoryState { } /** - * One account desktop in the sidebar. Nested @Trace fields are what + * One account desktop shared by the sidebar, settings and device picker. Nested @Trace fields are what * SidebarDeviceGroup actually watches — replacing a plain object on * the parent array does not update a reused ForEach child. */ @@ -37,6 +37,10 @@ export class WorkspaceDirectoryState { export class DeviceDirectoryEntry { @Trace deviceId: string = ''; @Trace deviceName: string = ''; + @Trace deviceAlias: string | null | undefined = undefined; + @Trace deviceKind: string | undefined = undefined; + @Trace lastSeenAt: number | undefined = undefined; + @Trace compatible: boolean | undefined = undefined; @Trace online: boolean = false; @Trace status: DeviceDirectoryStatus = 'idle'; @Trace errorText: string = ''; @@ -44,9 +48,13 @@ export class DeviceDirectoryEntry { @Trace catalogSource: string = ''; @Trace recentWorkspaces: RecentWorkspaceEntry[] = []; @Trace sessions: RemoteSession[] = []; + + get displayName(): string { + return this.deviceAlias ?? (this.deviceName || this.deviceId); + } } -/** Snapshot of every account desktop the sidebar can observe. */ +/** Shared observable directory of account desktops. */ @ObservedV2 export class DeviceDirectoryState { @Trace refreshing: boolean = false; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets index 582ad4fd49..fb994fe035 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/DeviceDirectoryViewModel.ets @@ -90,6 +90,10 @@ export class DeviceDirectoryViewModel { return { deviceId: item.deviceId, deviceName: item.deviceName, + deviceAlias: item.deviceAlias, + deviceKind: item.deviceKind, + lastSeenAt: item.lastSeenAt, + compatible: item.compatible, online: item.online }; })); @@ -256,6 +260,10 @@ export class DeviceDirectoryViewModel { const existing = this.state.find(device.deviceId); if (existing) { existing.deviceName = device.deviceName || existing.deviceName; + existing.deviceAlias = device.deviceAlias; + existing.deviceKind = device.deviceKind; + existing.lastSeenAt = device.lastSeenAt; + existing.compatible = device.compatible; if (existing.online && !online) { this.inFlight.delete(device.deviceId); if (existing.status === 'loading') existing.status = 'idle'; @@ -268,6 +276,10 @@ export class DeviceDirectoryViewModel { device.deviceName || device.deviceId, online ); + created.deviceAlias = device.deviceAlias; + created.deviceKind = device.deviceKind; + created.lastSeenAt = device.lastSeenAt; + created.compatible = device.compatible; return created; }); this.state.replace(next); diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets index 8ea37e4ef8..54c98571bb 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets @@ -9,6 +9,7 @@ import { CloudAccountDevice, CloudAccountRequestError, CloudAccountSession, + accountDeviceDisplayName, isDeviceControllable } from '../../services/CloudAccountClient'; import { CloudAccountSessionStore, PersistedCloudAccountSession } from '../../services/CloudAccountSessionStore'; @@ -74,6 +75,7 @@ export class SettingsController { private accountDevices: CloudAccountDevice[] = []; private lastAccountDevicesAt: number = 0; private stopPresence?: () => void; + private latestPresence?: string[]; private presenceGeneration: number = 0; private presenceRefreshing: boolean = false; private targetProbeTimer: number = -1; @@ -292,9 +294,12 @@ export class SettingsController { this.stopPresence = binding.client.observePresence(binding.relayUrl, binding.session, (ids: string[]) => { if (epoch !== this.presenceGeneration) return; + this.latestPresence = ids.slice(); const previousTarget = this.accountDevices.find((device: CloudAccountDevice) => device.deviceId === this.requireCloud().remoteState.controlTargetDeviceId); this.accountDevices = this.accountDevices.map((device: CloudAccountDevice): CloudAccountDevice => ({ deviceId: device.deviceId, deviceName: device.deviceName, deviceKind: device.deviceKind, + deviceAlias: device.deviceAlias, + compatible: device.compatible, lastSeenAt: device.lastSeenAt, online: ids.includes(device.deviceId) })); const cloud = this.requireCloud(); @@ -322,6 +327,7 @@ export class SettingsController { stopPresencePolling(): void { this.presenceGeneration++; + this.latestPresence = undefined; this.stopPresence?.(); this.stopPresence = undefined; if (this.targetProbeTimer !== -1) clearTimeout(this.targetProbeTimer); this.targetProbeTimer = -1; @@ -435,11 +441,30 @@ export class SettingsController { if (!session || this.cloudRelayUrl.length === 0) { return []; } + const presenceAtStart = this.latestPresence; try { const devices = await cloud.client.listDevices(this.cloudRelayUrl, session, cloud.hooks.deviceId()); if (this.cloudSession !== session) throw new Error('Account changed while loading devices'); + // A presence snapshot received during this request is newer than its + // HTTP answer. Keep that liveness while accepting refreshed metadata. + const presence = this.latestPresence; + if (presence !== undefined && presence !== presenceAtStart) { + for (const device of devices) { + device.online = presence.includes(device.deviceId); + } + } this.accountDevices = devices; this.lastAccountDevicesAt = Date.now(); + const target = devices.find((device: CloudAccountDevice): boolean => + device.deviceId === cloud.remoteState.controlTargetDeviceId); + if (target && cloud.remoteState.controlTargetType === 'account_device') { + const displayName = accountDeviceDisplayName(target); + cloud.remoteState.setControlTarget('account_device', target.deviceId, displayName); + cloud.remoteState.setDesktopIdentity(displayName, target.deviceId); + } + const preferred = devices.find((device: CloudAccountDevice): boolean => + device.deviceId === this.preferredTargetDeviceId); + if (preferred) this.setPreferredCloudTarget(preferred.deviceId, accountDeviceDisplayName(preferred)); cloud.hooks.onAccountDevices(devices); return devices; } catch (err) { @@ -532,7 +557,7 @@ export class SettingsController { const devices = await this.listCloudAccountDevices(); const target = devices.find((device: CloudAccountDevice): boolean => device.deviceId === targetId); if (!target || !target.online) { - const targetName = target?.deviceName || targetDeviceName || targetId; + const targetName = target ? accountDeviceDisplayName(target) : targetDeviceName || targetId; remoteState.setControlTarget('account_device', targetId, targetName); remoteState.setDesktopIdentity(targetName, targetId); remoteState.setConnectionState('reconnecting'); @@ -543,6 +568,7 @@ export class SettingsController { await this.selectCloudAccountDevice({ deviceId: target.deviceId, deviceName: target.deviceName || targetDeviceName || target.deviceId, + deviceAlias: target.deviceAlias, online: target.online, lastSeenAt: target.lastSeenAt, compatible: target.compatible @@ -626,8 +652,9 @@ export class SettingsController { RemoteLogger.info( `account device sync device=${deviceId} workspace=${initialSync.workspace.path} sessions=${initialSync.sessions.length}` ); - cloud.remoteState.setControlTarget('account_device', deviceId, device.deviceName); - cloud.remoteState.setDesktopIdentity(device.deviceName, deviceId); + const displayName = accountDeviceDisplayName(device); + cloud.remoteState.setControlTarget('account_device', deviceId, displayName); + cloud.remoteState.setDesktopIdentity(displayName, deviceId); cloud.remoteState.setWorkspace( initialSync.workspace.name, initialSync.workspace.path, @@ -646,7 +673,7 @@ export class SettingsController { cloud.remoteState.setAuthenticatedUserId(initialSync.authenticatedUserId); cloud.remoteState.setHostCapabilities(initialSync.capabilities || []); cloud.remoteState.setConnectionState('connected'); - this.setPreferredCloudTarget(deviceId, device.deviceName || deviceId); + this.setPreferredCloudTarget(deviceId, displayName); await this.saveControlTargetType('account_device'); this.resyncAccountDevicePresence(); cloud.remoteState.setStatusText(RemoteI18n.t('connection.connected')); @@ -660,7 +687,7 @@ export class SettingsController { cloud.hooks.navigateRemoteHome(); } try { - await this.persistCurrentCloudSessionTarget(deviceId, device.deviceName || deviceId); + await this.persistCurrentCloudSessionTarget(deviceId, displayName); } catch (err) { RemoteLogger.warn(`account target persistence failed device=${deviceId}: ${String(err)}`); } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets index 60ab49eb1b..a63f0eacec 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets @@ -88,6 +88,7 @@ export interface CloudAccountBinding { export interface CloudAccountDevice { deviceId: string; deviceName: string; + deviceAlias?: string | null; deviceKind?: string; online: boolean; lastSeenAt?: number; @@ -102,6 +103,11 @@ export interface CloudAccountDevice { compatible?: boolean; } +/** Keep the registered name available to legacy device-kind filtering. */ +export function accountDeviceDisplayName(device: CloudAccountDevice): string { + return device.deviceAlias ?? (device.deviceName || device.deviceId); +} + /** The single gate every control entry point must reuse; see `compatible`. */ export function isDeviceControllable(device: CloudAccountDevice): boolean { return device.compatible !== false; @@ -132,6 +138,7 @@ interface ProvisionDeviceWire { interface CloudAccountDeviceWire { device_id: string; device_name: string; + device_alias?: string | null; device_kind?: string; online: boolean; last_seen_at?: number; @@ -419,6 +426,7 @@ export class CloudAccountClient { return hosts.map((device: CloudAccountDeviceWire): CloudAccountDevice => ({ deviceId: device.device_id, deviceName: device.device_name || device.device_id, + deviceAlias: device.device_alias, deviceKind: device.device_kind, online: device.online, lastSeenAt: device.last_seen_at, diff --git a/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs b/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs index 2dcf5e750a..1a74b4408f 100644 --- a/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs @@ -4,12 +4,23 @@ const fs = require('node:fs'); const path = require('node:path'); const ts = require('typescript'); const official = 'https://remote.openbitfun.com/v/1.0.2'; +const linkSource = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/services/AccountDeviceLink.ets'), 'utf8'); +const linkJs = ts.transpileModule(linkSource, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText; +const accountLink = {}; +new Function('exports', linkJs)(accountLink); +const accountSource = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/services/CloudAccountClient.ets'), 'utf8'); +const accountJs = ts.transpileModule(accountSource, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText; +const account = {}; +new Function('require', 'exports', accountJs)(name => ({ + './AccountDeviceLink': { OFFICIAL_RELAY_URL: official }, + './RemoteCrypto': { HarmonyRemoteCryptoCipher: class {} }, +}[name] || {}), account); const source = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/pages/viewmodel/SettingsController.ets'), 'utf8'); const js = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText; const exported = {}; new Function('require', 'exports', js)(name => ({ - '../../services/AccountDeviceLink': { OFFICIAL_RELAY_URL: official }, - '../../services/CloudAccountClient': { DEFAULT_CLOUD_RELAY_URL: official }, + '../../services/AccountDeviceLink': accountLink, + '../../services/CloudAccountClient': account, '../../services/RemoteLogger': { RemoteLogger: { warn() {} } }, '../../i18n/RemoteI18n': { RemoteI18n: { t: key => key } }, }[name] || {}), exported); @@ -35,3 +46,97 @@ test('an older relay credential retains its saved profile without claiming curre assert.equal(cleared, false); assert.equal(record.token, 'old-token'); }); + +test('device aliases are read without changing legacy device filtering or raw names', async () => { + const client = new account.CloudAccountClient(); + client.request = async () => [ + { device_id: 'desktop', device_name: 'Studio Mac', device_alias: 'HarmonyOS Phone', online: true, device_kind: 'desktop' }, + { device_id: 'cleared', device_name: 'Office PC', device_alias: null, online: false }, + { device_id: 'legacy', device_name: 'Legacy PC', online: true }, + { device_id: 'unnamed', device_name: '', online: false }, + { device_id: 'phone', device_name: 'HarmonyOS Phone', device_alias: 'Office', online: true }, + ]; + const devices = await client.listDevices(official, { token: 'token' }); + assert.deepEqual(devices.map(device => device.deviceId), ['desktop', 'cleared', 'legacy', 'unnamed']); + assert.equal(devices[0].deviceName, 'Studio Mac'); + assert.deepEqual(devices.map(account.accountDeviceDisplayName), ['HarmonyOS Phone', 'Office PC', 'Legacy PC', 'unnamed']); +}); + +test('directory refresh and presence retain aliases in the selected and preferred device names', async () => { + let alias = 'Office'; + let onPresence; + let published; + const client = new account.CloudAccountClient(); + client.request = async () => [ + { device_id: 'desktop', device_name: 'Studio Mac', device_alias: alias, online: true, compatible: false }, + ]; + client.observePresence = (_relay, _session, listener) => { onPresence = listener; return () => {}; }; + const state = { + controlTargetType: 'account_device', controlTargetDeviceId: 'desktop', + setControlTarget(type, id, name) { this.controlTargetType = type; this.controlTargetDeviceId = id; this.controlTargetDeviceName = name; }, + setDesktopIdentity(name, id) { this.desktopName = name; this.desktopId = id; }, + }; + const controller = new exported.SettingsController({ client, remoteState: state, hooks: { + deviceId: () => 'phone', onAccountDevices: devices => { published = devices; }, + } }); + controller.cloudSession = { token: 'token', userId: 'user' }; + controller.cloudRelayUrl = official; + controller.setPreferredCloudTarget('desktop', 'Old name'); + await controller.listCloudAccountDevices(); + assert.equal(state.controlTargetDeviceName, 'Office'); + assert.equal(state.desktopName, 'Office'); + assert.equal(controller.preferredCloudTarget().deviceName, 'Office'); + controller.startPresencePolling(0); + onPresence(['desktop']); + assert.equal(account.accountDeviceDisplayName(published[0]), 'Office'); + assert.equal(published[0].deviceName, 'Studio Mac'); + assert.equal(published[0].compatible, false); + + alias = 'Work PC'; + await controller.listCloudAccountDevices(); + assert.equal(state.controlTargetDeviceName, 'Work PC'); + alias = null; + await controller.listCloudAccountDevices(); + assert.equal(state.controlTargetDeviceName, 'Studio Mac'); + assert.equal(controller.preferredCloudTarget().deviceName, 'Studio Mac'); + assert.equal(state.controlTargetDeviceId, 'desktop'); + controller.stopPresencePolling(); +}); + +for (const online of [true, false]) { + test(`a delayed device list retains newer ${online ? 'online' : 'offline'} presence and refreshes metadata`, async () => { + const device = { deviceId: 'desktop', deviceName: 'Desktop', online: !online }; + let onPresence; + let published; + const client = { + listDevices: async () => [{ ...device }], + observePresence: (_relay, _session, listener) => { onPresence = listener; return () => {}; }, + }; + const controller = new exported.SettingsController({ client, remoteState: {}, hooks: { + deviceId: () => 'phone', onAccountDevices: devices => { published = devices; }, + } }); + controller.cloudSession = { token: 'token', userId: 'user' }; + controller.cloudRelayUrl = official; + await controller.listCloudAccountDevices(); + controller.startPresencePolling(0); + + let resolve; + client.listDevices = () => new Promise(yes => { resolve = yes; }); + const pending = controller.listCloudAccountDevices(); + onPresence(online ? ['desktop'] : []); + assert.equal(published[0].online, online); + resolve([{ ...device, deviceAlias: 'Office', compatible: false }]); + const result = await pending; + assert.equal(result[0].online, online); + assert.equal(published[0].online, online); + assert.equal(controller.knownAccountDevice('desktop').online, online); + assert.equal(published[0].deviceAlias, 'Office'); + assert.equal(published[0].compatible, false); + + // A later explicit read must still recover from a missed presence event. + client.listDevices = async () => [{ ...device }]; + await controller.listCloudAccountDevices(); + assert.equal(published[0].online, !online); + controller.stopPresencePolling(); + }); +} diff --git a/src/apps/mobile/harmonyos/tools/tests/device-directory-lifecycle.test.cjs b/src/apps/mobile/harmonyos/tools/tests/device-directory-lifecycle.test.cjs index 19989b8469..070433b85f 100644 --- a/src/apps/mobile/harmonyos/tools/tests/device-directory-lifecycle.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/device-directory-lifecycle.test.cjs @@ -193,3 +193,29 @@ test('directory restores the active target and refresh preserves an explicit sel f.vm.syncDevices([{ deviceId: 'desktop', online: true }, { deviceId: 'other', online: false }]); assert.equal(f.state.selectedDeviceId, 'other'); }); + +test('shared device rows update presence and metadata without replacing their loaded directory', () => { + const f = fixture(); + f.active('desktop'); + f.vm.completeLiveCatalog('desktop', [{ path: '/project' }], 'opened', []); + const entry = f.state.find('desktop'); + const workspaces = entry.workspaces; + const device = { deviceId: 'desktop', deviceName: 'Desktop', online: true, deviceKind: 'desktop', lastSeenAt: 42, compatible: false }; + f.vm.syncDevices([{ ...device, deviceAlias: 'Office' }]); + assert.equal(f.state.find('desktop'), entry); + assert.equal(entry.displayName, 'Office'); + assert.equal(entry.deviceName, 'Desktop'); + f.vm.refreshActive(); + assert.equal(entry.displayName, 'Office'); + assert.equal(entry.deviceKind, 'desktop'); + assert.equal(entry.lastSeenAt, 42); + assert.equal(entry.compatible, false); + f.active(''); + f.vm.syncDevices([{ ...device, online: false, deviceAlias: 'Office' }]); + assert.equal(entry.online, false, 'already open views must observe the offline transition'); + f.vm.syncDevices([{ ...device, deviceAlias: null }]); + assert.equal(entry.online, true, 'the same row must return online without reopening a view'); + assert.equal(entry.displayName, 'Desktop'); + assert.equal(entry.workspaces, workspaces); + assert.equal(f.state.selectedDeviceId, 'desktop'); +}); diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+Account.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+Account.swift index a2f1cb9b96..b47a0591c2 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+Account.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+Account.swift @@ -258,7 +258,7 @@ extension MobileAppModel { let targetKey = "account:\(device.id)" return MobileAccountDevice( id: device.id, - name: device.name, + name: device.displayName, online: device.online || (targetKey == remoteExpectedDeviceKey && remoteConnected && remoteInitialSessionReady), selected: device.id == ready.selectedDeviceId diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt index 7c126343fe..c23845e7de 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt @@ -347,7 +347,7 @@ public class AccountStore internal constructor( val preferred = AccountDevicePolicy.preferredTarget(devices, deviceId) val selected = loggedIn.copy( targetDeviceId = preferred?.id, - targetDeviceName = preferred?.name, + targetDeviceName = preferred?.displayName, ) if (!persistLogin(selected)) return@launch session = selected @@ -389,7 +389,7 @@ public class AccountStore internal constructor( ?: AccountDevicePolicy.preferredTarget(devices, deviceId) val selected = current.copy( targetDeviceId = preferred?.id, - targetDeviceName = preferred?.name, + targetDeviceName = preferred?.displayName, ) // This retry only refreshes the volatile device-list projection. The // authenticated bytes saved before the failed list request stay exact. @@ -439,10 +439,10 @@ public class AccountStore internal constructor( val selected = ready.devices.firstOrNull { it.id == targetId } ?.takeIf { AccountDevicePolicy.canSelect(it, deviceId) } ?: return - val updated = current.copy(targetDeviceId = selected.id, targetDeviceName = selected.name) + val updated = current.copy(targetDeviceId = selected.id, targetDeviceName = selected.displayName) if (!persistLogin(updated)) return session = updated - _state.value = ready.copy(selectedDeviceId = selected.id, selectedDeviceName = selected.name) + _state.value = ready.copy(selectedDeviceId = selected.id, selectedDeviceName = selected.displayName) } /** @@ -466,7 +466,7 @@ public class AccountStore internal constructor( val active = session!! val selected = if (pendingInitialDeviceSelection) { val preferred = AccountDevicePolicy.preferredTarget(devices, deviceId) - active.copy(targetDeviceId = preferred?.id, targetDeviceName = preferred?.name) + active.copy(targetDeviceId = preferred?.id, targetDeviceName = preferred?.displayName) } else active pendingInitialDeviceSelection = false session = selected @@ -556,7 +556,8 @@ public class AccountStore internal constructor( username = displayedProfile?.takeIf { it.userId == current.userId }?.username ?: current.username, devices = controllableDevices, selectedDeviceId = current.targetDeviceId.takeIf { selectionConfirmed }, - selectedDeviceName = current.targetDeviceName.takeIf { selectionConfirmed }, + selectedDeviceName = (controllableDevices.firstOrNull { it.id == current.targetDeviceId }?.displayName + ?: current.targetDeviceName).takeIf { selectionConfirmed }, ).copy(avatarUrl = displayedProfile?.takeIf { it.userId == current.userId }?.avatarUrl) enrichProfile(current) } @@ -798,7 +799,7 @@ private class CloudBackend( private fun AccountSessionData.toTransportSession(): CloudAccountSession = CloudAccountSession(token, userId, masterKey) - private fun CloudAccountDevice.toUi(): AccountDeviceUi = AccountDeviceUi(deviceId, deviceName, online, lastSeenAt, compatible) + private fun CloudAccountDevice.toUi(): AccountDeviceUi = AccountDeviceUi(deviceId, deviceName, online, lastSeenAt, compatible, deviceAlias) } @Serializable diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountUiState.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountUiState.kt index a91e7f425b..ff9e026d96 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountUiState.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountUiState.kt @@ -28,9 +28,14 @@ public data class AccountDeviceUi public constructor( * builds. `false` is confirmed incompatible and is never a control target; * null is an older Relay that does not gate, "unknown but usable". */ - public val compatible: Boolean? = null, + public val compatible: Boolean?, + public val deviceAlias: String?, ) { public constructor(id: String, name: String, online: Boolean, lastSeenAt: Long?) : this(id, name, online, lastSeenAt, null) + public constructor(id: String, name: String, online: Boolean, lastSeenAt: Long?, compatible: Boolean?) : this(id, name, online, lastSeenAt, compatible, null) + + /** Keep the registered name available to legacy device-kind filtering. */ + public val displayName: String get() = deviceAlias ?: name.ifBlank { id } /** The single gate every control entry point reuses; see [compatible]. */ public val controllable: Boolean get() = compatible != false diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountStoreTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountStoreTest.kt index 8e4585935c..c693ab3909 100644 --- a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountStoreTest.kt +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/account/AccountStoreTest.kt @@ -326,7 +326,10 @@ class AccountStoreTest { @Test fun onlyControllableDevicesReachTheList() = runTest { - val store = AccountStore.create(this, FakeAccountBackend(), MemorySecureStore(), "phone-1", "Android") + val backend = FakeAccountBackend().also { + it.deviceAliases = mapOf("phone-2" to "Studio Mac", "desktop-1" to "HarmonyOS Phone") + } + val store = AccountStore.create(this, backend, MemorySecureStore(), "phone-1", "Android") store.dispatch(AccountIntent.Login) advanceUntilIdle() @@ -334,6 +337,46 @@ class AccountStoreTest { // This device and the user's other phone are gone; the offline desktop // stays, because "known but not running" is worth showing. assertEquals(listOf("desktop-1", "desktop-2"), ready.devices.map { it.id }) + assertEquals("HarmonyOS Phone", ready.devices.first().displayName) + assertEquals("Desktop", ready.devices.first().name) + } + + @Test + fun selectedDeviceAliasRefreshesAndClearsWithoutChangingItsIdentity() = runTest { + val backend = FakeAccountBackend().also { + it.desktop2Online = true + it.deviceAliases = mapOf("desktop-1" to "Studio", "desktop-2" to "Office") + } + val secure = MemorySecureStore() + val store = AccountStore.create(this, backend, secure, "phone-1", "Android") + store.dispatch(AccountIntent.Login) + advanceUntilIdle() + assertEquals("Studio", assertIs(store.state.value).selectedDeviceName) + store.dispatch(AccountIntent.SelectDevice("desktop-2")) + assertEquals("Office", assertIs(store.state.value).selectedDeviceName) + val saved = secure.read("github_device_session_v1")!! + + backend.deviceAliases = mapOf("desktop-2" to "Work PC") + store.dispatch(AccountIntent.RefreshDevices) + advanceUntilIdle() + val refreshed = assertIs(store.state.value) + assertEquals("Work PC", refreshed.selectedDeviceName) + assertEquals("Work PC", refreshed.devices.single { it.id == "desktop-2" }.displayName) + assertEquals("desktop-2", refreshed.selectedDeviceId) + + backend.deviceAliases = emptyMap() + store.dispatch(AccountIntent.RefreshDevices) + advanceUntilIdle() + assertEquals("DESKTOP-KM3L4UI", assertIs(store.state.value).selectedDeviceName) + assertContentEquals(saved, secure.read("github_device_session_v1")) + store.stop() + + val restored = AccountStore.create(this, backend, secure, "phone-1", "Android") + restored.dispatch(AccountIntent.Restore) + advanceUntilIdle() + val ready = assertIs(restored.state.value) + assertEquals("desktop-2", ready.selectedDeviceId) + assertEquals("DESKTOP-KM3L4UI", ready.selectedDeviceName) } @Test @@ -843,6 +886,7 @@ private class FakeAccountBackend : AccountBackend { var listThrowable: Throwable? = null var desktop1Online: Boolean = true var desktop2Online: Boolean = false + var deviceAliases: Map = emptyMap() var settings: String? = null val transportTargets = mutableListOf() override suspend fun login( @@ -880,7 +924,7 @@ private class FakeAccountBackend : AccountBackend { AccountDeviceUi("phone-2", "HarmonyOS Phone", true, 1), AccountDeviceUi("desktop-1", "Desktop", desktop1Online, 1), AccountDeviceUi("desktop-2", "DESKTOP-KM3L4UI", desktop2Online, 1), - ) + ).map { it.copy(deviceAlias = deviceAliases[it.id]) } } diff --git a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt index 104845ddc9..f2b1bb575b 100644 --- a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt +++ b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt @@ -195,6 +195,7 @@ public data class CloudAccountDevice public constructor( * treated as "unknown but usable", never as incompatible. */ public val compatible: Boolean? = null, + public val deviceAlias: String? = null, ) { /** The single gate every control entry point reuses; see [compatible]. */ public val controllable: Boolean get() = compatible != false @@ -331,6 +332,7 @@ public class CloudAccountClient internal constructor( device.lastSeenAt, device.deviceKind, device.compatible, + device.deviceAlias, ) } @@ -693,6 +695,7 @@ private data class AccountDeviceWire( @SerialName("last_seen_at") val lastSeenAt: Long? = null, @SerialName("device_kind") val deviceKind: String? = null, val compatible: Boolean? = null, + @SerialName("device_alias") val deviceAlias: String? = null, ) private fun decode(value: String): ByteArray = try { diff --git a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt index eed5599cf6..4a60251aab 100644 --- a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt +++ b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt @@ -132,8 +132,8 @@ class CloudAccountClientTest { fun deviceDirectoryCarriesTheRelayCompatibilityVerdict() = runTest { val engine = MockEngine { _ -> json("""[ - {"device_id":"d-1","device_name":"Desktop 1","device_kind":"desktop","online":true,"compatible":true}, - {"device_id":"d-2","device_name":"Desktop 2","device_kind":"desktop","online":true,"compatible":false}, + {"device_id":"d-1","device_name":"Desktop 1","device_alias":"Office","device_kind":"desktop","online":true,"compatible":true}, + {"device_id":"d-2","device_name":"Desktop 2","device_alias":null,"device_kind":"desktop","online":true,"compatible":false}, {"device_id":"d-3","device_name":"Desktop 3","device_kind":"desktop","online":true} ]""") } @@ -145,6 +145,8 @@ class CloudAccountClientTest { // An older Relay that does not gate reads as "unknown but usable". assertEquals(null, devices.getValue("d-3").compatible) assertEquals(listOf(true, false, true), listOf("d-1", "d-2", "d-3").map { devices.getValue(it).controllable }) + assertEquals(listOf("Office", null, null), listOf("d-1", "d-2", "d-3").map { devices.getValue(it).deviceAlias }) + assertEquals("Desktop 1", devices.getValue("d-1").deviceName) } @Test @@ -175,12 +177,12 @@ class CloudAccountClientTest { val engine = MockEngine { json( """[ - {"device_id":"desktop-1","device_name":"Studio Mac","online":true,"device_kind":"desktop"}, + {"device_id":"desktop-1","device_name":"Studio Mac","device_alias":"HarmonyOS Phone","online":true,"device_kind":"desktop"}, {"device_id":"cli-1","device_name":"Build host","online":true,"device_kind":"cli"}, {"device_id":"phone-2","device_name":"Pixel 8","online":true,"device_kind":"mobile"}, {"device_id":"watch-1","device_name":"Watch","online":false,"device_kind":"watch"}, {"device_id":"phone-1","device_name":"Pixel 8","online":true}, - {"device_id":"harmony-phone","device_name":"HarmonyOS Phone","online":true}, + {"device_id":"harmony-phone","device_name":"HarmonyOS Phone","device_alias":"Studio Mac","online":true}, {"device_id":"harmony-watch","device_name":"HarmonyOS Watch","online":false}, {"device_id":"phone-3","device_name":"Legacy Phone","online":true}, {"device_id":"watch-2","device_name":"Legacy Watch","online":false}, @@ -203,6 +205,8 @@ class CloudAccountClientTest { assertEquals("desktop", devices[0].deviceKind) assertEquals("cli", devices[1].deviceKind) assertEquals(null, devices[2].deviceKind) + assertEquals("Studio Mac", devices[0].deviceName) + assertEquals("HarmonyOS Phone", devices[0].deviceAlias) } @Test