From 4117124504a99741ae8e16f6332ca1c60001e805 Mon Sep 17 00:00:00 2001 From: guantw Date: Wed, 11 Nov 2026 15:37:36 +0900 Subject: [PATCH 1/3] feat(mobile): display account device aliases Prefer account device aliases in Android, iOS and HarmonyOS device lists, sidebars and selected-target labels. Preserve registered names for device filtering and fall back to the device name or ID when no alias is supplied. Refresh selected labels when aliases change or are cleared. --- .../app/ui/account/AccountProfileCards.kt | 2 +- .../ui/remote/ConnectAccountDeviceScreen.kt | 2 +- .../mobile/app/ui/shell/MobileScreen.kt | 2 +- .../sidebar/SidebarRemoteWorkspaceSection.kt | 2 +- .../pages/components/AccountProfilePanel.ets | 6 +- .../components/ConnectAccountDevicePage.ets | 6 +- .../components/SidebarWorkspaceSection.ets | 6 +- .../ets/pages/state/DeviceDirectoryState.ets | 5 ++ .../viewmodel/DeviceDirectoryViewModel.ets | 3 + .../pages/viewmodel/SettingsController.ets | 24 +++++-- .../main/ets/services/CloudAccountClient.ets | 8 +++ .../tools/tests/account-restore.test.cjs | 70 ++++++++++++++++++- .../tests/device-directory-lifecycle.test.cjs | 19 +++++ .../MobileAppModel+Account.swift | 2 +- .../core/feature/account/AccountStore.kt | 15 ++-- .../core/feature/account/AccountUiState.kt | 7 +- .../core/feature/account/AccountStoreTest.kt | 48 ++++++++++++- .../core/transport/CloudAccountClient.kt | 3 + .../core/transport/CloudAccountClientTest.kt | 12 ++-- 19 files changed, 207 insertions(+), 35 deletions(-) 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..ba1d0e0ef0 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,6 +1,6 @@ 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 { @@ -189,7 +189,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 +219,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)) 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..9ebbc51ad7 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,6 +1,6 @@ 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 { NavigationBackButton } from './NavigationBackButton'; @@ -95,7 +95,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 +127,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)) 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/state/DeviceDirectoryState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/DeviceDirectoryState.ets index 0c512a258b..e0f598c374 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 @@ -37,6 +37,7 @@ export class WorkspaceDirectoryState { export class DeviceDirectoryEntry { @Trace deviceId: string = ''; @Trace deviceName: string = ''; + @Trace deviceAlias: string | null | undefined = undefined; @Trace online: boolean = false; @Trace status: DeviceDirectoryStatus = 'idle'; @Trace errorText: string = ''; @@ -44,6 +45,10 @@ 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. */ 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..fe75071f0d 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,7 @@ export class DeviceDirectoryViewModel { return { deviceId: item.deviceId, deviceName: item.deviceName, + deviceAlias: item.deviceAlias, online: item.online }; })); @@ -256,6 +257,7 @@ export class DeviceDirectoryViewModel { const existing = this.state.find(device.deviceId); if (existing) { existing.deviceName = device.deviceName || existing.deviceName; + existing.deviceAlias = device.deviceAlias; if (existing.online && !online) { this.inFlight.delete(device.deviceId); if (existing.status === 'loading') existing.status = 'idle'; @@ -268,6 +270,7 @@ export class DeviceDirectoryViewModel { device.deviceName || device.deviceId, online ); + created.deviceAlias = device.deviceAlias; 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..39e3f4bff0 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'; @@ -295,6 +296,7 @@ export class SettingsController { 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, lastSeenAt: device.lastSeenAt, online: ids.includes(device.deviceId) })); const cloud = this.requireCloud(); @@ -440,6 +442,16 @@ export class SettingsController { if (this.cloudSession !== session) throw new Error('Account changed while loading devices'); 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 +544,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 +555,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 +639,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 +660,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 +674,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..b4f28adad1 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,58 @@ 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 }, + ]; + 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'); + + 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(); +}); 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..e9394cc738 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,22 @@ 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('alias refresh and removal update the sidebar without replacing its 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 }; + 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'); + f.vm.syncDevices([{ ...device, deviceAlias: null }]); + 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 From ac5558b62affb690a59ab5d6d6cf865289e892e0 Mon Sep 17 00:00:00 2001 From: guantw Date: Wed, 11 Nov 2026 15:37:50 +0900 Subject: [PATCH 2/3] fix(harmonyos): share live device state across account pages Settings and connection pages kept private device snapshots after background presence updates changed the sidebar. Read the shared observable directory in both pages and preserve device metadata while refreshing its rows. --- .../pages/components/AccountProfilePanel.ets | 13 +++++++------ .../components/AppRootOverlaySurfaces.ets | 4 ++++ .../pages/components/AppRootPresentation.ets | 2 ++ .../components/ConnectAccountDevicePage.ets | 11 ++++++----- .../main/ets/pages/components/ConnectView.ets | 3 +++ .../ets/pages/components/SettingsSheet.ets | 3 +++ .../pages/preview/ImmersiveBottomPreview.ets | 19 ++++++++++--------- .../ets/pages/state/DeviceDirectoryState.ets | 7 +++++-- .../viewmodel/DeviceDirectoryViewModel.ets | 9 +++++++++ .../pages/viewmodel/SettingsController.ets | 1 + .../tools/tests/account-restore.test.cjs | 3 ++- .../tests/device-directory-lifecycle.test.cjs | 11 +++++++++-- 12 files changed, 61 insertions(+), 25 deletions(-) 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 ba1d0e0ef0..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 @@ -3,6 +3,7 @@ import { RemoteI18n } from '../../i18n/RemoteI18n'; 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) { @@ -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 9ebbc51ad7..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 @@ -3,10 +3,12 @@ import { RemoteI18n } from '../../i18n/RemoteI18n'; 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() @@ -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/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 e0f598c374..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. */ @@ -38,6 +38,9 @@ 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 = ''; @@ -51,7 +54,7 @@ export class DeviceDirectoryEntry { } } -/** 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 fe75071f0d..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 @@ -91,6 +91,9 @@ export class DeviceDirectoryViewModel { deviceId: item.deviceId, deviceName: item.deviceName, deviceAlias: item.deviceAlias, + deviceKind: item.deviceKind, + lastSeenAt: item.lastSeenAt, + compatible: item.compatible, online: item.online }; })); @@ -258,6 +261,9 @@ export class DeviceDirectoryViewModel { 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'; @@ -271,6 +277,9 @@ export class DeviceDirectoryViewModel { 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 39e3f4bff0..c735370c0d 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 @@ -297,6 +297,7 @@ export class SettingsController { 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(); 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 b4f28adad1..4f3e6410b1 100644 --- a/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs @@ -68,7 +68,7 @@ test('directory refresh and presence retain aliases in the selected and preferre let published; const client = new account.CloudAccountClient(); client.request = async () => [ - { device_id: 'desktop', device_name: 'Studio Mac', device_alias: alias, online: true }, + { device_id: 'desktop', device_name: 'Studio Mac', device_alias: alias, online: true, compatible: false }, ]; client.observePresence = (_relay, _session, listener) => { onPresence = listener; return () => {}; }; const state = { @@ -90,6 +90,7 @@ test('directory refresh and presence retain aliases in the selected and preferre 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(); 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 e9394cc738..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 @@ -194,20 +194,27 @@ test('directory restores the active target and refresh preserves an explicit sel assert.equal(f.state.selectedDeviceId, 'other'); }); -test('alias refresh and removal update the sidebar without replacing its loaded directory', () => { +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 }; + 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'); From 6c916239d8437b81f4fed9897f8ae17048e7ac00 Mon Sep 17 00:00:00 2001 From: guantw Date: Wed, 11 Nov 2026 15:38:06 +0900 Subject: [PATCH 3/3] fix(harmonyos): preserve newer presence during device refresh A delayed device-list response could replace online or offline status received while the request was in flight. Apply the newer presence snapshot to the response while retaining refreshed device metadata; later HTTP reads can still recover from missed events. --- .../pages/viewmodel/SettingsController.ets | 12 ++++++ .../tools/tests/account-restore.test.cjs | 38 +++++++++++++++++++ 2 files changed, 50 insertions(+) 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 c735370c0d..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 @@ -75,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; @@ -293,6 +294,7 @@ 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, @@ -325,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; @@ -438,9 +441,18 @@ 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 => 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 4f3e6410b1..1a74b4408f 100644 --- a/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/account-restore.test.cjs @@ -102,3 +102,41 @@ test('directory refresh and presence retain aliases in the selected and preferre 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(); + }); +}